GreasyFork markdown

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

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

  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.3
  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. var inPostNewScriptVer = location.href.indexOf('/versions/new') > 0;
  42.  
  43.  
  44. // Native $("selector:contains('text')"); https://github.com/nefe/You-Dont-Need-jQuery#1.12
  45. function contains(selector, text) {
  46. var elements = document.querySelectorAll(selector);
  47. return Array.from(elements).filter(function(element) {
  48. return RegExp(text).test(element.textContent);
  49. });
  50. }
  51.  
  52.  
  53. window.addEventListener('DOMContentLoaded', function(e) {
  54.  
  55. var refElements = contains('.label-note', '(See allowed code)' );
  56.  
  57. if (inForum){
  58.  
  59. refElements.forEach(element => {element.insertAdjacentHTML('beforeend','<br>'); addFeatures(element); });
  60.  
  61. }
  62. else { // not in Forum
  63.  
  64. // multiple textareas
  65. if (inPostNewScriptVer) {
  66. refElements = contains('.label-note', '(See allowed code)' );
  67. refElements.forEach(element => { addFeatures(element.appendChild(document.createElement('br'))); });
  68.  
  69. } else { // every other page
  70.  
  71.  
  72. if (nn = document.querySelectorAll('input[value="markdown"]')) {
  73. for (var n, i=0; (i<nn.length) && (n=nn[i]); i++) {
  74. if (location.href.indexOf('/script_versions/')) {
  75. n.click();
  76. }
  77. n.click(); // posting a new script
  78. addFeatures(n.parentNode.appendChild(document.createElement('br')));
  79. }
  80. }
  81.  
  82.  
  83. }
  84.  
  85. }
  86.  
  87.  
  88. });
  89.  
  90.  
  91.  
  92. function insertAfter(referenceNode, newNode) {
  93. referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  94. }
  95.  
  96.  
  97.  
  98. function addFeatures(n) {
  99.  
  100. if (!n){
  101. return;
  102. }
  103.  
  104. var form = n.closest('form');
  105. if (form.action.indexOf('/edit') < 0) {
  106. n.click();
  107. }
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114. if (inPostNewScriptVer) {
  115. n.parentNode.textAreaNode = n.parentNode.querySelector('textarea.TextBox, textarea.previewable, div.previewable textarea');
  116. } else {
  117. n.parentNode.textAreaNode = form.querySelector('textarea.TextBox, textarea.previewable, div.previewable textarea');
  118.  
  119. }
  120.  
  121. // ------------------------------------------------------------------
  122.  
  123.  
  124. // console.log(form.querySelector('textarea.TextBox, textarea.previewable, div.previewable textarea'));
  125. // console.log(form)
  126. // console.log(form.querySelector('textarea.TextBox, textarea.previewable, div.previewable textarea'));
  127. //THIS // n.parentNode.textAreaNode = form.querySelector('textarea.TextBox, textarea.previewable, div.previewable textarea');
  128. // add formatting help tooltips (the '(?)' )
  129.  
  130. // .querySelector('input[value="html').firstElementChild
  131. /*
  132. // n.previousElementSibling.insertAdjacentHTML('beforeend',
  133. // n.querySelector('input[value="html"]').nextSibling.insertAdjacentHTML('beforeend',
  134. const newContent = document.createElement('a');
  135. newContent.innerHTML = '<a href="/help/allowed-markup" target="_blank" title="'+
  136. '* (name, title), a (href), abbr, b, blockquote (cite), br, center, cite, code, dd, del, dfn, div, dl, dt, em, '+
  137. 'h1, h2, h3, h4, h5, h6, hr, i, ins, img (alt, height, src (https), width), kbd, li, mark, ol, p, pre, q (cite), '+
  138. 'rp, rt, ruby, s, samp, small, span, strike, strong, tt, table, tbody, tfoot, thead, td, th, tr, sub, sup, '+
  139. 'time (datetime, pubdate), u, ul, var">?</a>' ;
  140. n.insertAdjacentHTML('beforeend',
  141. ' (<a href="http://www.darkcoding.net/software/markdown-quick-reference/" target="_blank">?</a>)');
  142. // if (location.href.indexOf('/forum/messages/') > -1)
  143. if (location.href.indexOf('/conversations/') > -1)
  144. GM_addStyle('#ConversationForm label { display:inline-block; margin-right:2ex }\
  145. #ConversationForm .TextBox { margin-top:0 }');
  146. */
  147. // ------------------------------------------------------------------
  148.  
  149.  
  150. GM_addStyle('\
  151. .Button {\
  152. display: inline-block;\
  153. cursor: pointer;\
  154. margin: 0px;\
  155. font-size: 12px;\
  156. line-height: 1;\
  157. font-weight: bold;\
  158. padding: 4px 6px;\
  159. background: -moz-linear-gradient(center bottom , #CCC 0%, #FAFAFA 100%) repeat scroll 0% 0% #F8F8F8;\
  160. border: 1px solid #999;\
  161. border-radius: 2px;\
  162. white-space: nowrap;\
  163. text-shadow: 0px 1px 0px #FFF;\
  164. box-shadow: 0px 1px 0px #FFF inset, 0px -1px 2px #BBB inset;\
  165. color: #333;}'
  166. );
  167.  
  168.  
  169.  
  170.  
  171.  
  172.  
  173. // add buttons
  174. // debugger
  175. btnMake(n, '<b>'+__('B')+'</b>', __('Bold'), '**');
  176. btnMake(n, '<i>'+__('I')+'</i>', __('Italic'), '*');
  177. btnMake(n, '<u>'+__('U')+'</u>', __('Underline'), '<u>','</u>');
  178. btnMake(n, '<s>'+__('S')+'</s>', __('Strikethrough'), '<s>','</s>');
  179. btnMake(n, '&lt;br&gt;', __('Force line break'), '<br>','', true);
  180. btnMake(n, '---', __('Horizontal line'), '\n\n---\n\n', '', true);
  181. btnMake(n, __('URL'), __('Add URL to selected text'),
  182. function(e) {
  183. try {edWrapInTag('[', ']('+prompt(__('URL')+':')+')', edInit(e.target))}
  184. catch(ex) {}
  185. });
  186. btnMake(n, __('Image (https)'), __('Convert selected https://url to inline image'), '!['+__('image')+'](', ')');
  187. if (inForum)
  188. btnMake(n, __('Table'), __('Insert table template'), __('\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n'), '', true);
  189. btnMake(n, __('Code'), __('Apply CODE markdown to selected text'),
  190. function(e){
  191. var ed = edInit(e.target);
  192. if (ed.sel.indexOf('\n') < 0)
  193. edWrapInTag('`', '`', ed);
  194. else
  195. edWrapInTag(((ed.sel1==0) || (ed.text.charAt(ed.sel1-1) == '\n') ? '' : '\n') + '```' + (ed.sel.charAt(0) == '\n' ? '' : '\n'),
  196. (ed.sel.substr(-1) == '\n' ? '' : '\n') + '```' + (ed.text.substr(ed.sel2,1) == '\n' ? '' : '\n'),
  197. ed);
  198. });
  199.  
  200.  
  201.  
  202.  
  203.  
  204. var allPreviewTabs = contains('.preview-tab', 'Preview' );
  205. allPreviewTabs.forEach(element => { element.onclick = function(event) {
  206. let target = event.target; // delegation: where was the click?
  207. if (target.tagName !== 'A' && target.tagName !== 'SPAN') {return}
  208. // console.log(element.closest('.label-note') )
  209. form.querySelectorAll('.Button').forEach(element2 => element2.style.display = 'none');
  210. } } );
  211.  
  212. var allWriteTabs = contains('.write-tab', 'Write' );
  213. allWriteTabs.forEach(element => { element.onclick = function(event) {
  214. let target = event.target; // where was the click?
  215. if (target.tagName !== 'A' && target.tagName !== 'SPAN') {return}
  216. form.querySelectorAll('.Button').forEach(element2 => element2.style.display = 'inline-block');
  217. } });
  218.  
  219.  
  220.  
  221.  
  222.  
  223. }
  224.  
  225.  
  226.  
  227.  
  228. function btnMake(afterNode, label, title, tag1_or_cb, tag2, noWrap) {
  229. var a = document.createElement('a');
  230. a.className = 'Button';
  231. a.innerHTML = label;
  232. a.title = title;
  233. // if (inForum)
  234. // a.style.setProperty('float','right');
  235. a.addEventListener('click',
  236. typeof(tag1_or_cb) == 'function' ? tag1_or_cb : // if
  237. noWrap ? function(e){edInsertText(tag1_or_cb, edInit(e.target))} : // else if
  238. function(e){edWrapInTag(tag1_or_cb, tag2, edInit(e.target))} // else
  239. );
  240.  
  241.  
  242. var nparent;
  243. inForum ? nparent = afterNode : nparent = afterNode.parentNode;
  244. a.textAreaNode = nparent.textAreaNode || nparent.parentNode.querySelector('textArea');;
  245. nparent.appendChild(a);
  246. }
  247.  
  248.  
  249.  
  250.  
  251. function edInit(btn) {
  252. var ed = {node: btn.textAreaNode || btn.parentNode.textAreaNode};
  253. ed.sel1 = ed.node.selectionStart;
  254. ed.sel2 = ed.node.selectionEnd,
  255. ed.text = ed.node.value;
  256. ed.sel = ed.text.substring(ed.sel1, ed.sel2);
  257. return ed;
  258. }
  259.  
  260. function edWrapInTag(tag1, tag2, ed) {
  261. ed.node.value = ed.text.substr(0, ed.sel1) + tag1 + ed.sel + (tag2?tag2:tag1) + ed.text.substr(ed.sel2);
  262. ed.node.setSelectionRange(ed.sel1 + tag1.length, ed.sel1 + tag1.length + ed.sel.length);
  263. ed.node.focus();
  264. }
  265.  
  266. function edInsertText(text, ed) {
  267. ed.node.value = ed.text.substr(0, ed.sel2) + text + ed.text.substr(ed.sel2);
  268. ed.node.setSelectionRange(ed.sel2 + text.length, ed.sel2 + text.length);
  269. ed.node.focus();
  270. }
  271.  
  272. var __ = (function (l, langs) {
  273. var lang = langs[l] || langs[l.replace(/-.+/, '')];
  274. return lang ? function (text) { return lang[text] || text; }
  275. : function (text) { return text }; // No matching language, fallback to english
  276. })(location.pathname.match(/^\/(.+?)\//)[1], {
  277. // Can be full name, or just the beginning part.
  278. 'zh-CN': {
  279. 'Bold': '粗体',
  280. 'Italic': '斜体',
  281. 'Underline': '下划线',
  282. 'Strikethrough': '删除线',
  283. 'Force line break': '强制换行',
  284. 'Horizontal line': '水平分割线',
  285. 'URL': '链接',
  286. 'Add URL to selected text': '为所选文字添加链接',
  287. 'Image (https)': '图片 (https)',
  288. 'Convert selected https://url to inline image': '将所选地址转换为行内图片',
  289. 'image': '图片描述', // Default image alt value
  290. 'Table': '表格',
  291. 'Insert table template': '插入表格模板',
  292. 'Code': '代码',
  293. 'Apply CODE markdown to selected text': '将选中代码围起来',
  294.  
  295. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  296. '\n| 表头 1 | 表头 2 |\n|-------|-------|\n| 表格 1 | 表格 2 |\n| 表格 3 | 表格 4 |\n'
  297. },
  298. 'ru': {
  299. 'B': 'Ж',
  300. 'I': 'К',
  301. 'U': 'Ч',
  302. 'S': 'П',
  303. 'Bold': 'Жирный',
  304. 'Italic': 'Курсив',
  305. 'Underline': 'Подчеркнутый',
  306. 'Strikethrough': 'Перечеркнутый',
  307. 'Force line break': 'Новая строка',
  308. 'Horizontal line': 'Горизонтальная линия',
  309. 'URL': 'ссылка',
  310. 'Add URL to selected text': 'Добавить ссылку к выделенному тексту',
  311. 'Image (https)': 'Картинка (https)',
  312. 'Convert selected https://url to inline image': 'Преобразовать выделенный https:// адрес в картинку',
  313. 'image': 'картинка', // Default image alt value
  314. 'Table': 'Таблица',
  315. 'Insert table template': 'Вставить шаблон таблицы',
  316. 'Code': 'Код',
  317. 'Apply CODE markdown to selected text': 'Пометить выделенный фрагмент как программный код',
  318.  
  319. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  320. '\n| заголовок1 | заголовок2 |\n|-------|-------|\n| ячейка1 | ячейка2 |\n| ячейка3 | ячейка4 |\n'
  321. },
  322. 'fr': {
  323. 'B': 'G',
  324. 'I': 'I',
  325. 'U': 'S',
  326. 'S': 'B',
  327. 'Bold': 'Gras',
  328. 'Italic': 'Italique',
  329. 'Underline': 'Souligné',
  330. 'Strikethrough': 'Barré',
  331. 'Force line break': 'Forcer le saut de ligne',
  332. 'Horizontal line': 'Ligne horizontale',
  333. 'URL': 'URL',
  334. 'Add URL to selected text': 'Ajouter URL au texte sélectionné',
  335. 'Image (https)': 'Image (https)',
  336. 'Convert selected https://url to inline image': 'Convertir https://url sélectionnés en images',
  337. 'image': 'image', // Default image alt value
  338. 'Table': 'Tableau',
  339. 'Insert table template': 'Insérer un modèle de table',
  340. 'Code': 'Code',
  341. 'Apply CODE markdown to selected text': 'Appliquer CODE markdown au texte sélectionné',
  342.  
  343. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  344. '\n| En-tête 1 | En-tête 2 |\n|-------|-------|\n| cellule 1 | cellule 2 |\n| cellule 3 | cellule 4 |\n'
  345. }
  346. });