bootstrap-markdown.js 51 KB

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