jquery.markitup.js 18 KB

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