Greasy Fork is available in English.

Markdown toolbar for GreasyFork

Select Markdown format by default, add help links, add toolbar formatting buttons for markdown

Fra 08.03.2021. Se den seneste versjonen.

  1. // ==UserScript==
  2. // @name Markdown toolbar for GreasyFork
  3. // @name:ru Markdown-тулбар для GreasyFork
  4. // @name:zh-CN GreasyFork markdown
  5. // @author wOxxOm, darkred
  6. // @contributor JixunMoe
  7. // @license MIT License
  8. // @description Select Markdown format by default, add help links, add toolbar formatting buttons for markdown
  9. // @description:ru Включает формат Markdown по умолчанию, добавляет справочные ссылки по форматам, добавляет панель кнопок форматирования markdown
  10. // @description:zh-CN 在论坛默认使用 Markdown 格式,添加格式帮助链接及 Markdown 工具栏
  11. // @icon https://raw.githubusercontent.com/dcurtis/markdown-mark/master/png/66x40-solid.png
  12. // @namespace wOxxOm.scripts
  13. // @version 2.0.0
  14. // @include https://greatest.deepsurf.us/*discussions/*
  15. // @include https://greatest.deepsurf.us/*scripts/*/versions/new*
  16. // @include https://greatest.deepsurf.us/*script_versions/new*
  17. // @include https://greatest.deepsurf.us/*/conversations/*
  18. // @include https://greatest.deepsurf.us/en/users/edit
  19. // @run-at document-start
  20. // @grant GM_addStyle
  21. // ==/UserScript==
  22.  
  23. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  24.  
  25.  
  26. // @include https://forum.userstyles.org/discussion/*
  27. // @include https://forum.userstyles.org/post/discussion*
  28. // @include https://forum.userstyles.org/messages/*
  29. // @include https://forum.userstyles.org/messages/add*
  30. // @include https://forum.userstyles.org/*/editdiscussion/*
  31.  
  32. var inForum = location.href.indexOf('/discussions') > 0;
  33.  
  34. window.addEventListener('DOMContentLoaded', function(e) {
  35. if (inForum){
  36. addFeatures(document.querySelector('.label-note > input').parentNode.appendChild(document.createElement('br')));
  37. }
  38. else {
  39.  
  40. if (nn = document.querySelectorAll('input[value="markdown"]'))
  41. for (var n, i=0; (i<nn.length) && (n=nn[i]); i++) {
  42. if (location.href.indexOf('/script_versions/')) {
  43. n.click();
  44. }
  45. n.click(); // posting a new script
  46. addFeatures(n.parentNode.appendChild(document.createElement('br')));
  47. }
  48.  
  49. // addFeatures(document.querySelector('.form-control'));
  50. }
  51.  
  52. new MutationObserver(function(mutations) {
  53. for (var i=0, ml=mutations.length, m; (i<ml) && (m=mutations[i]); i++) {
  54. for (var j=0, nodes=m.addedNodes, nl=nodes.length, n; (j<nl) && (n=nodes[j]); j++) {
  55. if (n.nodeType == 1) // Node.ELEMENT_NODE 1 An Element node like <p> or <div>.
  56. if (inForum) {
  57. if ((n.localName == 'label' && n.querySelector('input[value="Markdown"], input[value="Html"], input[value="markdown"], input[value="html"]'))
  58. || (n = n.querySelector('input[value="Markdown"], input[value="markdown"]') || n.querySelector('input[value="Html"], input[value="html"]')))
  59. return addFeatures(n.closest('label'));
  60. } else {
  61. if (((n.localName == 'input') && (n.value.toLowerCase() == 'Markdown'))
  62. || (n = n.querySelector('input[value="Markdown"], input[value="markdown"]'))) {
  63. if (location.href.indexOf('/script_versions/'))
  64. n.click();
  65. return addFeatures(n.parentNode.appendChild(document.createElement('br')));
  66. }
  67. }
  68. }
  69. }
  70. }).observe(document, {subtree:true, childList:true});
  71. });
  72.  
  73.  
  74.  
  75.  
  76.  
  77. function addFeatures(n) {
  78.  
  79. if (!n){
  80. return;
  81. }
  82.  
  83. /*
  84. if (!inForum) {
  85. */
  86. var form = n.closest('form');
  87. // span.current > a.write-tab
  88. // var form = n.querySelector('form');
  89. if (form.action.indexOf('/edit') < 0) {
  90. n.click();
  91. }
  92.  
  93. n.parentNode.textAreaNode = form.querySelector('textarea.TextBox, textarea.previewable');
  94. // add formatting help tooltips (the '(?)' )
  95. n.previousElementSibling.insertAdjacentHTML('beforeend',
  96. ' (<a href="/help/allowed-markup" target="_blank" title="'+
  97. '* (name, title), a (href), abbr, b, blockquote (cite), br, center, cite, code, dd, del, dfn, div, dl, dt, em, '+
  98. 'h1, h2, h3, h4, h5, h6, hr, i, ins, img (alt, height, src (https), width), kbd, li, mark, ol, p, pre, q (cite), '+
  99. 'rp, rt, ruby, s, samp, small, span, strike, strong, tt, table, tbody, tfoot, thead, td, th, tr, sub, sup, '+
  100. 'time (datetime, pubdate), u, ul, var">?</a>)');
  101. n.insertAdjacentHTML('beforeend',
  102. ' (<a href="http://www.darkcoding.net/software/markdown-quick-reference/" target="_blank">?</a>)');
  103. // if (location.href.indexOf('/forum/messages/') > -1)
  104. if (location.href.indexOf('/conversations/') > -1)
  105. GM_addStyle('#ConversationForm label { display:inline-block; margin-right:2ex }\
  106. #ConversationForm .TextBox { margin-top:0 }');
  107.  
  108.  
  109. /*
  110.  
  111. } else { // if not in forum
  112. */
  113. for (var wrapper=n; wrapper = wrapper.parentNode; )
  114. // if (t = wrapper.querySelector('textarea[id*="additional-info"]')) {
  115. if (t = wrapper.querySelector('textarea[id*="additional-info"], textarea[id*="conversation_messages_attributes_0_content"], textarea[id*="discussion_comments_attributes_0_text"], textarea[id*="comment_text"], textarea[id*="user_profile"]')) {
  116. n.parentNode.textAreaNode = t;
  117. break;
  118. }
  119. GM_addStyle('\
  120. .Button {\
  121. display: inline-block;\
  122. cursor: pointer;\
  123. margin: 0px;\
  124. font-size: 12px;\
  125. line-height: 1;\
  126. font-weight: bold;\
  127. padding: 4px 6px;\
  128. background: -moz-linear-gradient(center bottom , #CCC 0%, #FAFAFA 100%) repeat scroll 0% 0% #F8F8F8;\
  129. border: 1px solid #999;\
  130. border-radius: 2px;\
  131. white-space: nowrap;\
  132. text-shadow: 0px 1px 0px #FFF;\
  133. box-shadow: 0px 1px 0px #FFF inset, 0px -1px 2px #BBB inset;\
  134. color: #333;}'
  135. );
  136.  
  137. // }
  138.  
  139.  
  140.  
  141.  
  142. // add buttons
  143. // console.log(n);
  144. // debugger
  145. btnMake(n, '<b>'+__('B')+'</b>', __('Bold'), '**');
  146. btnMake(n, '<i>'+__('I')+'</i>', __('Italic'), '*');
  147. btnMake(n, '<u>'+__('U')+'</u>', __('Underline'), '<u>','</u>');
  148. btnMake(n, '<s>'+__('S')+'</s>', __('Strikethrough'), '<s>','</s>');
  149. btnMake(n, '&lt;br&gt;', __('Force line break'), '<br>','', true);
  150. btnMake(n, '---', __('Horizontal line'), '\n\n---\n\n', '', true);
  151. btnMake(n, __('URL'), __('Add URL to selected text'),
  152. function(e) {
  153. try {edWrapInTag('[', ']('+prompt(__('URL')+':')+')', edInit(e.target))}
  154. catch(ex) {}
  155. });
  156. btnMake(n, __('Image (https)'), __('Convert selected https://url to inline image'), '!['+__('image')+'](', ')');
  157. if (inForum)
  158. btnMake(n, __('Table'), __('Insert table template'), __('\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n'), '', true);
  159. btnMake(n, __('Code'), __('Apply CODE markdown to selected text'),
  160. function(e){
  161. var ed = edInit(e.target);
  162. if (ed.sel.indexOf('\n') < 0)
  163. edWrapInTag('`', '`', ed);
  164. else
  165. edWrapInTag(((ed.sel1==0) || (ed.text.charAt(ed.sel1-1) == '\n') ? '' : '\n') + '```' + (ed.sel.charAt(0) == '\n' ? '' : '\n'),
  166. (ed.sel.substr(-1) == '\n' ? '' : '\n') + '```' + (ed.text.substr(ed.sel2,1) == '\n' ? '' : '\n'),
  167. ed);
  168. });
  169.  
  170.  
  171.  
  172.  
  173. var previewTab = document.querySelector('span > a.preview-tab > span');
  174. if (previewTab){
  175. previewTab.onclick = function(){
  176. document.querySelectorAll('.Button').forEach(element => element.style.display = 'none');
  177. };
  178. }
  179.  
  180. var writeTab = document.querySelector('span > a.write-tab > span');
  181. if (writeTab){
  182. writeTab.onclick = function(){
  183. document.querySelectorAll('.Button').forEach(element => element.style.display = 'inline-block');
  184. };
  185. }
  186.  
  187.  
  188.  
  189.  
  190. }
  191.  
  192.  
  193.  
  194.  
  195. function btnMake(afterNode, label, title, tag1_or_cb, tag2, noWrap) {
  196. var a = document.createElement('a');
  197. a.className = 'Button';
  198. a.innerHTML = label;
  199. a.title = title;
  200. // if (inForum)
  201. // a.style.setProperty('float','right');
  202. a.addEventListener('click',
  203. typeof(tag1_or_cb) == 'function' ? tag1_or_cb : // if
  204. noWrap ? function(e){edInsertText(tag1_or_cb, edInit(e.target))} : // else if
  205. function(e){edWrapInTag(tag1_or_cb, tag2, edInit(e.target))} // else
  206. );
  207. var nparent = afterNode.parentNode;
  208. console.log(nparent)
  209. // a.textAreaNode = nparent.textAreaNode ;
  210. a.textAreaNode = nparent.parentNode.querySelector('textArea');
  211. // console.log(a.textAreaNode)
  212. // inForum ? nparent.insertBefore(a, nparent.firstElementChild) : nparent.appendChild(a);
  213. // nparent.insertBefore(a, nparent.firstElementChild)
  214. nparent.appendChild(a);
  215. }
  216.  
  217.  
  218.  
  219.  
  220. function edInit(btn) {
  221. var ed = {node: btn.textAreaNode || btn.parentNode.textAreaNode};
  222. ed.sel1 = ed.node.selectionStart;
  223. ed.sel2 = ed.node.selectionEnd,
  224. ed.text = ed.node.value;
  225. ed.sel = ed.text.substring(ed.sel1, ed.sel2);
  226. return ed;
  227. }
  228.  
  229. function edWrapInTag(tag1, tag2, ed) {
  230. ed.node.value = ed.text.substr(0, ed.sel1) + tag1 + ed.sel + (tag2?tag2:tag1) + ed.text.substr(ed.sel2);
  231. ed.node.setSelectionRange(ed.sel1 + tag1.length, ed.sel1 + tag1.length + ed.sel.length);
  232. ed.node.focus();
  233. }
  234.  
  235. function edInsertText(text, ed) {
  236. ed.node.value = ed.text.substr(0, ed.sel2) + text + ed.text.substr(ed.sel2);
  237. ed.node.setSelectionRange(ed.sel2 + text.length, ed.sel2 + text.length);
  238. ed.node.focus();
  239. }
  240.  
  241. var __ = (function (l, langs) {
  242. var lang = langs[l] || langs[l.replace(/-.+/, '')];
  243. return lang ? function (text) { return lang[text] || text; }
  244. : function (text) { return text }; // No matching language, fallback to english
  245. })(location.pathname.match(/^\/(.+?)\//)[1], {
  246. // Can be full name, or just the beginning part.
  247. 'zh-CN': {
  248. 'Bold': '粗体',
  249. 'Italic': '斜体',
  250. 'Underline': '下划线',
  251. 'Strikethrough': '删除线',
  252. 'Force line break': '强制换行',
  253. 'Horizontal line': '水平分割线',
  254. 'URL': '链接',
  255. 'Add URL to selected text': '为所选文字添加链接',
  256. 'Image (https)': '图片 (https)',
  257. 'Convert selected https://url to inline image': '将所选地址转换为行内图片',
  258. 'image': '图片描述', // Default image alt value
  259. 'Table': '表格',
  260. 'Insert table template': '插入表格模板',
  261. 'Code': '代码',
  262. 'Apply CODE markdown to selected text': '将选中代码围起来',
  263.  
  264. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  265. '\n| 表头 1 | 表头 2 |\n|-------|-------|\n| 表格 1 | 表格 2 |\n| 表格 3 | 表格 4 |\n'
  266. },
  267. 'ru': {
  268. 'B': 'Ж',
  269. 'I': 'К',
  270. 'U': 'Ч',
  271. 'S': 'П',
  272. 'Bold': 'Жирный',
  273. 'Italic': 'Курсив',
  274. 'Underline': 'Подчеркнутый',
  275. 'Strikethrough': 'Перечеркнутый',
  276. 'Force line break': 'Новая строка',
  277. 'Horizontal line': 'Горизонтальная линия',
  278. 'URL': 'ссылка',
  279. 'Add URL to selected text': 'Добавить ссылку к выделенному тексту',
  280. 'Image (https)': 'Картинка (https)',
  281. 'Convert selected https://url to inline image': 'Преобразовать выделенный https:// адрес в картинку',
  282. 'image': 'картинка', // Default image alt value
  283. 'Table': 'Таблица',
  284. 'Insert table template': 'Вставить шаблон таблицы',
  285. 'Code': 'Код',
  286. 'Apply CODE markdown to selected text': 'Пометить выделенный фрагмент как программный код',
  287.  
  288. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  289. '\n| заголовок1 | заголовок2 |\n|-------|-------|\n| ячейка1 | ячейка2 |\n| ячейка3 | ячейка4 |\n'
  290. },
  291. 'fr': {
  292. 'B': 'G',
  293. 'I': 'I',
  294. 'U': 'S',
  295. 'S': 'B',
  296. 'Bold': 'Gras',
  297. 'Italic': 'Italique',
  298. 'Underline': 'Souligné',
  299. 'Strikethrough': 'Barré',
  300. 'Force line break': 'Forcer le saut de ligne',
  301. 'Horizontal line': 'Ligne horizontale',
  302. 'URL': 'URL',
  303. 'Add URL to selected text': 'Ajouter URL au texte sélectionné',
  304. 'Image (https)': 'Image (https)',
  305. 'Convert selected https://url to inline image': 'Convertir https://url sélectionnés en images',
  306. 'image': 'image', // Default image alt value
  307. 'Table': 'Tableau',
  308. 'Insert table template': 'Insérer un modèle de table',
  309. 'Code': 'Code',
  310. 'Apply CODE markdown to selected text': 'Appliquer CODE markdown au texte sélectionné',
  311.  
  312. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  313. '\n| En-tête 1 | En-tête 2 |\n|-------|-------|\n| cellule 1 | cellule 2 |\n| cellule 3 | cellule 4 |\n'
  314. }
  315. });