You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jstoolbar.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /**
  2. * This file is part of DotClear.
  3. * Copyright (c) 2005 Nicolas Martin & Olivier Meunier and contributors. All rights reserved.
  4. * This code is released under the GNU General Public License.
  5. *
  6. * Modified by JP LANG for multiple text formatting
  7. */
  8. let lastJstPreviewed = null;
  9. const isMac = Boolean(navigator.platform.toLowerCase().match(/mac/));
  10. function jsToolBar(textarea) {
  11. if (!document.createElement) { return; }
  12. if (!textarea) { return; }
  13. if ((typeof(document["selection"]) == "undefined")
  14. && (typeof(textarea["setSelectionRange"]) == "undefined")) {
  15. return;
  16. }
  17. this.textarea = textarea;
  18. this.toolbarBlock = document.createElement('div');
  19. this.toolbarBlock.className = 'jstBlock';
  20. this.textarea.parentNode.insertBefore(this.toolbarBlock, this.textarea);
  21. this.editor = document.createElement('div');
  22. this.editor.className = 'jstEditor';
  23. this.preview = document.createElement('div');
  24. this.preview.className = 'wiki wiki-preview hidden';
  25. this.preview.setAttribute('id', 'preview_' + textarea.getAttribute('id'));
  26. this.editor.appendChild(this.textarea);
  27. this.editor.appendChild(this.preview);
  28. this.tabsBlock = document.createElement('div');
  29. this.tabsBlock.className = 'jstTabs tabs';
  30. var This = this;
  31. this.textarea.onkeydown = function(event) { This.keyboardShortcuts.call(This, event); };
  32. this.editTab = new jsTab('Edit', true);
  33. this.editTab.onclick = function(event) { This.hidePreview.call(This, event); return false; };
  34. this.previewTab = new jsTab('Preview');
  35. this.previewTab.onclick = function(event) { This.showPreview.call(This, event); return false; };
  36. var elementsTab = document.createElement('li');
  37. elementsTab.classList = 'tab-elements';
  38. var tabs = document.createElement('ul');
  39. tabs.appendChild(this.editTab);
  40. tabs.appendChild(this.previewTab);
  41. tabs.appendChild(elementsTab);
  42. this.tabsBlock.appendChild(tabs);
  43. this.toolbar = document.createElement("div");
  44. this.toolbar.className = 'jstElements';
  45. elementsTab.appendChild(this.toolbar);
  46. this.toolbarBlock.appendChild(this.tabsBlock);
  47. this.toolbarBlock.appendChild(this.editor);
  48. // Dragable resizing
  49. if (this.editor.addEventListener && navigator.appVersion.match(/\bMSIE\b/))
  50. {
  51. this.handle = document.createElement('div');
  52. this.handle.className = 'jstHandle';
  53. var dragStart = this.resizeDragStart;
  54. var This = this;
  55. this.handle.addEventListener('mousedown',function(event) { dragStart.call(This,event); },false);
  56. // fix memory leak in Firefox (bug #241518)
  57. window.addEventListener('unload',function() {
  58. var del = This.handle.parentNode.removeChild(This.handle);
  59. delete(This.handle);
  60. },false);
  61. this.editor.parentNode.insertBefore(this.handle,this.editor.nextSibling);
  62. }
  63. this.context = null;
  64. this.toolNodes = {}; // lorsque la toolbar est dessinée , cet objet est garni
  65. // de raccourcis vers les éléments DOM correspondants aux outils.
  66. }
  67. function jsTab(name, selected) {
  68. selected = selected || false;
  69. if(typeof jsToolBar.strings == 'undefined') {
  70. var tabName = name || null;
  71. } else {
  72. var tabName = jsToolBar.strings[name] || name || null;
  73. }
  74. var tab = document.createElement('li');
  75. var link = document.createElement('a');
  76. link.setAttribute('href', '#');
  77. link.innerText = tabName;
  78. link.className = 'tab-' + name.toLowerCase();
  79. if (selected == true) {
  80. link.classList.add('selected');
  81. }
  82. tab.appendChild(link)
  83. return tab;
  84. }
  85. function jsButton(title, fn, scope, className) {
  86. if(typeof jsToolBar.strings == 'undefined') {
  87. this.title = title || null;
  88. } else {
  89. this.title = jsToolBar.strings[title] || title || null;
  90. }
  91. this.fn = fn || function(){};
  92. this.scope = scope || null;
  93. this.className = className || null;
  94. }
  95. jsButton.prototype.draw = function() {
  96. if (!this.scope) return null;
  97. var button = document.createElement('button');
  98. button.setAttribute('type','button');
  99. button.tabIndex = 200;
  100. if (this.className) button.className = this.className;
  101. button.title = this.title;
  102. var span = document.createElement('span');
  103. span.appendChild(document.createTextNode(this.title));
  104. button.appendChild(span);
  105. if (this.icon != undefined) {
  106. button.style.backgroundImage = 'url('+this.icon+')';
  107. }
  108. if (typeof(this.fn) == 'function') {
  109. var This = this;
  110. button.onclick = function() { try { This.fn.apply(This.scope, arguments) } catch (e) {} return false; };
  111. }
  112. return button;
  113. }
  114. function jsSpace(id) {
  115. this.id = id || null;
  116. this.width = null;
  117. }
  118. jsSpace.prototype.draw = function() {
  119. var span = document.createElement('span');
  120. if (this.id) span.id = this.id;
  121. span.appendChild(document.createTextNode(String.fromCharCode(160)));
  122. span.className = 'jstSpacer';
  123. if (this.width) span.style.marginRight = this.width+'px';
  124. return span;
  125. }
  126. function jsCombo(title, options, scope, fn, className) {
  127. this.title = title || null;
  128. this.options = options || null;
  129. this.scope = scope || null;
  130. this.fn = fn || function(){};
  131. this.className = className || null;
  132. }
  133. jsCombo.prototype.draw = function() {
  134. if (!this.scope || !this.options) return null;
  135. var select = document.createElement('select');
  136. if (this.className) select.className = className;
  137. select.title = this.title;
  138. for (var o in this.options) {
  139. //var opt = this.options[o];
  140. var option = document.createElement('option');
  141. option.value = o;
  142. option.appendChild(document.createTextNode(this.options[o]));
  143. select.appendChild(option);
  144. }
  145. var This = this;
  146. select.onchange = function() {
  147. try {
  148. This.fn.call(This.scope, this.value);
  149. } catch (e) { alert(e); }
  150. return false;
  151. }
  152. return select;
  153. }
  154. jsToolBar.prototype = {
  155. base_url: '',
  156. mode: 'wiki',
  157. elements: {},
  158. help_link: '',
  159. shortcuts: {},
  160. getMode: function() {
  161. return this.mode;
  162. },
  163. setMode: function(mode) {
  164. this.mode = mode || 'wiki';
  165. },
  166. switchMode: function(mode) {
  167. mode = mode || 'wiki';
  168. this.draw(mode);
  169. },
  170. setHelpLink: function(link) {
  171. this.help_link = link;
  172. },
  173. setPreviewUrl: function(url) {
  174. this.previewTab.firstChild.setAttribute('data-url', url);
  175. },
  176. button: function(toolName) {
  177. var tool = this.elements[toolName];
  178. if (typeof tool.fn[this.mode] != 'function') return null;
  179. const className = 'jstb_' + toolName;
  180. let title = tool.title
  181. if (tool.hasOwnProperty('shortcut')) {
  182. this.shortcuts[tool.shortcut] = className;
  183. title = this.buttonTitleWithShortcut(tool.title, tool.shortcut)
  184. }
  185. var b = new jsButton(title, tool.fn[this.mode], this, className);
  186. if (tool.icon != undefined) b.icon = tool.icon;
  187. return b;
  188. },
  189. buttonTitleWithShortcut: function(title, shortcutKey) {
  190. if(typeof jsToolBar.strings == 'undefined') {
  191. var i18nTitle = title || null;
  192. } else {
  193. var i18nTitle = jsToolBar.strings[title] || title || null;
  194. }
  195. if (isMac) {
  196. return i18nTitle + " (⌘" + shortcutKey.toUpperCase() + ")";
  197. } else {
  198. return i18nTitle + " (Ctrl+" + shortcutKey.toUpperCase() + ")";
  199. }
  200. },
  201. space: function(toolName) {
  202. var tool = new jsSpace(toolName)
  203. if (this.elements[toolName].width !== undefined)
  204. tool.width = this.elements[toolName].width;
  205. return tool;
  206. },
  207. combo: function(toolName) {
  208. var tool = this.elements[toolName];
  209. var length = tool[this.mode].list.length;
  210. if (typeof tool[this.mode].fn != 'function' || length == 0) {
  211. return null;
  212. } else {
  213. var options = {};
  214. for (var i=0; i < length; i++) {
  215. var opt = tool[this.mode].list[i];
  216. options[opt] = tool.options[opt];
  217. }
  218. return new jsCombo(tool.title, options, this, tool[this.mode].fn);
  219. }
  220. },
  221. draw: function(mode) {
  222. this.setMode(mode);
  223. // Empty toolbar
  224. while (this.toolbar.hasChildNodes()) {
  225. this.toolbar.removeChild(this.toolbar.firstChild)
  226. }
  227. this.toolNodes = {}; // vide les raccourcis DOM/**/
  228. // Draw toolbar elements
  229. var b, tool, newTool;
  230. for (var i in this.elements) {
  231. b = this.elements[i];
  232. var disabled =
  233. b.type == undefined || b.type == ''
  234. || (b.disabled != undefined && b.disabled)
  235. || (b.context != undefined && b.context != null && b.context != this.context);
  236. if (!disabled && typeof this[b.type] == 'function') {
  237. tool = this[b.type](i);
  238. if (tool) newTool = tool.draw();
  239. if (newTool) {
  240. this.toolNodes[i] = newTool; //mémorise l'accès DOM pour usage éventuel ultérieur
  241. this.toolbar.appendChild(newTool);
  242. }
  243. }
  244. }
  245. },
  246. singleTag: function(stag,etag) {
  247. stag = stag || null;
  248. etag = etag || stag;
  249. if (!stag || !etag) { return; }
  250. this.encloseSelection(stag,etag);
  251. },
  252. encloseLineSelection: function(prefix, suffix, fn) {
  253. this.textarea.focus();
  254. prefix = prefix || '';
  255. suffix = suffix || '';
  256. var start, end, sel, scrollPos, subst, res;
  257. if (typeof(document["selection"]) != "undefined") {
  258. sel = document.selection.createRange().text;
  259. } else if (typeof(this.textarea["setSelectionRange"]) != "undefined") {
  260. start = this.textarea.selectionStart;
  261. end = this.textarea.selectionEnd;
  262. scrollPos = this.textarea.scrollTop;
  263. // go to the start of the line
  264. start = this.textarea.value.substring(0, start).replace(/[^\r\n]*$/g,'').length;
  265. // go to the end of the line
  266. end = this.textarea.value.length - this.textarea.value.substring(end, this.textarea.value.length).replace(/^[^\r\n]*/, '').length;
  267. sel = this.textarea.value.substring(start, end);
  268. }
  269. if (sel.match(/ $/)) { // exclude ending space char, if any
  270. sel = sel.substring(0, sel.length - 1);
  271. suffix = suffix + " ";
  272. }
  273. if (typeof(fn) == 'function') {
  274. res = (sel) ? fn.call(this,sel) : fn('');
  275. } else {
  276. res = (sel) ? sel : '';
  277. }
  278. subst = prefix + res + suffix;
  279. if (typeof(document["selection"]) != "undefined") {
  280. document.selection.createRange().text = subst;
  281. var range = this.textarea.createTextRange();
  282. range.collapse(false);
  283. range.move('character', -suffix.length);
  284. range.select();
  285. } else if (typeof(this.textarea["setSelectionRange"]) != "undefined") {
  286. this.textarea.value = this.textarea.value.substring(0, start) + subst +
  287. this.textarea.value.substring(end);
  288. if (sel || (!prefix && start === end)) {
  289. this.textarea.setSelectionRange(start + subst.length, start + subst.length);
  290. } else {
  291. this.textarea.setSelectionRange(start + prefix.length, start + prefix.length);
  292. }
  293. this.textarea.scrollTop = scrollPos;
  294. }
  295. },
  296. encloseSelection: function(prefix, suffix, fn) {
  297. this.textarea.focus();
  298. prefix = prefix || '';
  299. suffix = suffix || '';
  300. var start, end, sel, scrollPos, subst, res;
  301. if (typeof(document["selection"]) != "undefined") {
  302. sel = document.selection.createRange().text;
  303. } else if (typeof(this.textarea["setSelectionRange"]) != "undefined") {
  304. start = this.textarea.selectionStart;
  305. end = this.textarea.selectionEnd;
  306. scrollPos = this.textarea.scrollTop;
  307. sel = this.textarea.value.substring(start, end);
  308. if (start > 0 && this.textarea.value.substr(start-1, 1).match(/\S/)) {
  309. prefix = ' ' + prefix;
  310. }
  311. if (this.textarea.value.substr(end, 1).match(/\S/)) {
  312. suffix = suffix + ' ';
  313. }
  314. }
  315. if (sel.match(/ $/)) { // exclude ending space char, if any
  316. sel = sel.substring(0, sel.length - 1);
  317. suffix = suffix + " ";
  318. }
  319. if (typeof(fn) == 'function') {
  320. res = (sel) ? fn.call(this,sel) : fn('');
  321. } else {
  322. res = (sel) ? sel : '';
  323. }
  324. subst = prefix + res + suffix;
  325. if (typeof(document["selection"]) != "undefined") {
  326. document.selection.createRange().text = subst;
  327. var range = this.textarea.createTextRange();
  328. range.collapse(false);
  329. range.move('character', -suffix.length);
  330. range.select();
  331. // this.textarea.caretPos -= suffix.length;
  332. } else if (typeof(this.textarea["setSelectionRange"]) != "undefined") {
  333. this.textarea.value = this.textarea.value.substring(0, start) + subst +
  334. this.textarea.value.substring(end);
  335. if (sel) {
  336. this.textarea.setSelectionRange(start + subst.length, start + subst.length);
  337. } else {
  338. this.textarea.setSelectionRange(start + prefix.length, start + prefix.length);
  339. }
  340. this.textarea.scrollTop = scrollPos;
  341. }
  342. },
  343. showPreview: function(event) {
  344. if (event.target.classList.contains('selected')) { return; }
  345. lastJstPreviewed = this.toolbarBlock;
  346. this.preview.setAttribute('style', 'min-height: ' + this.textarea.clientHeight + 'px;')
  347. this.toolbar.classList.add('hidden');
  348. this.textarea.classList.add('hidden');
  349. this.preview.classList.remove('hidden');
  350. this.tabsBlock.querySelector('.tab-edit').classList.remove('selected');
  351. event.target.classList.add('selected');
  352. },
  353. hidePreview: function(event) {
  354. if (event.target.classList.contains('selected')) { return; }
  355. this.toolbar.classList.remove('hidden');
  356. this.textarea.classList.remove('hidden');
  357. this.textarea.focus();
  358. this.preview.classList.add('hidden');
  359. this.tabsBlock.querySelector('.tab-preview').classList.remove('selected');
  360. event.target.classList.add('selected');
  361. },
  362. keyboardShortcuts: function(e) {
  363. let stop = false;
  364. if (isToogleEditPreviewShortcut(e)) {
  365. // Switch to preview only if Edit tab is selected when the event triggers.
  366. if (this.tabsBlock.querySelector('.tab-edit.selected')) {
  367. stop = true
  368. this.tabsBlock.querySelector('.tab-preview').click();
  369. }
  370. }
  371. if (isModifierKey(e) && this.shortcuts.hasOwnProperty(e.key.toLowerCase())) {
  372. stop = true
  373. this.toolbar.querySelector("." + this.shortcuts[e.key.toLowerCase()]).click();
  374. }
  375. if (stop) {
  376. e.stopPropagation();
  377. e.preventDefault();
  378. }
  379. },
  380. stripBaseURL: function(url) {
  381. if (this.base_url != '') {
  382. var pos = url.indexOf(this.base_url);
  383. if (pos == 0) {
  384. url = url.substr(this.base_url.length);
  385. }
  386. }
  387. return url;
  388. }
  389. };
  390. /** Resizer
  391. -------------------------------------------------------- */
  392. jsToolBar.prototype.resizeSetStartH = function() {
  393. this.dragStartH = this.textarea.offsetHeight + 0;
  394. };
  395. jsToolBar.prototype.resizeDragStart = function(event) {
  396. var This = this;
  397. this.dragStartY = event.clientY;
  398. this.resizeSetStartH();
  399. document.addEventListener('mousemove', this.dragMoveHdlr=function(event){This.resizeDragMove(event);}, false);
  400. document.addEventListener('mouseup', this.dragStopHdlr=function(event){This.resizeDragStop(event);}, false);
  401. };
  402. jsToolBar.prototype.resizeDragMove = function(event) {
  403. this.textarea.style.height = (this.dragStartH+event.clientY-this.dragStartY)+'px';
  404. };
  405. jsToolBar.prototype.resizeDragStop = function(event) {
  406. document.removeEventListener('mousemove', this.dragMoveHdlr, false);
  407. document.removeEventListener('mouseup', this.dragStopHdlr, false);
  408. };
  409. /* Code highlighting menu */
  410. jsToolBar.prototype.precodeMenu = function(fn){
  411. var hlLanguages = window.userHlLanguages;
  412. var menu = $("<ul style='position:absolute;'></ul>");
  413. for (var i = 0; i < hlLanguages.length; i++) {
  414. var langItem = $('<div></div>').text(hlLanguages[i]);
  415. $("<li></li>").html(langItem).appendTo(menu).mousedown(function(){
  416. fn($(this).text());
  417. });
  418. }
  419. $("body").append(menu);
  420. menu.menu().width(150).position({
  421. my: "left top",
  422. at: "left bottom",
  423. of: this.toolNodes['precode']
  424. });
  425. $(document).on("mousedown", function() {
  426. menu.remove();
  427. });
  428. return false;
  429. };
  430. /* Table generator */
  431. jsToolBar.prototype.tableMenu = function(fn){
  432. var alphabets = "ABCDEFGHIJ".split('');
  433. var menu = $("<table class='table-generator'></table>");
  434. for (var r = 1; r <= 5; r++) {
  435. var row = $("<tr></tr>").appendTo(menu);
  436. for (var c = 1; c <= 10; c++) {
  437. $("<td data-row="+r+" data-col="+c+" title="+(c)+'&times;'+(r)+"></td>").mousedown(function(){
  438. fn(alphabets.slice(0, $(this).data('col')), $(this).data('row'));
  439. }).hover(function(){
  440. var hoverRow = $(this).data('row');
  441. var hoverCol = $(this).data('col');
  442. $(this).closest('table').find('td').each(function(_index, element){
  443. if ($(element).data('row') <= hoverRow && $(element).data('col') <= hoverCol){
  444. $(element).addClass('selected-cell');
  445. } else {
  446. $(element).removeClass('selected-cell');
  447. }
  448. });
  449. }).appendTo(row);
  450. }
  451. }
  452. $("body").append(menu);
  453. menu.position({
  454. my: "left top",
  455. at: "left bottom",
  456. of: this.toolNodes['table']
  457. });
  458. $(document).on("mousedown", function() {
  459. menu.remove();
  460. });
  461. return false;
  462. };
  463. $(document).keydown(function(e) {
  464. if (isToogleEditPreviewShortcut(e)) {
  465. if (lastJstPreviewed !== null) {
  466. e.preventDefault();
  467. e.stopPropagation();
  468. lastJstPreviewed.querySelector('.tab-edit').click();
  469. lastJstPreviewed = null;
  470. }
  471. }
  472. });
  473. function isToogleEditPreviewShortcut(e) {
  474. if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'p') {
  475. return true;
  476. } else {
  477. return false;
  478. }
  479. }
  480. function isModifierKey(e) {
  481. if (isMac && e.metaKey) {
  482. return true;
  483. } else if (!isMac && e.ctrlKey) {
  484. return true;
  485. } else {
  486. return false;
  487. }
  488. }