bootstrap-markdown.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. (function (factory) {
  2. if (typeof define === "function" && define.amd) {
  3. define(["jquery"], factory)
  4. } else if (typeof exports === "object") {
  5. factory(require("jquery"))
  6. } else {
  7. factory(jQuery)
  8. }
  9. })(function ($) {
  10. "use strict";
  11. var Markdown = function (element, options) {
  12. var opts = ["autofocus", "savable", "hideable", "width", "height", "resize", "iconlibrary", "language", "footer", "fullscreen", "hiddenButtons", "disabledButtons"];
  13. $.each(opts, function (_, opt) {
  14. if (typeof $(element).data(opt) !== "undefined") {
  15. options = typeof options == "object" ? options : {};
  16. options[opt] = $(element).data(opt)
  17. }
  18. });
  19. this.$ns = "bootstrap-markdown";
  20. this.$element = $(element);
  21. this.$editable = {el: null, type: null, attrKeys: [], attrValues: [], content: null};
  22. this.$options = $.extend(true, {}, $.fn.markdown.defaults, options, this.$element.data("options"));
  23. this.$oldContent = null;
  24. this.$isPreview = false;
  25. this.$isFullscreen = false;
  26. this.$editor = null;
  27. this.$textarea = null;
  28. this.$handler = [];
  29. this.$callback = [];
  30. this.$nextTab = [];
  31. this.showEditor()
  32. };
  33. Markdown.prototype = {
  34. constructor: Markdown, __alterButtons: function (name, alter) {
  35. var handler = this.$handler, isAll = name == "all", that = this;
  36. $.each(handler, function (k, v) {
  37. var halt = true;
  38. if (isAll) {
  39. halt = false
  40. } else {
  41. halt = v.indexOf(name) < 0
  42. }
  43. if (halt === false) {
  44. alter(that.$editor.find('button[data-handler="' + v + '"]'))
  45. }
  46. })
  47. }, __buildButtons: function (buttonsArray, container) {
  48. var i, ns = this.$ns, handler = this.$handler, callback = this.$callback;
  49. for (i = 0; i < buttonsArray.length; i++) {
  50. var y, btnGroups = buttonsArray[i];
  51. for (y = 0; y < btnGroups.length; y++) {
  52. var z, buttons = btnGroups[y].data, btnGroupContainer = $("<div/>", {class: "btn-group"});
  53. for (z = 0; z < buttons.length; z++) {
  54. var button = buttons[z], buttonContainer, buttonIconContainer, buttonHandler = ns + "-" + button.name, buttonIcon = this.__getIcon(button.icon), btnText = button.btnText ? button.btnText : "", btnClass = button.btnClass ? button.btnClass : "btn", tabIndex = button.tabIndex ? button.tabIndex : "-1", hotkey = typeof button.hotkey !== "undefined" ? button.hotkey : "", hotkeyCaption = typeof jQuery.hotkeys !== "undefined" && hotkey !== "" ? " (" + hotkey + ")" : "";
  55. buttonContainer = $("<button></button>");
  56. buttonContainer.text(" " + this.__localize(btnText)).addClass("btn-light").addClass(btnClass);
  57. if (btnClass.match(/btn\-(primary|success|info|warning|danger|link)/)) {
  58. buttonContainer.removeClass("btn-light")
  59. }
  60. buttonContainer.attr({type: "button", title: this.__localize(button.title) + hotkeyCaption, tabindex: tabIndex, "data-provider": ns, "data-handler": buttonHandler, "data-hotkey": hotkey});
  61. if (button.toggle === true) {
  62. buttonContainer.attr("data-toggle", "button")
  63. }
  64. buttonIconContainer = $("<span/>");
  65. buttonIconContainer.addClass(buttonIcon);
  66. buttonIconContainer.prependTo(buttonContainer);
  67. btnGroupContainer.addClass("mr-2");
  68. btnGroupContainer.append(buttonContainer);
  69. handler.push(buttonHandler);
  70. callback.push(button.callback)
  71. }
  72. container.append(btnGroupContainer)
  73. }
  74. }
  75. return container
  76. }, __setListener: function () {
  77. var hasRows = typeof this.$textarea.attr("rows") !== "undefined", maxRows = this.$textarea.val().split("\n").length > 5 ? this.$textarea.val().split("\n").length : "5", rowsVal = hasRows ? this.$textarea.attr("rows") : maxRows;
  78. this.$textarea.attr("rows", rowsVal);
  79. if (this.$options.resize) {
  80. this.$textarea.css("resize", this.$options.resize)
  81. }
  82. this.$textarea.on({focus: $.proxy(this.focus, this), keyup: $.proxy(this.keyup, this), change: $.proxy(this.change, this), select: $.proxy(this.select, this)});
  83. if (this.eventSupported("keydown")) {
  84. this.$textarea.on("keydown", $.proxy(this.keydown, this))
  85. }
  86. if (this.eventSupported("keypress")) {
  87. this.$textarea.on("keypress", $.proxy(this.keypress, this))
  88. }
  89. this.$textarea.data("markdown", this)
  90. }, __handle: function (e) {
  91. var target = $(e.currentTarget), handler = this.$handler, callback = this.$callback, handlerName = target.attr("data-handler"), callbackIndex = handler.indexOf(handlerName), callbackHandler = callback[callbackIndex];
  92. $(e.currentTarget).focus();
  93. callbackHandler(this);
  94. this.change(this);
  95. if (handlerName.indexOf("cmdSave") < 0) {
  96. this.$textarea.focus()
  97. }
  98. e.preventDefault()
  99. }, __localize: function (string) {
  100. var messages = $.fn.markdown.messages, language = this.$options.language;
  101. if (typeof messages !== "undefined" && typeof messages[language] !== "undefined" && typeof messages[language][string] !== "undefined") {
  102. return messages[language][string]
  103. }
  104. return string
  105. }, __getIcon: function (src) {
  106. return typeof src == "object" ? src[this.$options.iconlibrary] : src
  107. }, setFullscreen: function (mode) {
  108. var $editor = this.$editor, $textarea = this.$textarea;
  109. if (mode === true) {
  110. $editor.addClass("md-fullscreen-mode");
  111. $("body").addClass("md-nooverflow");
  112. this.$options.onFullscreen(this)
  113. } else {
  114. $editor.removeClass("md-fullscreen-mode");
  115. $("body").removeClass("md-nooverflow");
  116. if (this.$isPreview == true) this.hidePreview().showPreview()
  117. }
  118. this.$isFullscreen = mode;
  119. $textarea.focus()
  120. }, showEditor: function () {
  121. var instance = this, textarea, ns = this.$ns, container = this.$element, originalHeigth = container.css("height"), originalWidth = container.css("width"), editable = this.$editable, handler = this.$handler, callback = this.$callback, options = this.$options, editor = $("<div/>", {
  122. class: "md-editor", click: function () {
  123. instance.focus()
  124. }
  125. });
  126. if (this.$editor === null) {
  127. var editorHeader = $("<div/>", {class: "md-header btn-toolbar"});
  128. var allBtnGroups = [];
  129. if (options.buttons.length > 0) allBtnGroups = allBtnGroups.concat(options.buttons[0]);
  130. if (options.additionalButtons.length > 0) {
  131. $.each(options.additionalButtons[0], function (idx, buttonGroup) {
  132. var matchingGroups = $.grep(allBtnGroups, function (allButtonGroup, allIdx) {
  133. return allButtonGroup.name === buttonGroup.name
  134. });
  135. if (matchingGroups.length > 0) {
  136. matchingGroups[0].data = matchingGroups[0].data.concat(buttonGroup.data)
  137. } else {
  138. allBtnGroups.push(options.additionalButtons[0][idx])
  139. }
  140. })
  141. }
  142. if (options.reorderButtonGroups.length > 0) {
  143. allBtnGroups = allBtnGroups.filter(function (btnGroup) {
  144. return options.reorderButtonGroups.indexOf(btnGroup.name) > -1
  145. }).sort(function (a, b) {
  146. if (options.reorderButtonGroups.indexOf(a.name) < options.reorderButtonGroups.indexOf(b.name)) return -1;
  147. if (options.reorderButtonGroups.indexOf(a.name) > options.reorderButtonGroups.indexOf(b.name)) return 1;
  148. return 0
  149. })
  150. }
  151. if (allBtnGroups.length > 0) {
  152. editorHeader = this.__buildButtons([allBtnGroups], editorHeader)
  153. }
  154. if (options.fullscreen.enable) {
  155. editorHeader.append('<div class="md-controls"><a class="md-control md-control-fullscreen" href="#"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOn) + '"></span></a></div>').on("click", ".md-control-fullscreen", function (e) {
  156. e.preventDefault();
  157. instance.setFullscreen(true)
  158. })
  159. }
  160. editor.append(editorHeader);
  161. if (container.is("textarea")) {
  162. container.before(editor);
  163. textarea = container;
  164. textarea.addClass("md-input");
  165. editor.append(textarea)
  166. } else {
  167. var rawContent = typeof toMarkdown == "function" ? toMarkdown(container.html()) : container.html(), currentContent = $.trim(rawContent);
  168. textarea = $("<textarea/>", {class: "md-input", val: currentContent});
  169. editor.append(textarea);
  170. editable.el = container;
  171. editable.type = container.prop("tagName").toLowerCase();
  172. editable.content = container.html();
  173. $(container[0].attributes).each(function () {
  174. editable.attrKeys.push(this.nodeName);
  175. editable.attrValues.push(this.nodeValue)
  176. });
  177. container.replaceWith(editor)
  178. }
  179. var editorFooter = $("<div/>", {class: "md-footer"}), createFooter = false, footer = "";
  180. if (options.savable) {
  181. createFooter = true;
  182. var saveHandler = "cmdSave";
  183. handler.push(saveHandler);
  184. callback.push(options.onSave);
  185. editorFooter.append('<button class="btn btn-success" data-provider="' + ns + '" data-handler="' + saveHandler + '"><i class="icon icon-white icon-ok"></i> ' + this.__localize("Save") + "</button>")
  186. }
  187. footer = typeof options.footer === "function" ? options.footer(this) : options.footer;
  188. if ($.trim(footer) !== "") {
  189. createFooter = true;
  190. editorFooter.append(footer)
  191. }
  192. if (createFooter) editor.append(editorFooter);
  193. if (options.width && options.width !== "inherit") {
  194. if (jQuery.isNumeric(options.width)) {
  195. editor.css("display", "table");
  196. textarea.css("width", options.width + "px")
  197. } else {
  198. editor.addClass(options.width)
  199. }
  200. }
  201. if (options.height && options.height !== "inherit") {
  202. if (jQuery.isNumeric(options.height)) {
  203. var height = options.height;
  204. if (editorHeader) height = Math.max(0, height - editorHeader.outerHeight());
  205. if (editorFooter) height = Math.max(0, height - editorFooter.outerHeight());
  206. textarea.css("height", height + "px")
  207. } else {
  208. editor.addClass(options.height)
  209. }
  210. }
  211. this.$editor = editor;
  212. this.$textarea = textarea;
  213. this.$editable = editable;
  214. this.$oldContent = this.getContent();
  215. this.__setListener();
  216. this.$editor.attr("id", (new Date).getTime());
  217. this.$editor.on("click", '[data-provider="bootstrap-markdown"]', $.proxy(this.__handle, this));
  218. if (this.$element.is(":disabled") || this.$element.is("[readonly]")) {
  219. this.$editor.addClass("md-editor-disabled");
  220. this.disableButtons("all")
  221. }
  222. if (this.eventSupported("keydown") && typeof jQuery.hotkeys === "object") {
  223. editorHeader.find('[data-provider="bootstrap-markdown"]').each(function () {
  224. var $button = $(this), hotkey = $button.attr("data-hotkey");
  225. if (hotkey.toLowerCase() !== "") {
  226. textarea.bind("keydown", hotkey, function () {
  227. $button.trigger("click");
  228. return false
  229. })
  230. }
  231. })
  232. }
  233. if (options.initialstate === "preview") {
  234. this.showPreview()
  235. } else if (options.initialstate === "fullscreen" && options.fullscreen.enable) {
  236. this.setFullscreen(true)
  237. }
  238. } else {
  239. this.$editor.show()
  240. }
  241. if (options.autofocus) {
  242. this.$textarea.focus();
  243. this.$editor.addClass("active")
  244. }
  245. if (options.fullscreen.enable && options.fullscreen !== false) {
  246. this.$editor.append('<div class="md-fullscreen-controls">' + '<a href="#" class="exit-fullscreen" title="Exit fullscreen"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOff) + '">' + "</span></a>" + "</div>");
  247. this.$editor.on("click", ".exit-fullscreen", function (e) {
  248. e.preventDefault();
  249. instance.setFullscreen(false)
  250. })
  251. }
  252. this.hideButtons(options.hiddenButtons);
  253. this.disableButtons(options.disabledButtons);
  254. options.onShow(this);
  255. return this
  256. }, parseContent: function (val) {
  257. var content;
  258. var val = val || this.$textarea.val();
  259. if (this.$options.parser) {
  260. content = this.$options.parser(val)
  261. } else if (typeof markdown == "object") {
  262. content = markdown.toHTML(val)
  263. } else if (typeof marked == "function") {
  264. content = marked(val)
  265. } else {
  266. content = val
  267. }
  268. return content
  269. }, showPreview: function () {
  270. var options = this.$options, container = this.$textarea, afterContainer = container.next(), replacementContainer = $("<div/>", {class: "md-preview", "data-provider": "markdown-preview"}), content, callbackContent;
  271. if (this.$isPreview == true) {
  272. return this
  273. }
  274. this.$isPreview = true;
  275. this.disableButtons("all").enableButtons("cmdPreview");
  276. callbackContent = options.onPreview(this);
  277. content = typeof callbackContent == "string" ? callbackContent : this.parseContent();
  278. replacementContainer.html(content);
  279. if (afterContainer && afterContainer.attr("class") == "md-footer") {
  280. replacementContainer.insertBefore(afterContainer)
  281. } else {
  282. container.parent().append(replacementContainer)
  283. }
  284. replacementContainer.css({width: container.outerWidth() + "px", height: container.outerHeight() + "px"});
  285. if (this.$options.resize) {
  286. replacementContainer.css("resize", this.$options.resize)
  287. }
  288. container.hide();
  289. replacementContainer.data("markdown", this);
  290. if (this.$element.is(":disabled") || this.$element.is("[readonly]")) {
  291. this.$editor.addClass("md-editor-disabled");
  292. this.disableButtons("all")
  293. }
  294. return this
  295. }, hidePreview: function () {
  296. this.$isPreview = false;
  297. var container = this.$editor.find('div[data-provider="markdown-preview"]');
  298. container.remove();
  299. this.enableButtons("all");
  300. this.disableButtons(this.$options.disabledButtons);
  301. this.$textarea.show();
  302. this.__setListener();
  303. return this
  304. }, isDirty: function () {
  305. return this.$oldContent != this.getContent()
  306. }, getContent: function () {
  307. return this.$textarea.val()
  308. }, setContent: function (content) {
  309. this.$textarea.val(content);
  310. return this
  311. }, findSelection: function (chunk) {
  312. var content = this.getContent(), startChunkPosition;
  313. if (startChunkPosition = content.indexOf(chunk), startChunkPosition >= 0 && chunk.length > 0) {
  314. var oldSelection = this.getSelection(), selection;
  315. this.setSelection(startChunkPosition, startChunkPosition + chunk.length);
  316. selection = this.getSelection();
  317. this.setSelection(oldSelection.start, oldSelection.end);
  318. return selection
  319. } else {
  320. return null
  321. }
  322. }, getSelection: function () {
  323. var e = this.$textarea[0];
  324. return ("selectionStart" in e && function () {
  325. var l = e.selectionEnd - e.selectionStart;
  326. return {start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l)}
  327. } || function () {
  328. return null
  329. })()
  330. }, setSelection: function (start, end) {
  331. var e = this.$textarea[0];
  332. return ("selectionStart" in e && function () {
  333. e.selectionStart = start;
  334. e.selectionEnd = end;
  335. return
  336. } || function () {
  337. return null
  338. })()
  339. }, replaceSelection: function (text) {
  340. var e = this.$textarea[0];
  341. return ("selectionStart" in e && function () {
  342. e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
  343. e.selectionStart = e.value.length;
  344. return this
  345. } || function () {
  346. e.value += text;
  347. return jQuery(e)
  348. })()
  349. }, getNextTab: function () {
  350. if (this.$nextTab.length === 0) {
  351. return null
  352. } else {
  353. var nextTab, tab = this.$nextTab.shift();
  354. if (typeof tab == "function") {
  355. nextTab = tab()
  356. } else if (typeof tab == "object" && tab.length > 0) {
  357. nextTab = tab
  358. }
  359. return nextTab
  360. }
  361. }, setNextTab: function (start, end) {
  362. if (typeof start == "string") {
  363. var that = this;
  364. this.$nextTab.push(function () {
  365. return that.findSelection(start)
  366. })
  367. } else if (typeof start == "number" && typeof end == "number") {
  368. var oldSelection = this.getSelection();
  369. this.setSelection(start, end);
  370. this.$nextTab.push(this.getSelection());
  371. this.setSelection(oldSelection.start, oldSelection.end)
  372. }
  373. return
  374. }, __parseButtonNameParam: function (names) {
  375. return typeof names == "string" ? names.split(" ") : names
  376. }, enableButtons: function (name) {
  377. var buttons = this.__parseButtonNameParam(name), that = this;
  378. $.each(buttons, function (i, v) {
  379. that.__alterButtons(buttons[i], function (el) {
  380. el.removeAttr("disabled")
  381. })
  382. });
  383. return this
  384. }, disableButtons: function (name) {
  385. var buttons = this.__parseButtonNameParam(name), that = this;
  386. $.each(buttons, function (i, v) {
  387. that.__alterButtons(buttons[i], function (el) {
  388. el.attr("disabled", "disabled")
  389. })
  390. });
  391. return this
  392. }, hideButtons: function (name) {
  393. var buttons = this.__parseButtonNameParam(name), that = this;
  394. $.each(buttons, function (i, v) {
  395. that.__alterButtons(buttons[i], function (el) {
  396. el.prop("hidden", true)
  397. })
  398. });
  399. return this
  400. }, showButtons: function (name) {
  401. var buttons = this.__parseButtonNameParam(name), that = this;
  402. $.each(buttons, function (i, v) {
  403. that.__alterButtons(buttons[i], function (el) {
  404. el.removeProp("hidden")
  405. })
  406. });
  407. return this
  408. }, eventSupported: function (eventName) {
  409. var isSupported = eventName in this.$element;
  410. if (!isSupported) {
  411. this.$element.setAttribute(eventName, "return;");
  412. isSupported = typeof this.$element[eventName] === "function"
  413. }
  414. return isSupported
  415. }, keyup: function (e) {
  416. var blocked = false;
  417. switch (e.keyCode) {
  418. case 40:
  419. case 38:
  420. case 16:
  421. case 17:
  422. case 18:
  423. break;
  424. case 9:
  425. if (typeof tabOverride !== 'undefined') {
  426. break;
  427. }
  428. var nextTab;
  429. if (nextTab = this.getNextTab(), nextTab !== null) {
  430. var that = this;
  431. setTimeout(function () {
  432. that.setSelection(nextTab.start, nextTab.end)
  433. }, 500);
  434. blocked = true
  435. } else {
  436. var cursor = this.getSelection();
  437. if (cursor.start == cursor.end && cursor.end == this.getContent().length) {
  438. blocked = false
  439. } else {
  440. this.setSelection(this.getContent().length, this.getContent().length);
  441. blocked = true
  442. }
  443. }
  444. break;
  445. case 13:
  446. blocked = false;
  447. break;
  448. case 27:
  449. if (this.$isFullscreen) this.setFullscreen(false);
  450. blocked = false;
  451. break;
  452. default:
  453. blocked = false
  454. }
  455. if (blocked) {
  456. e.stopPropagation();
  457. e.preventDefault()
  458. }
  459. this.$options.onChange(this)
  460. }, change: function (e) {
  461. this.$options.onChange(this);
  462. return this
  463. }, select: function (e) {
  464. this.$options.onSelect(this);
  465. return this
  466. }, focus: function (e) {
  467. var options = this.$options, isHideable = options.hideable, editor = this.$editor;
  468. editor.addClass("active");
  469. $(document).find(".md-editor").each(function () {
  470. if ($(this).attr("id") !== editor.attr("id")) {
  471. var attachedMarkdown;
  472. if (attachedMarkdown = $(this).find("textarea").data("markdown"), attachedMarkdown === null) {
  473. attachedMarkdown = $(this).find('div[data-provider="markdown-preview"]').data("markdown")
  474. }
  475. if (attachedMarkdown) {
  476. attachedMarkdown.blur()
  477. }
  478. }
  479. });
  480. options.onFocus(this);
  481. return this
  482. }, blur: function (e) {
  483. var options = this.$options, isHideable = options.hideable, editor = this.$editor, editable = this.$editable;
  484. if (editor.hasClass("active") || this.$element.parent().length === 0) {
  485. editor.removeClass("active");
  486. if (isHideable) {
  487. if (editable.el !== null) {
  488. var oldElement = $("<" + editable.type + "/>"), content = this.getContent(), currentContent = this.parseContent(content);
  489. $(editable.attrKeys).each(function (k, v) {
  490. oldElement.attr(editable.attrKeys[k], editable.attrValues[k])
  491. });
  492. oldElement.html(currentContent);
  493. editor.replaceWith(oldElement)
  494. } else {
  495. editor.hide()
  496. }
  497. }
  498. options.onBlur(this)
  499. }
  500. return this
  501. }
  502. };
  503. var old = $.fn.markdown;
  504. $.fn.markdown = function (option) {
  505. return this.each(function () {
  506. var $this = $(this), data = $this.data("markdown"), options = typeof option == "object" && option;
  507. if (!data) $this.data("markdown", data = new Markdown(this, options))
  508. })
  509. };
  510. $.fn.markdown.messages = {};
  511. $.fn.markdown.defaults = {
  512. autofocus: false, hideable: false, savable: false, width: "inherit", height: "inherit", resize: "none", iconlibrary: "glyph", language: "en", initialstate: "editor", parser: null, buttons: [[{
  513. name: "groupFont", data: [{
  514. name: "cmdBold", hotkey: "Ctrl+B", title: "Bold", icon: {glyph: "glyphicon glyphicon-bold", fa: "fa fa-bold", "fa-3": "icon-bold"}, callback: function (e) {
  515. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  516. if (selected.length === 0) {
  517. chunk = e.__localize("strong text")
  518. } else {
  519. chunk = selected.text
  520. }
  521. if (content.substr(selected.start - 2, 2) === "**" && content.substr(selected.end, 2) === "**") {
  522. e.setSelection(selected.start - 2, selected.end + 2);
  523. e.replaceSelection(chunk);
  524. cursor = selected.start - 2
  525. } else {
  526. e.replaceSelection("**" + chunk + "**");
  527. cursor = selected.start + 2
  528. }
  529. e.setSelection(cursor, cursor + chunk.length)
  530. }
  531. }, {
  532. name: "cmdItalic", title: "Italic", hotkey: "Ctrl+I", icon: {glyph: "glyphicon glyphicon-italic", fa: "fa fa-italic", "fa-3": "icon-italic"}, callback: function (e) {
  533. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  534. if (selected.length === 0) {
  535. chunk = e.__localize("emphasized text")
  536. } else {
  537. chunk = selected.text
  538. }
  539. if (content.substr(selected.start - 1, 1) === "_" && content.substr(selected.end, 1) === "_") {
  540. e.setSelection(selected.start - 1, selected.end + 1);
  541. e.replaceSelection(chunk);
  542. cursor = selected.start - 1
  543. } else {
  544. e.replaceSelection("_" + chunk + "_");
  545. cursor = selected.start + 1
  546. }
  547. e.setSelection(cursor, cursor + chunk.length)
  548. }
  549. }, {
  550. name: "cmdHeading", title: "Heading", hotkey: "Ctrl+H", icon: {glyph: "glyphicon glyphicon-header", fa: "fa fa-header", "fa-3": "icon-font"}, callback: function (e) {
  551. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), pointer, prevChar;
  552. if (selected.length === 0) {
  553. chunk = e.__localize("heading text")
  554. } else {
  555. chunk = selected.text + "\n"
  556. }
  557. if ((pointer = 4, content.substr(selected.start - pointer, pointer) === "### ") || (pointer = 3, content.substr(selected.start - pointer, pointer) === "###")) {
  558. e.setSelection(selected.start - pointer, selected.end);
  559. e.replaceSelection(chunk);
  560. cursor = selected.start - pointer
  561. } else if (selected.start > 0 && (prevChar = content.substr(selected.start - 1, 1), !!prevChar && prevChar != "\n")) {
  562. e.replaceSelection("\n\n### " + chunk);
  563. cursor = selected.start + 6
  564. } else {
  565. e.replaceSelection("### " + chunk);
  566. cursor = selected.start + 4
  567. }
  568. e.setSelection(cursor, cursor + chunk.length)
  569. }
  570. }]
  571. }, {
  572. name: "groupLink", data: [{
  573. name: "cmdUrl", title: "URL/Link", hotkey: "Ctrl+L", icon: {glyph: "glyphicon glyphicon-link", fa: "fa fa-link", "fa-3": "icon-link"}, callback: function (e) {
  574. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
  575. if (selected.length === 0) {
  576. chunk = e.__localize("enter link description here")
  577. } else {
  578. chunk = selected.text
  579. }
  580. link = prompt(e.__localize("Insert Hyperlink"), "http://");
  581. var urlRegex = new RegExp("^((http|https)://|(mailto:)|(//))[a-z0-9]", "i");
  582. if (link !== null && link !== "" && link !== "http://" && urlRegex.test(link)) {
  583. var sanitizedLink = $("<div>" + link + "</div>").text();
  584. e.replaceSelection("[" + chunk + "](" + sanitizedLink + ")");
  585. cursor = selected.start + 1;
  586. e.setSelection(cursor, cursor + chunk.length)
  587. }
  588. }
  589. }, {
  590. name: "cmdImage", title: "Image", hotkey: "Ctrl+G", icon: {glyph: "glyphicon glyphicon-picture", fa: "fa fa-picture-o", "fa-3": "icon-image"}, callback: function (e) {
  591. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
  592. if (selected.length === 0) {
  593. chunk = e.__localize("enter image description here")
  594. } else {
  595. chunk = selected.text
  596. }
  597. link = prompt(e.__localize("Insert Image Hyperlink"), "http://");
  598. var urlRegex = new RegExp("^((http|https)://|(//))[a-z0-9]", "i");
  599. if (link !== null && link !== "" && link !== "http://" && urlRegex.test(link)) {
  600. var sanitizedLink = $("<div>" + link + "</div>").text();
  601. e.replaceSelection("![" + chunk + "](" + sanitizedLink + ' "' + e.__localize("enter image title here") + '")');
  602. cursor = selected.start + 2;
  603. e.setNextTab(e.__localize("enter image title here"));
  604. e.setSelection(cursor, cursor + chunk.length)
  605. }
  606. }
  607. }, {
  608. name: "cmdFile", title: "Attachment File", icon: {glyph: "glyphicon glyphicon-file", fa: "fa fa-file-archive-o", "fa-3": "icon-file"}, callback: function (e) {
  609. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
  610. if (selected.length === 0) {
  611. chunk = e.__localize("enter file description here")
  612. } else {
  613. chunk = selected.text
  614. }
  615. link = prompt(e.__localize("Insert File Hyperlink"), "http://");
  616. var urlRegex = new RegExp("^((http|https)://|(//))[a-z0-9]", "i");
  617. if (link !== null && link !== "" && link !== "http://" && urlRegex.test(link)) {
  618. var sanitizedLink = $("<div>" + link + "</div>").text();
  619. e.replaceSelection("[" + chunk + "](" + sanitizedLink + ' "' + e.__localize("enter file title here") + '")');
  620. cursor = selected.start + 2;
  621. e.setNextTab(e.__localize("enter file title here"));
  622. e.setSelection(cursor, cursor + chunk.length)
  623. }
  624. }
  625. }]
  626. }, {
  627. name: "groupMisc", data: [{
  628. name: "cmdList", hotkey: "Ctrl+U", title: "Unordered List", icon: {glyph: "glyphicon glyphicon-list", fa: "fa fa-list", "fa-3": "icon-list-ul"}, callback: function (e) {
  629. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  630. if (selected.length === 0) {
  631. chunk = e.__localize("list text here");
  632. e.replaceSelection("- " + chunk);
  633. cursor = selected.start + 2
  634. } else {
  635. if (selected.text.indexOf("\n") < 0) {
  636. chunk = selected.text;
  637. e.replaceSelection("- " + chunk);
  638. cursor = selected.start + 2
  639. } else {
  640. var list = [];
  641. list = selected.text.split("\n");
  642. chunk = list[0];
  643. $.each(list, function (k, v) {
  644. list[k] = "- " + v
  645. });
  646. e.replaceSelection("\n\n" + list.join("\n"));
  647. cursor = selected.start + 4
  648. }
  649. }
  650. e.setSelection(cursor, cursor + chunk.length)
  651. }
  652. }, {
  653. name: "cmdListO", hotkey: "Ctrl+O", title: "Ordered List", icon: {glyph: "glyphicon glyphicon-th-list", fa: "fa fa-list-ol", "fa-3": "icon-list-ol"}, callback: function (e) {
  654. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  655. if (selected.length === 0) {
  656. chunk = e.__localize("list text here");
  657. e.replaceSelection("1. " + chunk);
  658. cursor = selected.start + 3
  659. } else {
  660. if (selected.text.indexOf("\n") < 0) {
  661. chunk = selected.text;
  662. e.replaceSelection("1. " + chunk);
  663. cursor = selected.start + 3
  664. } else {
  665. var list = [];
  666. list = selected.text.split("\n");
  667. chunk = list[0];
  668. $.each(list, function (k, v) {
  669. list[k] = "1. " + v
  670. });
  671. e.replaceSelection("\n\n" + list.join("\n"));
  672. cursor = selected.start + 5
  673. }
  674. }
  675. e.setSelection(cursor, cursor + chunk.length)
  676. }
  677. }, {
  678. name: "cmdCode", hotkey: "Ctrl+K", title: "Code", icon: {glyph: "glyphicon glyphicon-asterisk", fa: "fa fa-code", "fa-3": "icon-code"}, callback: function (e) {
  679. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  680. if (selected.length === 0) {
  681. chunk = e.__localize("code text here")
  682. } else {
  683. chunk = selected.text
  684. }
  685. if (content.substr(selected.start - 4, 4) === "```\n" && content.substr(selected.end, 4) === "\n```") {
  686. e.setSelection(selected.start - 4, selected.end + 4);
  687. e.replaceSelection(chunk);
  688. cursor = selected.start - 4
  689. } else if (content.substr(selected.start - 1, 1) === "`" && content.substr(selected.end, 1) === "`") {
  690. e.setSelection(selected.start - 1, selected.end + 1);
  691. e.replaceSelection(chunk);
  692. cursor = selected.start - 1
  693. } else if (content.indexOf("\n") > -1) {
  694. e.replaceSelection("```\n" + chunk + "\n```");
  695. cursor = selected.start + 4
  696. } else {
  697. e.replaceSelection("`" + chunk + "`");
  698. cursor = selected.start + 1
  699. }
  700. e.setSelection(cursor, cursor + chunk.length)
  701. }
  702. }, {
  703. name: "cmdQuote", hotkey: "Ctrl+Q", title: "Quote", icon: {glyph: "glyphicon glyphicon-comment", fa: "fa fa-quote-left", "fa-3": "icon-quote-left"}, callback: function (e) {
  704. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  705. if (selected.length === 0) {
  706. chunk = e.__localize("quote here");
  707. e.replaceSelection("> " + chunk);
  708. cursor = selected.start + 2
  709. } else {
  710. if (selected.text.indexOf("\n") < 0) {
  711. chunk = selected.text;
  712. e.replaceSelection("> " + chunk);
  713. cursor = selected.start + 2
  714. } else {
  715. var list = [];
  716. list = selected.text.split("\n");
  717. chunk = list[0];
  718. $.each(list, function (k, v) {
  719. list[k] = "> " + v
  720. });
  721. e.replaceSelection("\n\n" + list.join("\n"));
  722. cursor = selected.start + 4
  723. }
  724. }
  725. e.setSelection(cursor, cursor + chunk.length)
  726. }
  727. }]
  728. }, {
  729. name: "groupUtil", data: [{
  730. name: "cmdPreview", toggle: true, hotkey: "Ctrl+P", title: "Preview", btnText: "Preview", btnClass: "btn btn-light", icon: {glyph: "glyphicon glyphicon-search", fa: "fa fa-search", "fa-3": "icon-search"}, callback: function (e) {
  731. var isPreview = e.$isPreview, content;
  732. if (isPreview === false) {
  733. e.showPreview()
  734. } else {
  735. e.hidePreview()
  736. }
  737. }
  738. }]
  739. }]], additionalButtons: [], reorderButtonGroups: [], hiddenButtons: [], disabledButtons: [], footer: "", fullscreen: {enable: true, icons: {fullscreenOn: {fa: "fa fa-expand", glyph: "glyphicon glyphicon-fullscreen", "fa-3": "icon-expand"}, fullscreenOff: {fa: "fa fa-compress", glyph: "glyphicon glyphicon-fullscreen", "fa-3": "icon-compress"}}}, onShow: function (e) {
  740. }, onPreview: function (e) {
  741. }, onSave: function (e) {
  742. }, onBlur: function (e) {
  743. }, onFocus: function (e) {
  744. }, onChange: function (e) {
  745. }, onFullscreen: function (e) {
  746. }, onSelect: function (e) {
  747. }
  748. };
  749. $.fn.markdown.Constructor = Markdown;
  750. $.fn.markdown.noConflict = function () {
  751. $.fn.markdown = old;
  752. return this
  753. };
  754. var initMarkdown = function (el) {
  755. var $this = el;
  756. if ($this.data("markdown")) {
  757. $this.data("markdown").showEditor();
  758. return
  759. }
  760. $this.markdown()
  761. };
  762. var blurNonFocused = function (e) {
  763. var $activeElement = $(document.activeElement);
  764. $(document).find(".md-editor").each(function () {
  765. var $this = $(this), focused = $activeElement.closest(".md-editor")[0] === this, attachedMarkdown = $this.find("textarea").data("markdown") || $this.find('div[data-provider="markdown-preview"]').data("markdown");
  766. if (attachedMarkdown && !focused) {
  767. attachedMarkdown.blur()
  768. }
  769. })
  770. };
  771. $(document).on("click.markdown.data-api", '[data-provide="markdown-editable"]', function (e) {
  772. initMarkdown($(this));
  773. e.preventDefault()
  774. }).on("click focusin", function (e) {
  775. blurNonFocused(e)
  776. }).ready(function () {
  777. $('textarea[data-provide="markdown"]').each(function () {
  778. initMarkdown($(this))
  779. })
  780. })
  781. });