PageRenderTime 62ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/media/foundry/2.1/scripts_/markitup.js

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