GreasyFork markdown

在论坛默认使用 Markdown 格式,添加格式帮助链接及 Markdown 工具栏

当前为 2021-03-10 提交的版本,查看 最新版本

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