bootstrap-markdown.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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);