PageRenderTime 64ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/public/vendor/markitup/jquery.markitup.js

https://gitlab.com/stefan.pataky/jingo
JavaScript | 634 lines | 599 code | 7 blank | 28 comment | 7 complexity | 9c8fe42b576c625a4fe59bb007ee999b MD5 | raw file
  1. // ----------------------------------------------------------------------------
  2. // markItUp! Universal MarkUp Engine, JQuery plugin
  3. // v 1.1.x
  4. // Dual licensed under the MIT and GPL licenses.
  5. // ----------------------------------------------------------------------------
  6. // Copyright (C) 2007-2012 Jay Salvat
  7. // http://markitup.jaysalvat.com/
  8. // ----------------------------------------------------------------------------
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. // ----------------------------------------------------------------------------
  27. (function($) {
  28. $.fn.markItUp = function(settings, extraSettings) {
  29. var method, params, options, ctrlKey, shiftKey, altKey; ctrlKey = shiftKey = altKey = false;
  30. if (typeof settings == 'string') {
  31. method = settings;
  32. params = extraSettings;
  33. }
  34. options = { id: '',
  35. nameSpace: '',
  36. root: '',
  37. previewHandler: false,
  38. previewInWindow: '', // 'width=800, height=600, resizable=yes, scrollbars=yes'
  39. previewInElement: '',
  40. previewAutoRefresh: true,
  41. previewPosition: 'after',
  42. previewTemplatePath: '~/templates/preview.html',
  43. previewParser: false,
  44. previewParserPath: '',
  45. previewParserVar: 'data',
  46. resizeHandle: true,
  47. beforeInsert: '',
  48. afterInsert: '',
  49. onEnter: {},
  50. onShiftEnter: {},
  51. onCtrlEnter: {},
  52. onTab: {},
  53. markupSet: [ { /* set */ } ]
  54. };
  55. $.extend(options, settings, extraSettings);
  56. // compute markItUp! path
  57. if (!options.root) {
  58. $('script').each(function(a, tag) {
  59. miuScript = $(tag).get(0).src.match(/(.*)jquery\.markitup(\.pack)?\.js$/);
  60. if (miuScript !== null) {
  61. options.root = miuScript[1];
  62. }
  63. });
  64. }
  65. return this.each(function() {
  66. var $$, textarea, levels, scrollPosition, caretPosition, caretOffset,
  67. clicked, hash, header, footer, previewWindow, template, iFrame, abort;
  68. $$ = $(this);
  69. textarea = this;
  70. levels = [];
  71. abort = false;
  72. scrollPosition = caretPosition = 0;
  73. caretOffset = -1;
  74. options.previewParserPath = localize(options.previewParserPath);
  75. options.previewTemplatePath = localize(options.previewTemplatePath);
  76. if (method) {
  77. switch(method) {
  78. case 'remove':
  79. remove();
  80. break;
  81. case 'insert':
  82. markup(params);
  83. break;
  84. default:
  85. $.error('Method ' + method + ' does not exist on jQuery.markItUp');
  86. }
  87. return;
  88. }
  89. // apply the computed path to ~/
  90. function localize(data, inText) {
  91. if (inText) {
  92. return data.replace(/("|')~\//g, "$1"+options.root);
  93. }
  94. return data.replace(/^~\//, options.root);
  95. }
  96. // init and build editor
  97. function init() {
  98. id = ''; nameSpace = '';
  99. if (options.id) {
  100. id = 'id="'+options.id+'"';
  101. } else if ($$.attr("id")) {
  102. id = 'id="markItUp'+($$.attr("id").substr(0, 1).toUpperCase())+($$.attr("id").substr(1))+'"';
  103. }
  104. if (options.nameSpace) {
  105. nameSpace = 'class="'+options.nameSpace+'"';
  106. }
  107. $$.wrap('<div '+nameSpace+'></div>');
  108. $$.wrap('<div '+id+' class="markItUp"></div>');
  109. $$.wrap('<div class="markItUpContainer"></div>');
  110. $$.addClass("markItUpEditor");
  111. // add the header before the textarea
  112. header = $('<div class="markItUpHeader"></div>').insertBefore($$);
  113. $(dropMenus(options.markupSet)).appendTo(header);
  114. // add the footer after the textarea
  115. footer = $('<div class="markItUpFooter"></div>').insertAfter($$);
  116. // add the resize handle after textarea
  117. if (options.resizeHandle === true && $.browser.safari !== true) {
  118. resizeHandle = $('<div class="markItUpResizeHandle"></div>')
  119. .insertAfter($$)
  120. .bind("mousedown.markItUp", function(e) {
  121. var h = $$.height(), y = e.clientY, mouseMove, mouseUp;
  122. mouseMove = function(e) {
  123. $$.css("height", Math.max(20, e.clientY+h-y)+"px");
  124. return false;
  125. };
  126. mouseUp = function(e) {
  127. $("html").unbind("mousemove.markItUp", mouseMove).unbind("mouseup.markItUp", mouseUp);
  128. return false;
  129. };
  130. $("html").bind("mousemove.markItUp", mouseMove).bind("mouseup.markItUp", mouseUp);
  131. });
  132. footer.append(resizeHandle);
  133. }
  134. // listen key events
  135. $$.bind('keydown.markItUp', keyPressed).bind('keyup', keyPressed);
  136. // bind an event to catch external calls
  137. $$.bind("insertion.markItUp", function(e, settings) {
  138. if (settings.target !== false) {
  139. get();
  140. }
  141. if (textarea === $.markItUp.focused) {
  142. markup(settings);
  143. }
  144. });
  145. // remember the last focus
  146. $$.bind('focus.markItUp', function() {
  147. $.markItUp.focused = this;
  148. });
  149. if (options.previewInElement) {
  150. refreshPreview();
  151. }
  152. }
  153. // recursively build header with dropMenus from markupset
  154. function dropMenus(markupSet) {
  155. var ul = $('<ul></ul>'), i = 0;
  156. $('li:hover > ul', ul).css('display', 'block');
  157. $.each(markupSet, function() {
  158. var button = this, t = '', title, li, j;
  159. title = (button.key) ? (button.name||'')+' [Ctrl+'+button.key+']' : (button.name||'');
  160. key = (button.key) ? 'accesskey="'+button.key+'"' : '';
  161. if (button.separator) {
  162. li = $('<li class="markItUpSeparator">'+(button.separator||'')+'</li>').appendTo(ul);
  163. } else {
  164. i++;
  165. for (j = levels.length -1; j >= 0; j--) {
  166. t += levels[j]+"-";
  167. }
  168. li = $('<li class="markItUpButton markItUpButton'+t+(i)+' '+(button.className||'')+'"><a href="" '+key+' title="'+title+'">'+(button.name||'')+'</a></li>')
  169. .bind("contextmenu.markItUp", function() { // prevent contextmenu on mac and allow ctrl+click
  170. return false;
  171. }).bind('click.markItUp', function() {
  172. return false;
  173. }).bind("focusin.markItUp", function(){
  174. $$.focus();
  175. }).bind('mouseup', function() {
  176. if (button.call) {
  177. eval(button.call)();
  178. }
  179. setTimeout(function() { markup(button) },1);
  180. return false;
  181. }).bind('mouseenter.markItUp', function() {
  182. $('> ul', this).show();
  183. $(document).one('click', function() { // close dropmenu if click outside
  184. $('ul ul', header).hide();
  185. }
  186. );
  187. }).bind('mouseleave.markItUp', function() {
  188. $('> ul', this).hide();
  189. }).appendTo(ul);
  190. if (button.dropMenu) {
  191. levels.push(i);
  192. $(li).addClass('markItUpDropMenu').append(dropMenus(button.dropMenu));
  193. }
  194. }
  195. });
  196. levels.pop();
  197. return ul;
  198. }
  199. // markItUp! markups
  200. function magicMarkups(string) {
  201. if (string) {
  202. string = string.toString();
  203. string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g,
  204. function(x, a) {
  205. var b = a.split('|!|');
  206. if (altKey === true) {
  207. return (b[1] !== undefined) ? b[1] : b[0];
  208. } else {
  209. return (b[1] === undefined) ? "" : b[0];
  210. }
  211. }
  212. );
  213. // [![prompt]!], [![prompt:!:value]!]
  214. string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g,
  215. function(x, a) {
  216. var b = a.split(':!:');
  217. if (abort === true) {
  218. return false;
  219. }
  220. value = prompt(b[0], (b[1]) ? b[1] : '');
  221. if (value === null) {
  222. abort = true;
  223. }
  224. return value;
  225. }
  226. );
  227. return string;
  228. }
  229. return "";
  230. }
  231. // prepare action
  232. function prepare(action) {
  233. if ($.isFunction(action)) {
  234. action = action(hash);
  235. }
  236. return magicMarkups(action);
  237. }
  238. // build block to insert
  239. function build(string) {
  240. var openWith = prepare(clicked.openWith);
  241. var placeHolder = prepare(clicked.placeHolder);
  242. var replaceWith = prepare(clicked.replaceWith);
  243. var closeWith = prepare(clicked.closeWith);
  244. var openBlockWith = prepare(clicked.openBlockWith);
  245. var closeBlockWith = prepare(clicked.closeBlockWith);
  246. var multiline = clicked.multiline;
  247. if (replaceWith !== "") {
  248. block = openWith + replaceWith + closeWith;
  249. } else if (selection === '' && placeHolder !== '') {
  250. block = openWith + placeHolder + closeWith;
  251. } else {
  252. string = string || selection;
  253. var lines = [string], blocks = [];
  254. if (multiline === true) {
  255. lines = string.split(/\r?\n/);
  256. }
  257. for (var l = 0; l < lines.length; l++) {
  258. line = lines[l];
  259. var trailingSpaces;
  260. if (trailingSpaces = line.match(/ *$/)) {
  261. blocks.push(openWith + line.replace(/ *$/g, '') + closeWith + trailingSpaces);
  262. } else {
  263. blocks.push(openWith + line + closeWith);
  264. }
  265. }
  266. block = blocks.join("\n");
  267. }
  268. block = openBlockWith + block + closeBlockWith;
  269. return { block:block,
  270. openWith:openWith,
  271. replaceWith:replaceWith,
  272. placeHolder:placeHolder,
  273. closeWith:closeWith
  274. };
  275. }
  276. // define markup to insert
  277. function markup(button) {
  278. var len, j, n, i;
  279. hash = clicked = button;
  280. get();
  281. $.extend(hash, { line:"",
  282. root:options.root,
  283. textarea:textarea,
  284. selection:(selection||''),
  285. caretPosition:caretPosition,
  286. ctrlKey:ctrlKey,
  287. shiftKey:shiftKey,
  288. altKey:altKey
  289. }
  290. );
  291. // callbacks before insertion
  292. prepare(options.beforeInsert);
  293. prepare(clicked.beforeInsert);
  294. if ((ctrlKey === true && shiftKey === true) || button.multiline === true) {
  295. prepare(clicked.beforeMultiInsert);
  296. }
  297. $.extend(hash, { line:1 });
  298. if ((ctrlKey === true && shiftKey === true)) {
  299. lines = selection.split(/\r?\n/);
  300. for (j = 0, n = lines.length, i = 0; i < n; i++) {
  301. if ($.trim(lines[i]) !== '') {
  302. $.extend(hash, { line:++j, selection:lines[i] } );
  303. lines[i] = build(lines[i]).block;
  304. } else {
  305. lines[i] = "";
  306. }
  307. }
  308. string = { block:lines.join('\n')};
  309. start = caretPosition;
  310. len = string.block.length + (($.browser.opera) ? n-1 : 0);
  311. } else if (ctrlKey === true) {
  312. string = build(selection);
  313. start = caretPosition + string.openWith.length;
  314. len = string.block.length - string.openWith.length - string.closeWith.length;
  315. len = len - (string.block.match(/ $/) ? 1 : 0);
  316. len -= fixIeBug(string.block);
  317. } else if (shiftKey === true) {
  318. string = build(selection);
  319. start = caretPosition;
  320. len = string.block.length;
  321. len -= fixIeBug(string.block);
  322. } else {
  323. string = build(selection);
  324. start = caretPosition + string.block.length ;
  325. len = 0;
  326. start -= fixIeBug(string.block);
  327. }
  328. if ((selection === '' && string.replaceWith === '')) {
  329. caretOffset += fixOperaBug(string.block);
  330. start = caretPosition + string.openWith.length;
  331. len = string.block.length - string.openWith.length - string.closeWith.length;
  332. caretOffset = $$.val().substring(caretPosition, $$.val().length).length;
  333. caretOffset -= fixOperaBug($$.val().substring(0, caretPosition));
  334. }
  335. $.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } );
  336. if (string.block !== selection && abort === false) {
  337. insert(string.block);
  338. set(start, len);
  339. } else {
  340. caretOffset = -1;
  341. }
  342. get();
  343. $.extend(hash, { line:'', selection:selection });
  344. // callbacks after insertion
  345. if ((ctrlKey === true && shiftKey === true) || button.multiline === true) {
  346. prepare(clicked.afterMultiInsert);
  347. }
  348. prepare(clicked.afterInsert);
  349. prepare(options.afterInsert);
  350. // refresh preview if opened
  351. if (previewWindow && options.previewAutoRefresh) {
  352. refreshPreview();
  353. }
  354. // reinit keyevent
  355. shiftKey = altKey = ctrlKey = abort = false;
  356. }
  357. // Substract linefeed in Opera
  358. function fixOperaBug(string) {
  359. if ($.browser.opera) {
  360. return string.length - string.replace(/\n*/g, '').length;
  361. }
  362. return 0;
  363. }
  364. // Substract linefeed in IE
  365. function fixIeBug(string) {
  366. if ($.browser.msie) {
  367. return string.length - string.replace(/\r*/g, '').length;
  368. }
  369. return 0;
  370. }
  371. // add markup
  372. function insert(block) {
  373. if (document.selection) {
  374. var newSelection = document.selection.createRange();
  375. newSelection.text = block;
  376. } else {
  377. textarea.value = textarea.value.substring(0, caretPosition) + block + textarea.value.substring(caretPosition + selection.length, textarea.value.length);
  378. }
  379. }
  380. // set a selection
  381. function set(start, len) {
  382. if (textarea.createTextRange){
  383. // quick fix to make it work on Opera 9.5
  384. if ($.browser.opera && $.browser.version >= 9.5 && len == 0) {
  385. return false;
  386. }
  387. range = textarea.createTextRange();
  388. range.collapse(true);
  389. range.moveStart('character', start);
  390. range.moveEnd('character', len);
  391. range.select();
  392. } else if (textarea.setSelectionRange ){
  393. textarea.setSelectionRange(start, start + len);
  394. }
  395. textarea.scrollTop = scrollPosition;
  396. textarea.focus();
  397. }
  398. // get the selection
  399. function get() {
  400. textarea.focus();
  401. scrollPosition = textarea.scrollTop;
  402. if (document.selection) {
  403. selection = document.selection.createRange().text;
  404. if ($.browser.msie) { // ie
  405. var range = document.selection.createRange(), rangeCopy = range.duplicate();
  406. rangeCopy.moveToElementText(textarea);
  407. caretPosition = -1;
  408. while(rangeCopy.inRange(range)) {
  409. rangeCopy.moveStart('character');
  410. caretPosition ++;
  411. }
  412. } else { // opera
  413. caretPosition = textarea.selectionStart;
  414. }
  415. } else { // gecko & webkit
  416. caretPosition = textarea.selectionStart;
  417. selection = textarea.value.substring(caretPosition, textarea.selectionEnd);
  418. }
  419. return selection;
  420. }
  421. // open preview window
  422. function preview() {
  423. if (typeof options.previewHandler === 'function') {
  424. previewWindow = true;
  425. } else if (options.previewInElement) {
  426. previewWindow = $(options.previewInElement);
  427. } else if (!previewWindow || previewWindow.closed) {
  428. if (options.previewInWindow) {
  429. previewWindow = window.open('', 'preview', options.previewInWindow);
  430. $(window).unload(function() {
  431. previewWindow.close();
  432. });
  433. } else {
  434. iFrame = $('<iframe class="markItUpPreviewFrame"></iframe>');
  435. if (options.previewPosition == 'after') {
  436. iFrame.insertAfter(footer);
  437. } else {
  438. iFrame.insertBefore(header);
  439. }
  440. previewWindow = iFrame[iFrame.length - 1].contentWindow || frame[iFrame.length - 1];
  441. }
  442. } else if (altKey === true) {
  443. if (iFrame) {
  444. iFrame.remove();
  445. } else {
  446. previewWindow.close();
  447. }
  448. previewWindow = iFrame = false;
  449. }
  450. if (!options.previewAutoRefresh) {
  451. refreshPreview();
  452. }
  453. if (options.previewInWindow) {
  454. previewWindow.focus();
  455. }
  456. }
  457. // refresh Preview window
  458. function refreshPreview() {
  459. renderPreview();
  460. }
  461. function renderPreview() {
  462. var phtml;
  463. if (options.previewHandler && typeof options.previewHandler === 'function') {
  464. options.previewHandler( $$.val() );
  465. } else if (options.previewParser && typeof options.previewParser === 'function') {
  466. var data = options.previewParser( $$.val() );
  467. writeInPreview(localize(data, 1) );
  468. } else if (options.previewParserPath !== '') {
  469. $.ajax({
  470. type: 'POST',
  471. dataType: 'text',
  472. global: false,
  473. url: options.previewParserPath,
  474. data: options.previewParserVar+'='+encodeURIComponent($$.val()),
  475. success: function(data) {
  476. writeInPreview( localize(data, 1) );
  477. }
  478. });
  479. } else {
  480. if (!template) {
  481. $.ajax({
  482. url: options.previewTemplatePath,
  483. dataType: 'text',
  484. global: false,
  485. success: function(data) {
  486. writeInPreview( localize(data, 1).replace(/<!-- content -->/g, $$.val()) );
  487. }
  488. });
  489. }
  490. }
  491. return false;
  492. }
  493. function writeInPreview(data) {
  494. if (options.previewInElement) {
  495. $(options.previewInElement).html(data);
  496. } else if (previewWindow && previewWindow.document) {
  497. try {
  498. sp = previewWindow.document.documentElement.scrollTop
  499. } catch(e) {
  500. sp = 0;
  501. }
  502. previewWindow.document.open();
  503. previewWindow.document.write(data);
  504. previewWindow.document.close();
  505. previewWindow.document.documentElement.scrollTop = sp;
  506. }
  507. }
  508. // set keys pressed
  509. function keyPressed(e) {
  510. shiftKey = e.shiftKey;
  511. altKey = e.altKey;
  512. ctrlKey = (!(e.altKey && e.ctrlKey)) ? (e.ctrlKey || e.metaKey) : false;
  513. if (e.type === 'keydown') {
  514. if (ctrlKey === true) {
  515. li = $('a[accesskey="'+((e.keyCode == 13) ? '\\n' : String.fromCharCode(e.keyCode))+'"]', header).parent('li');
  516. if (li.length !== 0) {
  517. ctrlKey = false;
  518. setTimeout(function() {
  519. li.triggerHandler('mouseup');
  520. },1);
  521. return false;
  522. }
  523. }
  524. if (e.keyCode === 13 || e.keyCode === 10) { // Enter key
  525. if (ctrlKey === true) { // Enter + Ctrl
  526. ctrlKey = false;
  527. markup(options.onCtrlEnter);
  528. return options.onCtrlEnter.keepDefault;
  529. } else if (shiftKey === true) { // Enter + Shift
  530. shiftKey = false;
  531. markup(options.onShiftEnter);
  532. return options.onShiftEnter.keepDefault;
  533. } else { // only Enter
  534. markup(options.onEnter);
  535. return options.onEnter.keepDefault;
  536. }
  537. }
  538. if (e.keyCode === 9) { // Tab key
  539. if (shiftKey == true || ctrlKey == true || altKey == true) {
  540. return false;
  541. }
  542. if (caretOffset !== -1) {
  543. get();
  544. caretOffset = $$.val().length - caretOffset;
  545. set(caretOffset, 0);
  546. caretOffset = -1;
  547. return false;
  548. } else {
  549. markup(options.onTab);
  550. return options.onTab.keepDefault;
  551. }
  552. }
  553. }
  554. }
  555. function remove() {
  556. $$.unbind(".markItUp").removeClass('markItUpEditor');
  557. $$.parent('div').parent('div.markItUp').parent('div').replaceWith($$);
  558. $$.data('markItUp', null);
  559. }
  560. init();
  561. });
  562. };
  563. $.fn.markItUpRemove = function() {
  564. return this.each(function() {
  565. $(this).markItUp('remove');
  566. }
  567. );
  568. };
  569. $.markItUp = function(settings) {
  570. var options = { target:false };
  571. $.extend(options, settings);
  572. if (options.target) {
  573. return $(options.target).each(function() {
  574. $(this).focus();
  575. $(this).trigger('insertion', [options]);
  576. });
  577. } else {
  578. $('textarea').trigger('insertion', [options]);
  579. }
  580. };
  581. })(jQuery);