Theme Inspinia
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bootstrap-markdown.js 43KB

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