bootstrap-markdown.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  1. /* ===================================================
  2. * bootstrap-markdown.js v2.10.0
  3. * http://github.com/toopay/bootstrap-markdown
  4. * ===================================================
  5. * Copyright 2013-2016 Taufan Aditya
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * ========================================================== */
  19. (function (factory) {
  20. if (typeof define === "function" && define.amd) {
  21. //RequireJS
  22. define(["jquery"], factory);
  23. } else if (typeof exports === 'object') {
  24. //Backbone.js
  25. factory(require('jquery'));
  26. } else {
  27. //Jquery plugin
  28. factory(jQuery);
  29. }
  30. }(function ($) {
  31. "use strict"; // jshint ;_;
  32. /* MARKDOWN CLASS DEFINITION
  33. * ========================== */
  34. var Markdown = function (element, options) {
  35. // @TODO : remove this BC on next major release
  36. // @see : https://github.com/toopay/bootstrap-markdown/issues/109
  37. var opts = ['autofocus', 'savable', 'hideable', 'width',
  38. 'height', 'resize', 'iconlibrary', 'language',
  39. 'footer', 'fullscreen', 'hiddenButtons', 'disabledButtons'];
  40. $.each(opts, function (_, opt) {
  41. if (typeof $(element).data(opt) !== 'undefined') {
  42. options = typeof options == 'object' ? options : {}
  43. options[opt] = $(element).data(opt)
  44. }
  45. });
  46. // End BC
  47. // Class Properties
  48. this.$ns = 'bootstrap-markdown';
  49. this.$element = $(element);
  50. this.$editable = {el: null, type: null, attrKeys: [], attrValues: [], content: null};
  51. this.$options = $.extend(true, {}, $.fn.markdown.defaults, options, this.$element.data('options'));
  52. this.$oldContent = null;
  53. this.$isPreview = false;
  54. this.$isFullscreen = false;
  55. this.$editor = null;
  56. this.$textarea = null;
  57. this.$handler = [];
  58. this.$callback = [];
  59. this.$nextTab = [];
  60. this.showEditor();
  61. };
  62. Markdown.prototype = {
  63. constructor: Markdown
  64. , __alterButtons: function (name, alter) {
  65. var handler = this.$handler, isAll = (name == 'all'), that = this;
  66. $.each(handler, function (k, v) {
  67. var halt = true;
  68. if (isAll) {
  69. halt = false;
  70. } else {
  71. halt = v.indexOf(name) < 0;
  72. }
  73. if (halt === false) {
  74. alter(that.$editor.find('button[data-handler="' + v + '"]'));
  75. }
  76. });
  77. }
  78. , __buildButtons: function (buttonsArray, container) {
  79. var i,
  80. ns = this.$ns,
  81. handler = this.$handler,
  82. callback = this.$callback;
  83. for (i = 0; i < buttonsArray.length; i++) {
  84. // Build each group container
  85. var y, btnGroups = buttonsArray[i];
  86. for (y = 0; y < btnGroups.length; y++) {
  87. // Build each button group
  88. var z,
  89. buttons = btnGroups[y].data,
  90. btnGroupContainer = $('<div/>', {
  91. 'class': 'btn-group'
  92. });
  93. for (z = 0; z < buttons.length; z++) {
  94. var button = buttons[z],
  95. buttonContainer, buttonIconContainer,
  96. buttonHandler = ns + '-' + button.name,
  97. buttonIcon = this.__getIcon(button.icon),
  98. btnText = button.btnText ? button.btnText : '',
  99. btnClass = button.btnClass ? button.btnClass : 'btn',
  100. tabIndex = button.tabIndex ? button.tabIndex : '-1',
  101. hotkey = typeof button.hotkey !== 'undefined' ? button.hotkey : '',
  102. hotkeyCaption = typeof jQuery.hotkeys !== 'undefined' && hotkey !== '' ? ' (' + hotkey + ')' : '';
  103. // Construct the button object
  104. buttonContainer = $('<button></button>');
  105. buttonContainer.text(' ' + this.__localize(btnText)).addClass('btn-default btn-sm').addClass(btnClass);
  106. if (btnClass.match(/btn\-(primary|success|info|warning|danger|link)/)) {
  107. buttonContainer.removeClass('btn-default');
  108. }
  109. buttonContainer.attr({
  110. 'type': 'button',
  111. 'title': this.__localize(button.title) + hotkeyCaption,
  112. 'tabindex': tabIndex,
  113. 'data-provider': ns,
  114. 'data-handler': buttonHandler,
  115. 'data-hotkey': hotkey
  116. });
  117. if (button.toggle === true) {
  118. buttonContainer.attr('data-toggle', 'button');
  119. }
  120. buttonIconContainer = $('<span/>');
  121. buttonIconContainer.addClass(buttonIcon);
  122. buttonIconContainer.prependTo(buttonContainer);
  123. // Attach the button object
  124. btnGroupContainer.append(buttonContainer);
  125. // Register handler and callback
  126. handler.push(buttonHandler);
  127. callback.push(button.callback);
  128. }
  129. // Attach the button group into container dom
  130. container.append(btnGroupContainer);
  131. }
  132. }
  133. return container;
  134. }
  135. , __setListener: function () {
  136. // Set size and resizable Properties
  137. var hasRows = typeof this.$textarea.attr('rows') !== 'undefined',
  138. maxRows = this.$textarea.val().split("\n").length > 5 ? this.$textarea.val().split("\n").length : '5',
  139. rowsVal = hasRows ? this.$textarea.attr('rows') : maxRows;
  140. this.$textarea.attr('rows', rowsVal);
  141. if (this.$options.resize) {
  142. this.$textarea.css('resize', this.$options.resize);
  143. }
  144. this.$textarea.on({
  145. 'focus': $.proxy(this.focus, this),
  146. 'keyup': $.proxy(this.keyup, this),
  147. 'change': $.proxy(this.change, this),
  148. 'select': $.proxy(this.select, this)
  149. });
  150. if (this.eventSupported('keydown')) {
  151. this.$textarea.on('keydown', $.proxy(this.keydown, this));
  152. }
  153. if (this.eventSupported('keypress')) {
  154. this.$textarea.on('keypress', $.proxy(this.keypress, this))
  155. }
  156. // Re-attach markdown data
  157. this.$textarea.data('markdown', this);
  158. }
  159. , __handle: function (e) {
  160. var target = $(e.currentTarget),
  161. handler = this.$handler,
  162. callback = this.$callback,
  163. handlerName = target.attr('data-handler'),
  164. callbackIndex = handler.indexOf(handlerName),
  165. callbackHandler = callback[callbackIndex];
  166. // Trigger the focusin
  167. $(e.currentTarget).focus();
  168. callbackHandler(this);
  169. // Trigger onChange for each button handle
  170. this.change(this);
  171. // Unless it was the save handler,
  172. // focusin the textarea
  173. if (handlerName.indexOf('cmdSave') < 0) {
  174. this.$textarea.focus();
  175. }
  176. e.preventDefault();
  177. }
  178. , __localize: function (string) {
  179. var messages = $.fn.markdown.messages,
  180. language = this.$options.language;
  181. if (
  182. typeof messages !== 'undefined' &&
  183. typeof messages[language] !== 'undefined' &&
  184. typeof messages[language][string] !== 'undefined'
  185. ) {
  186. return messages[language][string];
  187. }
  188. return string;
  189. }
  190. , __getIcon: function (src) {
  191. return typeof src == 'object' ? src[this.$options.iconlibrary] : src;
  192. }
  193. , setFullscreen: function (mode) {
  194. var $editor = this.$editor,
  195. $textarea = this.$textarea;
  196. if (mode === true) {
  197. $editor.addClass('md-fullscreen-mode');
  198. $('body').addClass('md-nooverflow');
  199. this.$options.onFullscreen(this);
  200. } else {
  201. $editor.removeClass('md-fullscreen-mode');
  202. $('body').removeClass('md-nooverflow');
  203. this.$options.onFullscreenExit(this);
  204. if (this.$isPreview == true) this.hidePreview().showPreview()
  205. }
  206. this.$isFullscreen = mode;
  207. $textarea.focus();
  208. }
  209. , showEditor: function () {
  210. var instance = this,
  211. textarea,
  212. ns = this.$ns,
  213. container = this.$element,
  214. originalHeigth = container.css('height'),
  215. originalWidth = container.css('width'),
  216. editable = this.$editable,
  217. handler = this.$handler,
  218. callback = this.$callback,
  219. options = this.$options,
  220. editor = $('<div/>', {
  221. 'class': 'md-editor',
  222. click: function () {
  223. instance.focus();
  224. }
  225. });
  226. // Prepare the editor
  227. if (this.$editor === null) {
  228. // Create the panel
  229. var editorHeader = $('<div/>', {
  230. 'class': 'md-header btn-toolbar'
  231. });
  232. // Merge the main & additional button groups together
  233. var allBtnGroups = [];
  234. if (options.buttons.length > 0) allBtnGroups = allBtnGroups.concat(options.buttons[0]);
  235. if (options.additionalButtons.length > 0) {
  236. // iterate the additional button groups
  237. $.each(options.additionalButtons[0], function (idx, buttonGroup) {
  238. // see if the group name of the addional group matches an existing group
  239. var matchingGroups = $.grep(allBtnGroups, function (allButtonGroup, allIdx) {
  240. return allButtonGroup.name === buttonGroup.name;
  241. });
  242. // if it matches add the addional buttons to that group, if not just add it to the all buttons group
  243. if (matchingGroups.length > 0) {
  244. matchingGroups[0].data = matchingGroups[0].data.concat(buttonGroup.data);
  245. } else {
  246. allBtnGroups.push(options.additionalButtons[0][idx]);
  247. }
  248. });
  249. }
  250. // Reduce and/or reorder the button groups
  251. if (options.reorderButtonGroups.length > 0) {
  252. allBtnGroups = allBtnGroups
  253. .filter(function (btnGroup) {
  254. return options.reorderButtonGroups.indexOf(btnGroup.name) > -1;
  255. })
  256. .sort(function (a, b) {
  257. if (options.reorderButtonGroups.indexOf(a.name) < options.reorderButtonGroups.indexOf(b.name)) return -1;
  258. if (options.reorderButtonGroups.indexOf(a.name) > options.reorderButtonGroups.indexOf(b.name)) return 1;
  259. return 0;
  260. });
  261. }
  262. // Build the buttons
  263. if (allBtnGroups.length > 0) {
  264. editorHeader = this.__buildButtons([allBtnGroups], editorHeader);
  265. }
  266. if (options.fullscreen.enable) {
  267. 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) {
  268. e.preventDefault();
  269. instance.setFullscreen(true);
  270. });
  271. }
  272. editor.append(editorHeader);
  273. // Wrap the textarea
  274. if (container.is('textarea')) {
  275. container.before(editor);
  276. textarea = container;
  277. textarea.addClass('md-input');
  278. editor.append(textarea);
  279. } else {
  280. var rawContent = (typeof toMarkdown == 'function') ? toMarkdown(container.html()) : container.html(),
  281. currentContent = $.trim(rawContent);
  282. // This is some arbitrary content that could be edited
  283. textarea = $('<textarea/>', {
  284. 'class': 'md-input',
  285. 'val': currentContent
  286. });
  287. editor.append(textarea);
  288. // Save the editable
  289. editable.el = container;
  290. editable.type = container.prop('tagName').toLowerCase();
  291. editable.content = container.html();
  292. $(container[0].attributes).each(function () {
  293. editable.attrKeys.push(this.nodeName);
  294. editable.attrValues.push(this.nodeValue);
  295. });
  296. // Set editor to blocked the original container
  297. container.replaceWith(editor);
  298. }
  299. var editorFooter = $('<div/>', {
  300. 'class': 'md-footer'
  301. }),
  302. createFooter = false,
  303. footer = '';
  304. // Create the footer if savable
  305. if (options.savable) {
  306. createFooter = true;
  307. var saveHandler = 'cmdSave';
  308. // Register handler and callback
  309. handler.push(saveHandler);
  310. callback.push(options.onSave);
  311. editorFooter.append('<button class="btn btn-success" data-provider="'
  312. + ns
  313. + '" data-handler="'
  314. + saveHandler
  315. + '"><i class="icon icon-white icon-ok"></i> '
  316. + this.__localize('Save')
  317. + '</button>');
  318. }
  319. footer = typeof options.footer === 'function' ? options.footer(this) : options.footer;
  320. if ($.trim(footer) !== '') {
  321. createFooter = true;
  322. editorFooter.append(footer);
  323. }
  324. if (createFooter) editor.append(editorFooter);
  325. // Set width
  326. if (options.width && options.width !== 'inherit') {
  327. if (jQuery.isNumeric(options.width)) {
  328. editor.css('display', 'table');
  329. textarea.css('width', options.width + 'px');
  330. } else {
  331. editor.addClass(options.width);
  332. }
  333. }
  334. // Set height
  335. if (options.height && options.height !== 'inherit') {
  336. if (jQuery.isNumeric(options.height)) {
  337. var height = options.height;
  338. if (editorHeader) height = Math.max(0, height - editorHeader.outerHeight());
  339. if (editorFooter) height = Math.max(0, height - editorFooter.outerHeight());
  340. textarea.css('height', height + 'px');
  341. } else {
  342. editor.addClass(options.height);
  343. }
  344. }
  345. // Reference
  346. this.$editor = editor;
  347. this.$textarea = textarea;
  348. this.$editable = editable;
  349. this.$oldContent = this.getContent();
  350. this.__setListener();
  351. // Set editor attributes, data short-hand API and listener
  352. this.$editor.attr('id', (new Date()).getTime());
  353. this.$editor.on('click', '[data-provider="bootstrap-markdown"]', $.proxy(this.__handle, this));
  354. if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
  355. this.$editor.addClass('md-editor-disabled');
  356. this.disableButtons('all');
  357. }
  358. if (this.eventSupported('keydown') && typeof jQuery.hotkeys === 'object') {
  359. editorHeader.find('[data-provider="bootstrap-markdown"]').each(function () {
  360. var $button = $(this),
  361. hotkey = $button.attr('data-hotkey');
  362. if (hotkey.toLowerCase() !== '') {
  363. textarea.bind('keydown', hotkey, function () {
  364. $button.trigger('click');
  365. return false;
  366. });
  367. }
  368. });
  369. }
  370. if (options.initialstate === 'preview') {
  371. this.showPreview();
  372. } else if (options.initialstate === 'fullscreen' && options.fullscreen.enable) {
  373. this.setFullscreen(true);
  374. }
  375. } else {
  376. this.$editor.show();
  377. }
  378. if (options.autofocus) {
  379. this.$textarea.focus();
  380. this.$editor.addClass('active');
  381. }
  382. if (options.fullscreen.enable && options.fullscreen !== false) {
  383. this.$editor.append('<div class="md-fullscreen-controls">'
  384. + '<a href="#" class="exit-fullscreen" title="Exit fullscreen"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOff) + '">'
  385. + '</span></a>'
  386. + '</div>');
  387. this.$editor.on('click', '.exit-fullscreen', function (e) {
  388. e.preventDefault();
  389. instance.setFullscreen(false);
  390. });
  391. }
  392. // hide hidden buttons from options
  393. this.hideButtons(options.hiddenButtons);
  394. // disable disabled buttons from options
  395. this.disableButtons(options.disabledButtons);
  396. // enable dropZone if available and configured
  397. if (options.dropZoneOptions) {
  398. if (this.$editor.dropzone) {
  399. options.dropZoneOptions.init = function () {
  400. var caretPos = 0;
  401. this.on('drop', function (e) {
  402. caretPos = textarea.prop('selectionStart');
  403. });
  404. this.on('success', function (file, path) {
  405. var text = textarea.val();
  406. textarea.val(text.substring(0, caretPos) + '\n![description](' + path + ')\n' + text.substring(caretPos));
  407. });
  408. this.on('error', function (file, error, xhr) {
  409. console.log('Error:', error);
  410. });
  411. }
  412. this.$textarea.addClass('dropzone');
  413. this.$editor.dropzone(options.dropZoneOptions);
  414. } else {
  415. console.log('dropZoneOptions was configured, but DropZone was not detected.');
  416. }
  417. }
  418. // Trigger the onShow hook
  419. options.onShow(this);
  420. return this;
  421. }
  422. , parseContent: function (val) {
  423. var content;
  424. // parse with supported markdown parser
  425. var val = val || this.$textarea.val();
  426. if (this.$options.parser) {
  427. content = this.$options.parser(val);
  428. } else if (typeof markdown == 'object') {
  429. content = markdown.toHTML(val);
  430. } else if (typeof marked == 'function') {
  431. content = marked(val);
  432. } else {
  433. content = val;
  434. }
  435. return content;
  436. }
  437. , showPreview: function () {
  438. var options = this.$options,
  439. container = this.$textarea,
  440. afterContainer = container.next(),
  441. replacementContainer = $('<div/>', {'class': 'md-preview', 'data-provider': 'markdown-preview'}),
  442. content,
  443. callbackContent;
  444. if (this.$isPreview == true) {
  445. // Avoid sequenced element creation on missused scenario
  446. // @see https://github.com/toopay/bootstrap-markdown/issues/170
  447. return this;
  448. }
  449. // Give flag that tell the editor enter preview mode
  450. this.$isPreview = true;
  451. // Disable all buttons
  452. this.disableButtons('all').enableButtons('cmdPreview');
  453. // Try to get the content from callback
  454. callbackContent = options.onPreview(this);
  455. // Set the content based from the callback content if string otherwise parse value from textarea
  456. content = typeof callbackContent == 'string' ? callbackContent : this.parseContent();
  457. // Build preview element
  458. replacementContainer.html(content);
  459. if (afterContainer && afterContainer.attr('class') == 'md-footer') {
  460. // If there is footer element, insert the preview container before it
  461. replacementContainer.insertBefore(afterContainer);
  462. } else {
  463. // Otherwise, just append it after textarea
  464. container.parent().append(replacementContainer);
  465. }
  466. // Set the preview element dimensions
  467. replacementContainer.css({
  468. width: container.outerWidth() + 'px',
  469. height: container.outerHeight() + 'px'
  470. });
  471. if (this.$options.resize) {
  472. replacementContainer.css('resize', this.$options.resize);
  473. }
  474. // Hide the last-active textarea
  475. container.hide();
  476. // Attach the editor instances
  477. replacementContainer.data('markdown', this);
  478. if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
  479. this.$editor.addClass('md-editor-disabled');
  480. this.disableButtons('all');
  481. }
  482. return this;
  483. }
  484. , hidePreview: function () {
  485. // Give flag that tell the editor quit preview mode
  486. this.$isPreview = false;
  487. // Obtain the preview container
  488. var container = this.$editor.find('div[data-provider="markdown-preview"]');
  489. // Remove the preview container
  490. container.remove();
  491. // Enable all buttons
  492. this.enableButtons('all');
  493. // Disable configured disabled buttons
  494. this.disableButtons(this.$options.disabledButtons);
  495. // Back to the editor
  496. this.$textarea.show();
  497. this.__setListener();
  498. return this;
  499. }
  500. , isDirty: function () {
  501. return this.$oldContent != this.getContent();
  502. }
  503. , getContent: function () {
  504. return this.$textarea.val();
  505. }
  506. , setContent: function (content) {
  507. this.$textarea.val(content);
  508. return this;
  509. }
  510. , findSelection: function (chunk) {
  511. var content = this.getContent(), startChunkPosition;
  512. if (startChunkPosition = content.indexOf(chunk), startChunkPosition >= 0 && chunk.length > 0) {
  513. var oldSelection = this.getSelection(), selection;
  514. this.setSelection(startChunkPosition, startChunkPosition + chunk.length);
  515. selection = this.getSelection();
  516. this.setSelection(oldSelection.start, oldSelection.end);
  517. return selection;
  518. } else {
  519. return null;
  520. }
  521. }
  522. , getSelection: function () {
  523. var e = this.$textarea[0];
  524. return (
  525. ('selectionStart' in e && function () {
  526. var l = e.selectionEnd - e.selectionStart;
  527. return {
  528. start: e.selectionStart,
  529. end: e.selectionEnd,
  530. length: l,
  531. text: e.value.substr(e.selectionStart, l)
  532. };
  533. }) ||
  534. /* browser not supported */
  535. function () {
  536. return null;
  537. }
  538. )();
  539. }
  540. , setSelection: function (start, end) {
  541. var e = this.$textarea[0];
  542. return (
  543. ('selectionStart' in e && function () {
  544. e.selectionStart = start;
  545. e.selectionEnd = end;
  546. return;
  547. }) ||
  548. /* browser not supported */
  549. function () {
  550. return null;
  551. }
  552. )();
  553. }
  554. , replaceSelection: function (text) {
  555. var e = this.$textarea[0];
  556. return (
  557. ('selectionStart' in e && function () {
  558. e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
  559. // Set cursor to the last replacement end
  560. e.selectionStart = e.value.length;
  561. return this;
  562. }) ||
  563. /* browser not supported */
  564. function () {
  565. e.value += text;
  566. return jQuery(e);
  567. }
  568. )();
  569. }
  570. , getNextTab: function () {
  571. // Shift the nextTab
  572. if (this.$nextTab.length === 0) {
  573. return null;
  574. } else {
  575. var nextTab, tab = this.$nextTab.shift();
  576. if (typeof tab == 'function') {
  577. nextTab = tab();
  578. } else if (typeof tab == 'object' && tab.length > 0) {
  579. nextTab = tab;
  580. }
  581. return nextTab;
  582. }
  583. }
  584. , setNextTab: function (start, end) {
  585. // Push new selection into nextTab collections
  586. if (typeof start == 'string') {
  587. var that = this;
  588. this.$nextTab.push(function () {
  589. return that.findSelection(start);
  590. });
  591. } else if (typeof start == 'number' && typeof end == 'number') {
  592. var oldSelection = this.getSelection();
  593. this.setSelection(start, end);
  594. this.$nextTab.push(this.getSelection());
  595. this.setSelection(oldSelection.start, oldSelection.end);
  596. }
  597. return;
  598. }
  599. , __parseButtonNameParam: function (names) {
  600. return typeof names == 'string' ?
  601. names.split(' ') :
  602. names;
  603. }
  604. , enableButtons: function (name) {
  605. var buttons = this.__parseButtonNameParam(name),
  606. that = this;
  607. $.each(buttons, function (i, v) {
  608. that.__alterButtons(buttons[i], function (el) {
  609. el.removeAttr('disabled');
  610. });
  611. });
  612. return this;
  613. }
  614. , disableButtons: function (name) {
  615. var buttons = this.__parseButtonNameParam(name),
  616. that = this;
  617. $.each(buttons, function (i, v) {
  618. that.__alterButtons(buttons[i], function (el) {
  619. el.attr('disabled', 'disabled');
  620. });
  621. });
  622. return this;
  623. }
  624. , hideButtons: function (name) {
  625. var buttons = this.__parseButtonNameParam(name),
  626. that = this;
  627. $.each(buttons, function (i, v) {
  628. that.__alterButtons(buttons[i], function (el) {
  629. el.addClass('hidden');
  630. });
  631. });
  632. return this;
  633. }
  634. , showButtons: function (name) {
  635. var buttons = this.__parseButtonNameParam(name),
  636. that = this;
  637. $.each(buttons, function (i, v) {
  638. that.__alterButtons(buttons[i], function (el) {
  639. el.removeClass('hidden');
  640. });
  641. });
  642. return this;
  643. }
  644. , eventSupported: function (eventName) {
  645. var isSupported = eventName in this.$element;
  646. if (!isSupported) {
  647. this.$element.setAttribute(eventName, 'return;');
  648. isSupported = typeof this.$element[eventName] === 'function';
  649. }
  650. return isSupported;
  651. }
  652. , keyup: function (e) {
  653. var blocked = false;
  654. switch (e.keyCode) {
  655. case 40: // down arrow
  656. case 38: // up arrow
  657. case 16: // shift
  658. case 17: // ctrl
  659. case 18: // alt
  660. break;
  661. case 9: // tab
  662. var nextTab;
  663. if (nextTab = this.getNextTab(), nextTab !== null) {
  664. // Get the nextTab if exists
  665. var that = this;
  666. setTimeout(function () {
  667. that.setSelection(nextTab.start, nextTab.end);
  668. }, 500);
  669. blocked = true;
  670. } else {
  671. // The next tab memory contains nothing...
  672. // check the cursor position to determine tab action
  673. var cursor = this.getSelection();
  674. if (cursor.start == cursor.end && cursor.end == this.getContent().length) {
  675. // The cursor already reach the end of the content
  676. blocked = false;
  677. } else {
  678. // Put the cursor to the end
  679. this.setSelection(this.getContent().length, this.getContent().length);
  680. blocked = true;
  681. }
  682. }
  683. break;
  684. case 13: // enter
  685. blocked = false;
  686. break;
  687. case 27: // escape
  688. if (this.$isFullscreen) this.setFullscreen(false);
  689. blocked = false;
  690. break;
  691. default:
  692. blocked = false;
  693. }
  694. if (blocked) {
  695. e.stopPropagation();
  696. e.preventDefault();
  697. }
  698. this.$options.onChange(this);
  699. }
  700. , change: function (e) {
  701. this.$options.onChange(this);
  702. return this;
  703. }
  704. , select: function (e) {
  705. this.$options.onSelect(this);
  706. return this;
  707. }
  708. , focus: function (e) {
  709. var options = this.$options,
  710. isHideable = options.hideable,
  711. editor = this.$editor;
  712. editor.addClass('active');
  713. // Blur other markdown(s)
  714. $(document).find('.md-editor').each(function () {
  715. if ($(this).attr('id') !== editor.attr('id')) {
  716. var attachedMarkdown;
  717. if (attachedMarkdown = $(this).find('textarea').data('markdown'),
  718. attachedMarkdown === null) {
  719. attachedMarkdown = $(this).find('div[data-provider="markdown-preview"]').data('markdown');
  720. }
  721. if (attachedMarkdown) {
  722. attachedMarkdown.blur();
  723. }
  724. }
  725. });
  726. // Trigger the onFocus hook
  727. options.onFocus(this);
  728. return this;
  729. }
  730. , blur: function (e) {
  731. var options = this.$options,
  732. isHideable = options.hideable,
  733. editor = this.$editor,
  734. editable = this.$editable;
  735. if (editor.hasClass('active') || this.$element.parent().length === 0) {
  736. editor.removeClass('active');
  737. if (isHideable) {
  738. // Check for editable elements
  739. if (editable.el !== null) {
  740. // Build the original element
  741. var oldElement = $('<' + editable.type + '/>'),
  742. content = this.getContent(),
  743. currentContent = this.parseContent(content);
  744. $(editable.attrKeys).each(function (k, v) {
  745. oldElement.attr(editable.attrKeys[k], editable.attrValues[k]);
  746. });
  747. // Get the editor content
  748. oldElement.html(currentContent);
  749. editor.replaceWith(oldElement);
  750. } else {
  751. editor.hide();
  752. }
  753. }
  754. // Trigger the onBlur hook
  755. options.onBlur(this);
  756. }
  757. return this;
  758. }
  759. };
  760. /* MARKDOWN PLUGIN DEFINITION
  761. * ========================== */
  762. var old = $.fn.markdown;
  763. $.fn.markdown = function (option) {
  764. return this.each(function () {
  765. var $this = $(this)
  766. , data = $this.data('markdown')
  767. , options = typeof option == 'object' && option;
  768. if (!data) $this.data('markdown', (data = new Markdown(this, options)))
  769. })
  770. };
  771. $.fn.markdown.messages = {};
  772. $.fn.markdown.defaults = {
  773. /* Editor Properties */
  774. autofocus: false,
  775. hideable: false,
  776. savable: false,
  777. width: 'inherit',
  778. height: 'inherit',
  779. resize: 'none',
  780. iconlibrary: 'glyph',
  781. language: 'en',
  782. initialstate: 'editor',
  783. parser: null,
  784. dropZoneOptions: null,
  785. /* Buttons Properties */
  786. buttons: [
  787. [{
  788. name: 'groupFont',
  789. data: [{
  790. name: 'cmdBold',
  791. hotkey: 'Ctrl+B',
  792. title: 'Bold',
  793. icon: {glyph: 'glyphicon glyphicon-bold', fa: 'fa fa-bold', 'fa-3': 'icon-bold'},
  794. callback: function (e) {
  795. // Give/remove ** surround the selection
  796. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  797. if (selected.length === 0) {
  798. // Give extra word
  799. chunk = e.__localize('strong text');
  800. } else {
  801. chunk = selected.text;
  802. }
  803. // transform selection and set the cursor into chunked text
  804. if (content.substr(selected.start - 2, 2) === '**'
  805. && content.substr(selected.end, 2) === '**') {
  806. e.setSelection(selected.start - 2, selected.end + 2);
  807. e.replaceSelection(chunk);
  808. cursor = selected.start - 2;
  809. } else {
  810. e.replaceSelection('**' + chunk + '**');
  811. cursor = selected.start + 2;
  812. }
  813. // Set the cursor
  814. e.setSelection(cursor, cursor + chunk.length);
  815. }
  816. }, {
  817. name: 'cmdItalic',
  818. title: 'Italic',
  819. hotkey: 'Ctrl+I',
  820. icon: {glyph: 'glyphicon glyphicon-italic', fa: 'fa fa-italic', 'fa-3': 'icon-italic'},
  821. callback: function (e) {
  822. // Give/remove * surround the selection
  823. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  824. if (selected.length === 0) {
  825. // Give extra word
  826. chunk = e.__localize('emphasized text');
  827. } else {
  828. chunk = selected.text;
  829. }
  830. // transform selection and set the cursor into chunked text
  831. if (content.substr(selected.start - 1, 1) === '_'
  832. && content.substr(selected.end, 1) === '_') {
  833. e.setSelection(selected.start - 1, selected.end + 1);
  834. e.replaceSelection(chunk);
  835. cursor = selected.start - 1;
  836. } else {
  837. e.replaceSelection('_' + chunk + '_');
  838. cursor = selected.start + 1;
  839. }
  840. // Set the cursor
  841. e.setSelection(cursor, cursor + chunk.length);
  842. }
  843. }, {
  844. name: 'cmdHeading',
  845. title: 'Heading',
  846. hotkey: 'Ctrl+H',
  847. icon: {glyph: 'glyphicon glyphicon-header', fa: 'fa fa-header', 'fa-3': 'icon-font'},
  848. callback: function (e) {
  849. // Append/remove ### surround the selection
  850. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), pointer, prevChar;
  851. if (selected.length === 0) {
  852. // Give extra word
  853. chunk = e.__localize('heading text');
  854. } else {
  855. chunk = selected.text + '\n';
  856. }
  857. // transform selection and set the cursor into chunked text
  858. if ((pointer = 4, content.substr(selected.start - pointer, pointer) === '### ')
  859. || (pointer = 3, content.substr(selected.start - pointer, pointer) === '###')) {
  860. e.setSelection(selected.start - pointer, selected.end);
  861. e.replaceSelection(chunk);
  862. cursor = selected.start - pointer;
  863. } else if (selected.start > 0 && (prevChar = content.substr(selected.start - 1, 1), !!prevChar && prevChar != '\n')) {
  864. e.replaceSelection('\n\n### ' + chunk);
  865. cursor = selected.start + 6;
  866. } else {
  867. // Empty string before element
  868. e.replaceSelection('### ' + chunk);
  869. cursor = selected.start + 4;
  870. }
  871. // Set the cursor
  872. e.setSelection(cursor, cursor + chunk.length);
  873. }
  874. }]
  875. }, {
  876. name: 'groupLink',
  877. data: [{
  878. name: 'cmdUrl',
  879. title: 'URL/Link',
  880. hotkey: 'Ctrl+L',
  881. icon: {glyph: 'glyphicon glyphicon-link', fa: 'fa fa-link', 'fa-3': 'icon-link'},
  882. callback: function (e) {
  883. // Give [] surround the selection and prepend the link
  884. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
  885. if (selected.length === 0) {
  886. // Give extra word
  887. chunk = e.__localize('enter link description here');
  888. } else {
  889. chunk = selected.text;
  890. }
  891. link = prompt(e.__localize('Insert Hyperlink'), 'http://');
  892. var urlRegex = new RegExp('^((http|https)://|(mailto:)|(//))[a-z0-9]', 'i');
  893. if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
  894. var sanitizedLink = $('<div>' + link + '</div>').text();
  895. // transform selection and set the cursor into chunked text
  896. e.replaceSelection('[' + chunk + '](' + sanitizedLink + ')');
  897. cursor = selected.start + 1;
  898. // Set the cursor
  899. e.setSelection(cursor, cursor + chunk.length);
  900. }
  901. }
  902. }, {
  903. name: 'cmdImage',
  904. title: 'Image',
  905. hotkey: 'Ctrl+G',
  906. icon: {glyph: 'glyphicon glyphicon-picture', fa: 'fa fa-picture-o', 'fa-3': 'icon-picture'},
  907. callback: function (e) {
  908. // Give ![] surround the selection and prepend the image link
  909. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
  910. if (selected.length === 0) {
  911. // Give extra word
  912. chunk = e.__localize('enter image description here');
  913. } else {
  914. chunk = selected.text;
  915. }
  916. link = prompt(e.__localize('Insert Image Hyperlink'), 'http://');
  917. var urlRegex = new RegExp('^((http|https)://|(//))[a-z0-9]', 'i');
  918. if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
  919. var sanitizedLink = $('<div>' + link + '</div>').text();
  920. // transform selection and set the cursor into chunked text
  921. e.replaceSelection('![' + chunk + '](' + sanitizedLink + ' "' + e.__localize('enter image title here') + '")');
  922. cursor = selected.start + 2;
  923. // Set the next tab
  924. e.setNextTab(e.__localize('enter image title here'));
  925. // Set the cursor
  926. e.setSelection(cursor, cursor + chunk.length);
  927. }
  928. }
  929. }]
  930. }, {
  931. name: 'groupMisc',
  932. data: [{
  933. name: 'cmdList',
  934. hotkey: 'Ctrl+U',
  935. title: 'Unordered List',
  936. icon: {glyph: 'glyphicon glyphicon-list', fa: 'fa fa-list', 'fa-3': 'icon-list-ul'},
  937. callback: function (e) {
  938. // Prepend/Give - surround the selection
  939. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  940. // transform selection and set the cursor into chunked text
  941. if (selected.length === 0) {
  942. // Give extra word
  943. chunk = e.__localize('list text here');
  944. e.replaceSelection('- ' + chunk);
  945. // Set the cursor
  946. cursor = selected.start + 2;
  947. } else {
  948. if (selected.text.indexOf('\n') < 0) {
  949. chunk = selected.text;
  950. e.replaceSelection('- ' + chunk);
  951. // Set the cursor
  952. cursor = selected.start + 2;
  953. } else {
  954. var list = [];
  955. list = selected.text.split('\n');
  956. chunk = list[0];
  957. $.each(list, function (k, v) {
  958. list[k] = '- ' + v;
  959. });
  960. e.replaceSelection('\n\n' + list.join('\n'));
  961. // Set the cursor
  962. cursor = selected.start + 4;
  963. }
  964. }
  965. // Set the cursor
  966. e.setSelection(cursor, cursor + chunk.length);
  967. }
  968. },
  969. {
  970. name: 'cmdListO',
  971. hotkey: 'Ctrl+O',
  972. title: 'Ordered List',
  973. icon: {glyph: 'glyphicon glyphicon-th-list', fa: 'fa fa-list-ol', 'fa-3': 'icon-list-ol'},
  974. callback: function (e) {
  975. // Prepend/Give - surround the selection
  976. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  977. // transform selection and set the cursor into chunked text
  978. if (selected.length === 0) {
  979. // Give extra word
  980. chunk = e.__localize('list text here');
  981. e.replaceSelection('1. ' + chunk);
  982. // Set the cursor
  983. cursor = selected.start + 3;
  984. } else {
  985. if (selected.text.indexOf('\n') < 0) {
  986. chunk = selected.text;
  987. e.replaceSelection('1. ' + chunk);
  988. // Set the cursor
  989. cursor = selected.start + 3;
  990. } else {
  991. var list = [];
  992. list = selected.text.split('\n');
  993. chunk = list[0];
  994. $.each(list, function (k, v) {
  995. list[k] = '1. ' + v;
  996. });
  997. e.replaceSelection('\n\n' + list.join('\n'));
  998. // Set the cursor
  999. cursor = selected.start + 5;
  1000. }
  1001. }
  1002. // Set the cursor
  1003. e.setSelection(cursor, cursor + chunk.length);
  1004. }
  1005. },
  1006. {
  1007. name: 'cmdCode',
  1008. hotkey: 'Ctrl+K',
  1009. title: 'Code',
  1010. icon: {glyph: 'glyphicon glyphicon-asterisk', fa: 'fa fa-code', 'fa-3': 'icon-code'},
  1011. callback: function (e) {
  1012. // Give/remove ** surround the selection
  1013. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  1014. if (selected.length === 0) {
  1015. // Give extra word
  1016. chunk = e.__localize('code text here');
  1017. } else {
  1018. chunk = selected.text;
  1019. }
  1020. // transform selection and set the cursor into chunked text
  1021. if (content.substr(selected.start - 4, 4) === '```\n'
  1022. && content.substr(selected.end, 4) === '\n```') {
  1023. e.setSelection(selected.start - 4, selected.end + 4);
  1024. e.replaceSelection(chunk);
  1025. cursor = selected.start - 4;
  1026. } else if (content.substr(selected.start - 1, 1) === '`'
  1027. && content.substr(selected.end, 1) === '`') {
  1028. e.setSelection(selected.start - 1, selected.end + 1);
  1029. e.replaceSelection(chunk);
  1030. cursor = selected.start - 1;
  1031. } else if (content.indexOf('\n') > -1) {
  1032. e.replaceSelection('```\n' + chunk + '\n```');
  1033. cursor = selected.start + 4;
  1034. } else {
  1035. e.replaceSelection('`' + chunk + '`');
  1036. cursor = selected.start + 1;
  1037. }
  1038. // Set the cursor
  1039. e.setSelection(cursor, cursor + chunk.length);
  1040. }
  1041. },
  1042. {
  1043. name: 'cmdQuote',
  1044. hotkey: 'Ctrl+Q',
  1045. title: 'Quote',
  1046. icon: {glyph: 'glyphicon glyphicon-comment', fa: 'fa fa-quote-left', 'fa-3': 'icon-quote-left'},
  1047. callback: function (e) {
  1048. // Prepend/Give - surround the selection
  1049. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  1050. // transform selection and set the cursor into chunked text
  1051. if (selected.length === 0) {
  1052. // Give extra word
  1053. chunk = e.__localize('quote here');
  1054. e.replaceSelection('> ' + chunk);
  1055. // Set the cursor
  1056. cursor = selected.start + 2;
  1057. } else {
  1058. if (selected.text.indexOf('\n') < 0) {
  1059. chunk = selected.text;
  1060. e.replaceSelection('> ' + chunk);
  1061. // Set the cursor
  1062. cursor = selected.start + 2;
  1063. } else {
  1064. var list = [];
  1065. list = selected.text.split('\n');
  1066. chunk = list[0];
  1067. $.each(list, function (k, v) {
  1068. list[k] = '> ' + v;
  1069. });
  1070. e.replaceSelection('\n\n' + list.join('\n'));
  1071. // Set the cursor
  1072. cursor = selected.start + 4;
  1073. }
  1074. }
  1075. // Set the cursor
  1076. e.setSelection(cursor, cursor + chunk.length);
  1077. }
  1078. }]
  1079. }, {
  1080. name: 'groupUtil',
  1081. data: [{
  1082. name: 'cmdPreview',
  1083. toggle: true,
  1084. hotkey: 'Ctrl+P',
  1085. title: 'Preview',
  1086. btnText: 'Preview',
  1087. btnClass: 'btn btn-primary btn-sm',
  1088. icon: {glyph: 'glyphicon glyphicon-search', fa: 'fa fa-search', 'fa-3': 'icon-search'},
  1089. callback: function (e) {
  1090. // Check the preview mode and toggle based on this flag
  1091. var isPreview = e.$isPreview, content;
  1092. if (isPreview === false) {
  1093. // Give flag that tell the editor enter preview mode
  1094. e.showPreview();
  1095. } else {
  1096. e.hidePreview();
  1097. }
  1098. }
  1099. }]
  1100. }]
  1101. ],
  1102. additionalButtons: [], // Place to hook more buttons by code
  1103. reorderButtonGroups: [],
  1104. hiddenButtons: [], // Default hidden buttons
  1105. disabledButtons: [], // Default disabled buttons
  1106. footer: '',
  1107. fullscreen: {
  1108. enable: true,
  1109. icons: {
  1110. fullscreenOn: {
  1111. fa: 'fa fa-expand',
  1112. glyph: 'glyphicon glyphicon-fullscreen',
  1113. 'fa-3': 'icon-resize-full'
  1114. },
  1115. fullscreenOff: {
  1116. fa: 'fa fa-compress',
  1117. glyph: 'glyphicon glyphicon-fullscreen',
  1118. 'fa-3': 'icon-resize-small'
  1119. }
  1120. }
  1121. },
  1122. /* Events hook */
  1123. onShow: function (e) {
  1124. },
  1125. onPreview: function (e) {
  1126. },
  1127. onSave: function (e) {
  1128. },
  1129. onBlur: function (e) {
  1130. },
  1131. onFocus: function (e) {
  1132. },
  1133. onChange: function (e) {
  1134. },
  1135. onFullscreen: function (e) {
  1136. },
  1137. onFullscreenExit: function (e) {
  1138. },
  1139. onSelect: function (e) {
  1140. }
  1141. };
  1142. $.fn.markdown.Constructor = Markdown;
  1143. /* MARKDOWN NO CONFLICT
  1144. * ==================== */
  1145. $.fn.markdown.noConflict = function () {
  1146. $.fn.markdown = old;
  1147. return this;
  1148. };
  1149. /* MARKDOWN GLOBAL FUNCTION & DATA-API
  1150. * ==================================== */
  1151. var initMarkdown = function (el) {
  1152. var $this = el;
  1153. if ($this.data('markdown')) {
  1154. $this.data('markdown').showEditor();
  1155. return;
  1156. }
  1157. $this.markdown()
  1158. };
  1159. var blurNonFocused = function (e) {
  1160. var $activeElement = $(document.activeElement);
  1161. // Blur event
  1162. $(document).find('.md-editor').each(function () {
  1163. var $this = $(this),
  1164. focused = $activeElement.closest('.md-editor')[0] === this,
  1165. attachedMarkdown = $this.find('textarea').data('markdown') ||
  1166. $this.find('div[data-provider="markdown-preview"]').data('markdown');
  1167. if (attachedMarkdown && !focused) {
  1168. attachedMarkdown.blur();
  1169. }
  1170. })
  1171. };
  1172. $(document)
  1173. .on('click.markdown.data-api', '[data-provide="markdown-editable"]', function (e) {
  1174. initMarkdown($(this));
  1175. e.preventDefault();
  1176. })
  1177. .on('click focusin', function (e) {
  1178. blurNonFocused(e);
  1179. })
  1180. .ready(function () {
  1181. $('textarea[data-provide="markdown"]').each(function () {
  1182. initMarkdown($(this));
  1183. })
  1184. });
  1185. }));