Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

editor.js 16 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. // MIT License. See license.txt
  3. /* Inspired from: http://github.com/mindmup/bootstrap-wysiwyg */
  4. // todo
  5. // make it inline friendly
  6. bsEditor = Class.extend({
  7. init: function(options) {
  8. this.options = $.extend(options || {}, this.default_options);
  9. if(this.options.editor) {
  10. this.setup_editor(this.options.editor);
  11. this.setup_fixed_toolbar();
  12. } else if(this.options.parent) {
  13. this.wrapper = $("<div></div>").appendTo(this.options.parent);
  14. this.setup_editor($("<div class='wn-editor'></div>").appendTo(this.wrapper));
  15. this.setup_inline_toolbar();
  16. this.editor.css(this.options.inline_editor_style);
  17. this.set_editing();
  18. }
  19. },
  20. setup_editor: function(editor) {
  21. var me = this;
  22. this.editor = $(editor);
  23. this.editor.on("click", function() {
  24. if(!me.editing) {
  25. me.set_editing();
  26. }
  27. }).on("mouseup keyup mouseout", function() {
  28. if(me.editing) {
  29. me.toolbar.save_selection();
  30. me.toolbar.update();
  31. me.options.change && me.options.change(me.clean_html());
  32. }
  33. }).data("object", this);
  34. this.bind_hotkeys();
  35. this.init_file_drops();
  36. },
  37. set_editing: function() {
  38. this.editor.attr('contenteditable', true);
  39. this.original_html = this.editor.html();
  40. this.toolbar.show();
  41. if(this.options.editor)
  42. this.toolbar.editor = this.editor.focus();
  43. this.editing = true;
  44. },
  45. setup_fixed_toolbar: function() {
  46. if(!window.bs_editor_toolbar) {
  47. window.bs_editor_toolbar = new bsEditorToolbar(this.options)
  48. }
  49. this.toolbar = window.bs_editor_toolbar;
  50. },
  51. setup_inline_toolbar: function() {
  52. this.toolbar = new bsEditorToolbar(this.options, this.wrapper, this.editor);
  53. },
  54. onhide: function(action) {
  55. this.editing = false;
  56. if(action==="Cancel") {
  57. this.editor.html(this.original_html);
  58. this.options.oncancel && this.options.oncancel(this);
  59. } else {
  60. this.options.onsave && this.options.onsave(this);
  61. this.options.change && this.options.change(this.get_value());
  62. }
  63. },
  64. default_options: {
  65. hotKeys: {
  66. 'ctrl+b meta+b': 'bold',
  67. 'ctrl+i meta+i': 'italic',
  68. 'ctrl+u meta+u': 'underline',
  69. 'ctrl+z meta+z': 'undo',
  70. 'ctrl+y meta+y meta+shift+z': 'redo',
  71. 'ctrl+l meta+l': 'justifyleft',
  72. 'ctrl+e meta+e': 'justifycenter',
  73. 'ctrl+j meta+j': 'justifyfull',
  74. 'shift+tab': 'outdent',
  75. 'tab': 'indent'
  76. },
  77. inline_editor_style: {
  78. "height": "400px",
  79. "background-color": "white",
  80. "border-collapse": "separate",
  81. "border": "1px solid rgb(204, 204, 204)",
  82. "padding": "4px",
  83. "box-sizing": "content-box",
  84. "-webkit-box-shadow": "rgba(0, 0, 0, 0.0745098) 0px 1px 1px 0px inset",
  85. "box-shadow": "rgba(0, 0, 0, 0.0745098) 0px 1px 1px 0px inset",
  86. "border-radius": "3px",
  87. "overflow": "scroll",
  88. "outline": "none"
  89. },
  90. toolbar_selector: '[data-role=editor-toolbar]',
  91. command_role: 'edit',
  92. active_toolbar_class: 'btn-info',
  93. selection_marker: 'edit-focus-marker',
  94. selection_color: 'darkgrey',
  95. remove_typography: true,
  96. max_file_size: 1,
  97. },
  98. bind_hotkeys: function () {
  99. var me = this;
  100. $.each(this.options.hotKeys, function (hotkey, command) {
  101. me.editor.keydown(hotkey, function (e) {
  102. if (me.editor.attr('contenteditable') && me.editor.is(':visible')) {
  103. e.preventDefault();
  104. e.stopPropagation();
  105. me.toolbar.execCommand(command);
  106. }
  107. }).keyup(hotkey, function (e) {
  108. if (me.editor.attr('contenteditable') && me.editor.is(':visible')) {
  109. e.preventDefault();
  110. e.stopPropagation();
  111. }
  112. });
  113. });
  114. },
  115. clean_html: function() {
  116. var html = this.editor.html() || "";
  117. html = html.replace(/(<br>|\s|<div><br><\/div>|&nbsp;)*$/, '');
  118. // remove custom typography (use CSS!)
  119. if(this.options.remove_typography) {
  120. html = html.replace(/(font-family|font-size|line-height):[^;]*;/g, '');
  121. html = html.replace(/<[^>]*(font=['"][^'"]*['"])>/g, function(a,b) { return a.replace(b, ''); });
  122. html = html.replace(/\s*style\s*=\s*["']\s*["']/g, '');
  123. return html;
  124. }
  125. },
  126. init_file_drops: function () {
  127. var me = this;
  128. this.editor.on('dragenter dragover', false)
  129. .on('drop', function (e) {
  130. var dataTransfer = e.originalEvent.dataTransfer;
  131. e.stopPropagation();
  132. e.preventDefault();
  133. if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
  134. me.insert_files(dataTransfer.files);
  135. }
  136. });
  137. },
  138. insert_files: function (files) {
  139. var me = this;
  140. this.editor.focus();
  141. $.each(files, function (i, file) {
  142. if (/^image\//.test(file.type)) {
  143. me.get_image(file, function(image_url) {
  144. me.toolbar.execCommand('insertimage', image_url);
  145. })
  146. }
  147. });
  148. },
  149. get_image: function (fileobj, callback) {
  150. var freader = new FileReader(),
  151. me = this;
  152. freader.onload = function() {
  153. var dataurl = freader.result;
  154. // add filename to dataurl
  155. var parts = dataurl.split(",");
  156. parts[0] += ";filename=" + fileobj.name;
  157. dataurl = parts[0] + ',' + parts[1];
  158. if(me.options.max_file_size) {
  159. if(dataurl.length > (me.options.max_file_size * 1024 * 1024 * 1.4)) {
  160. bs_get_modal("Upload Error", "Max file size (" + me.options.max_file_size + "M) exceeded.").modal("show");
  161. throw "file size exceeded";
  162. }
  163. }
  164. callback(dataurl);
  165. }
  166. freader.readAsDataURL(fileobj);
  167. },
  168. get_value: function() {
  169. return this.clean_html()
  170. },
  171. set_input: function(value) {
  172. if(this.options.field && this.options.field.inside_change_event)
  173. return;
  174. this.editor.html(value==null ? "" : value);
  175. }
  176. })
  177. bsEditorToolbar = Class.extend({
  178. init: function(options, parent, editor) {
  179. this.options = options;
  180. this.editor = editor;
  181. this.inline = !!parent;
  182. this.options.toolbar_style = $.extend((this.inline ? this.inline_style : this.fixed_style),
  183. this.options.toolbar_style || {});
  184. this.make(parent);
  185. this.toolbar.css(this.options.toolbar_style);
  186. this.setup_image_button();
  187. this.bind_events();
  188. //this.bind_touch();
  189. },
  190. fixed_style: {
  191. position: "fixed",
  192. top: "0px",
  193. padding: "5px",
  194. width: "100%",
  195. height: "45px",
  196. "background-color": "black",
  197. display: "none"
  198. },
  199. inline_style: {
  200. padding: "5px",
  201. },
  202. make: function(parent) {
  203. if(!parent)
  204. parent = $("body");
  205. if(!parent.find(".wn-editor-toolbar").length) {
  206. this.toolbar = $('<div class="wn-editor-toolbar wn-ignore-click">\
  207. <div class="btn-toolbar" data-role="editor-toolbar" style="margin-bottom: 7px;">\
  208. <div class="btn-group form-group">\
  209. <a class="btn btn-default btn-small dropdown-toggle" data-toggle="dropdown" \
  210. title="Font Size"><i class="icon-text-height"></i> <b class="caret"></b></a>\
  211. <ul class="dropdown-menu" role="menu">\
  212. <li><a href="#" data-edit="formatBlock &lt;p&gt;"><p>Paragraph</p></a></li>\
  213. <li><a href="#" data-edit="formatBlock &lt;h1&gt;"><h1>Heading 1</h1></a></li>\
  214. <li><a href="#" data-edit="formatBlock &lt;h2&gt;"><h2>Heading 2</h2></a></li>\
  215. <li><a href="#" data-edit="formatBlock &lt;h3&gt;"><h3>Heading 3</h3></a></li>\
  216. <li><a href="#" data-edit="formatBlock &lt;h4&gt;"><h4>Heading 4</h4></a></li>\
  217. <li><a href="#" data-edit="formatBlock &lt;h5&gt;"><h5>Heading 5</h5></a></li>\
  218. </ul>\
  219. </div>\
  220. <div class="btn-group form-group">\
  221. <a class="btn btn-default btn-small" data-edit="bold" title="Bold (Ctrl/Cmd+B)">\
  222. <i class="icon-bold"></i></a>\
  223. <a class="btn btn-default btn-small" data-edit="insertunorderedlist" title="Bullet list">\
  224. <i class="icon-list-ul"></i></a>\
  225. <a class="btn btn-default btn-small" data-edit="insertorderedlist" title="Number list">\
  226. <i class="icon-list-ol"></i></a>\
  227. <a class="btn btn-default btn-small" data-edit="outdent" title="Reduce indent (Shift+Tab)">\
  228. <i class="icon-indent-left"></i></a>\
  229. <a class="btn btn-default btn-small" data-edit="indent" title="Indent (Tab)">\
  230. <i class="icon-indent-right"></i></a>\
  231. </div>\
  232. <div class="btn-group hidden-xs form-group">\
  233. <a class="btn btn-default btn-small" data-edit="justifyleft" title="Align Left (Ctrl/Cmd+L)">\
  234. <i class="icon-align-left"></i></a>\
  235. <a class="btn btn-default btn-small" data-edit="justifycenter" title="Center (Ctrl/Cmd+E)">\
  236. <i class="icon-align-center"></i></a>\
  237. <a class="btn btn-default btn-small btn-add-link" title="Insert Link">\
  238. <i class="icon-link"></i></a>\
  239. <a class="btn btn-default btn-small" title="Remove Link" data-edit="unlink">\
  240. <i class="icon-unlink"></i></a>\
  241. <a class="btn btn-default btn-small btn-insert-img" title="Insert picture (or just drag & drop)">\
  242. <i class="icon-picture"></i></a>\
  243. <a class="btn btn-default btn-small" data-edit="insertHorizontalRule" \
  244. title="Horizontal Line Break">─</a>\
  245. </div>\
  246. <div class="btn-group form-group">\
  247. <a class="btn btn-default btn-small btn-html" title="HTML">\
  248. <i class="icon-code"></i></a>\
  249. <a class="btn btn-default btn-small btn-cancel" data-action="Cancel" title="Cancel">\
  250. <i class="icon-remove"></i></a>\
  251. <a class="btn btn-default btn-small btn-success" data-action="Save" title="Save">\
  252. <i class="icon-save"></i></a>\
  253. </div>\
  254. <input type="file" data-edit="insertImage" />\
  255. </div>').prependTo(parent);
  256. if(this.inline) {
  257. this.toolbar.find("[data-action]").remove();
  258. } else {
  259. this.toolbar.find(".btn-toolbar").addClass("container");
  260. }
  261. }
  262. },
  263. setup_image_button: function() {
  264. // magic-overlay
  265. var me = this;
  266. this.file_input = this.toolbar.find('input[type="file"]')
  267. .css({
  268. 'opacity':0,
  269. 'position':'absolute',
  270. 'left':0,
  271. 'width':0,
  272. 'height':0
  273. });
  274. this.toolbar.find(".btn-insert-img").on("click", function() {
  275. me.file_input.trigger("click");
  276. })
  277. },
  278. show: function() {
  279. var me = this;
  280. this.toolbar.toggle(true);
  281. if(!this.inline) {
  282. $("body").animate({"padding-top": this.toolbar.outerHeight() }, {
  283. complete: function() { me.toolbar.css("z-index", 1001); }
  284. });
  285. }
  286. },
  287. hide: function(action) {
  288. if(!this.editor)
  289. return;
  290. var me = this;
  291. this.toolbar.css("z-index", 0);
  292. if(!this.inline) {
  293. $("body").animate({"padding-top": 0 }, {complete: function() {
  294. me.toolbar.toggle(false);
  295. }});
  296. }
  297. this.editor && this.editor.attr('contenteditable', false).data("object").onhide(action);
  298. this.editor = null;
  299. },
  300. bind_events: function () {
  301. var me = this;
  302. // standard button events
  303. this.toolbar.find('a[data-' + me.options.command_role + ']').click(function () {
  304. me.restore_selection();
  305. me.editor.focus();
  306. me.execCommand($(this).data(me.options.command_role));
  307. me.save_selection();
  308. // close dropdown
  309. if(me.toolbar.find("ul.dropdown-menu:visible").length)
  310. me.toolbar.find('[data-toggle="dropdown"]').dropdown("toggle");
  311. return false;
  312. });
  313. this.toolbar.find('[data-toggle=dropdown]').click(function() { me.restore_selection() });
  314. // link
  315. this.toolbar.find(".btn-add-link").on("click", function() {
  316. if(!window.bs_link_editor) {
  317. window.bs_link_editor = new bsLinkEditor(me);
  318. }
  319. window.bs_link_editor.show();
  320. })
  321. // file event
  322. this.toolbar.find('input[type=file][data-' + me.options.command_role + ']').change(function () {
  323. me.restore_selection();
  324. if (this.type === 'file' && this.files && this.files.length > 0) {
  325. me.editor.data("object").insert_files(this.files);
  326. }
  327. me.save_selection();
  328. this.value = '';
  329. return false;
  330. });
  331. // save
  332. this.toolbar.find("[data-action='Save']").on("click", function() {
  333. me.hide("Save");
  334. })
  335. // cancel
  336. this.toolbar.find("[data-action='Cancel']").on("click", function() {
  337. me.hide("Cancel");
  338. })
  339. // edit html
  340. this.toolbar.find(".btn-html").on("click", function() {
  341. if(!window.bs_html_editor)
  342. window.bs_html_editor = new bsHTMLEditor();
  343. window.bs_html_editor.show(me.editor);
  344. })
  345. },
  346. update: function () {
  347. var me = this;
  348. if (this.toolbar) {
  349. $(this.toolbar).find('.btn[data-' + this.options.command_role + ']').each(function () {
  350. var command = $(this).data(me.options.command_role);
  351. if (document.queryCommandState(command)) {
  352. $(this).addClass(me.options.active_toolbar_class);
  353. } else {
  354. $(this).removeClass(me.options.active_toolbar_class);
  355. }
  356. });
  357. }
  358. },
  359. execCommand: function (commandWithArgs, valueArg) {
  360. var commandArr = commandWithArgs.split(' '),
  361. command = commandArr.shift(),
  362. args = commandArr.join(' ') + (valueArg || '');
  363. document.execCommand(command, 0, args);
  364. this.update();
  365. },
  366. get_current_range: function () {
  367. var sel = window.getSelection();
  368. if (sel.getRangeAt && sel.rangeCount) {
  369. return sel.getRangeAt(0);
  370. }
  371. },
  372. save_selection: function () {
  373. this.selected_range = this.get_current_range();
  374. },
  375. restore_selection: function () {
  376. var selection = window.getSelection();
  377. if (this.selected_range) {
  378. selection.removeAllRanges();
  379. selection.addRange(this.selected_range);
  380. }
  381. },
  382. mark_selection: function (input, color) {
  383. this.restore_selection();
  384. document.execCommand('hiliteColor', 0, color || 'transparent');
  385. this.save_selection();
  386. input.data(this.options.selection_marker, color);
  387. },
  388. // bind_touch: function() {
  389. // var me = this;
  390. // $(window).bind('touchend', function (e) {
  391. // var isInside = (me.editor.is(e.target) || me.editor.has(e.target).length > 0),
  392. // current_range = me.get_current_range(),
  393. // clear = current_range && (current_range.startContainer === current_range.endContainer && current_range.startOffset === current_range.endOffset);
  394. // if (!clear || isInside) {
  395. // me.save_selection();
  396. // me.update();
  397. // }
  398. // });
  399. // }
  400. });
  401. bsHTMLEditor = Class.extend({
  402. init: function() {
  403. var me = this;
  404. this.modal = bs_get_modal("<i class='icon-code'></i> Edit HTML", '<textarea class="form-control" \
  405. style="height: 400px; width: 100%; font-family: Monaco, Courier New, Fixed; font-size: 11px">\
  406. </textarea><br>\
  407. <button class="btn btn-primary" style="margin-top: 7px;">Save</button>');
  408. this.modal.addClass("wn-ignore-click");
  409. this.modal.find(".btn-primary").on("click", function() {
  410. var html = me.modal.find("textarea").val();
  411. $.each(me.dataurls, function(key, val) {
  412. html = html.replace(key, val);
  413. })
  414. me.editor.html(html);
  415. me.modal.modal("hide");
  416. });
  417. },
  418. show: function(editor) {
  419. var me = this;
  420. this.editor = editor;
  421. this.modal.modal("show")
  422. var html = me.editor.html();
  423. // pack dataurls so that html display is faster
  424. this.dataurls = {}
  425. html = html.replace(/<img\s*src=\s*["\'](data:[^,]*),([^"\']*)["\']/g, function(full, g1, g2) {
  426. var key = g2.slice(0,5) + "..." + g2.slice(-5);
  427. me.dataurls[key] = g1 + "," + g2;
  428. return '<img src="'+g1 + "," + key+'"';
  429. })
  430. this.modal.find("textarea").html(html_beautify(html));
  431. }
  432. });
  433. bsLinkEditor = Class.extend({
  434. init: function(toolbar) {
  435. var me = this;
  436. this.toolbar = toolbar;
  437. this.modal = bs_get_modal("<i class='icon-globe'></i> Insert Link", '<div class="form-group">\
  438. <input type="text" class="form-control" placeholder="http://example.com" />\
  439. </div>\
  440. <div class="checkbox" style="position: static;">\
  441. <label>\
  442. <input type="checkbox"> <span>Open Link in a new Window</span>\
  443. </label>\
  444. </div>\
  445. <button class="btn btn-primary" style="margin-top: 7px;">Insert</button>');
  446. this.modal.addClass("wn-ignore-click");
  447. this.modal.find(".btn-primary").on("click", function() {
  448. me.toolbar.restore_selection();
  449. var url = me.modal.find("input[type=text]").val();
  450. var selection = me.toolbar.selected_range.toString();
  451. if(url) {
  452. if(me.modal.find("input[type=checkbox]:checked").length) {
  453. var html = "<a href='" + url + "' target='_blank'>" + selection + "</a>";
  454. document.execCommand("insertHTML", false, html);
  455. } else {
  456. document.execCommand("CreateLink", false, url);
  457. }
  458. }
  459. me.modal.modal("hide");
  460. return false;
  461. });
  462. },
  463. show: function() {
  464. this.modal.find("input[type=text]").val("");
  465. this.modal.modal("show");
  466. }
  467. });
  468. bs_get_modal = wn.get_modal;