GreasyFork markdown

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

当前为 2014-12-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GreasyFork markdown
  3. // @name:ru GreasyFork markdown
  4. // @name:zh-CN GreasyFork markdown
  5. // @author wOxxOm
  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 1.3.0
  14. // @include https://greasyfork.org/*forum/discussion/*
  15. // @include https://greasyfork.org/*forum/post/discussion*
  16. // @include https://greasyfork.org/*scripts/*/versions/new
  17. // @include https://greasyfork.org/*script_versions/new
  18. // @run-at document-start
  19. // @grant GM_addStyle
  20. // ==/UserScript==
  21.  
  22. var inForum = location.href.indexOf('/forum/') > 0;
  23.  
  24. var ob = new MutationObserver(function(mutations){
  25. for (var i=0, ml=mutations.length, m; (i<ml) && (m=mutations[i]); i++)
  26. for (var j=0, nodes=m.addedNodes, nl=nodes.length, n; (j<nl) && (n=nodes[j]); j++)
  27. if (n.nodeType == 1)
  28. if (inForum) {
  29. if (((n.localName == 'label') && (n.for == 'Form_Format2'))
  30. || (n = n.querySelector('label[for="Form_Format2"]')))
  31. return addFeatures(n);
  32. } else {
  33. if (((n.localName == 'input') && (n.value == 'markdown'))
  34. || (n = n.querySelector('input[value="markdown"]'))) {
  35. if (location.href.indexOf('/script_versions/'))
  36. n.click();
  37. return addFeatures(n.parentNode.appendChild(document.createElement('br')));
  38. }
  39. }
  40. });
  41. ob.observe(document, {subtree:true, childList:true});
  42.  
  43. function addFeatures(n) {
  44. for (var form=n; (form = form.parentNode) && (form.localName != 'form'); ) {}
  45. if (inForum) {
  46. if (form.action.indexOf('/editcomment/') < 0)
  47. n.click();
  48.  
  49. n.parentNode.textAreaNode = form.querySelector('textarea');
  50.  
  51. // add formatting help tooltips
  52. n.previousElementSibling.insertAdjacentHTML('beforeend',
  53. ' (<a href="/help/allowed-markup" target="_blank" title="'+
  54. '* (name, title), a (href), abbr, b, blockquote (cite), br, center, cite, code, dd, del, dfn, div, dl, dt, em, '+
  55. 'h1, h2, h3, h4, h5, h6, hr, i, ins, img (alt, height, src (https), width), kbd, li, mark, ol, p, pre, q (cite), '+
  56. 'rp, rt, ruby, s, samp, small, span, strike, strong, tt, table, tbody, tfoot, thead, td, th, tr, sub, sup, '+
  57. 'time (datetime, pubdate), u, ul, var">?</a>)');
  58. n.insertAdjacentHTML('beforeend',
  59. ' (<a href="http://www.darkcoding.net/software/markdown-quick-reference/" target="_blank">?</a>)');
  60. } else {
  61. n.parentNode.textAreaNode = form.querySelector('textarea[id*="additional-info"]');
  62. GM_addStyle('.Button {\
  63. display: inline-block;\
  64. cursor: pointer;\
  65. margin: 0px;\
  66. font-size: 12px;\
  67. line-height: 1;\
  68. font-weight: bold;\
  69. padding: 4px 6px;\
  70. background: -moz-linear-gradient(center bottom , #CCC 0%, #FAFAFA 100%) repeat scroll 0% 0% #F8F8F8;\
  71. border: 1px solid #999;\
  72. border-radius: 2px;\
  73. white-space: nowrap;\
  74. text-shadow: 0px 1px 0px #FFF;\
  75. box-shadow: 0px 1px 0px #FFF inset, 0px -1px 2px #BBB inset;\
  76. color: #333;}');
  77. }
  78.  
  79. // add buttons
  80. btnMake(n, '<b>'+__('B')+'</b>', __('Bold'), '**');
  81. btnMake(n, '<i>'+__('I')+'</i>', __('Italic'), '*');
  82. btnMake(n, '<u>'+__('U')+'</u>', __('Underline'), '<u>','</u>');
  83. btnMake(n, '<s>'+__('S')+'</s>', __('Strikethrough'), '<s>','</s>');
  84. btnMake(n, '&lt;br&gt;', __('Force line break'), '<br>','', true);
  85. btnMake(n, '---', __('Horizontal line'), '\n\n---\n\n', '', true);
  86. btnMake(n, __('URL'), __('Add URL to selected text'),
  87. function(e) {
  88. try {edWrapInTag('[', ']('+prompt(__('URL')+':')+')', edInit(e.target))}
  89. catch(e) {};
  90. });
  91. btnMake(n, __('Image (https)'), __('Convert selected https://url to inline image'), '!['+__('image')+'](', ')');
  92. if (inForum)
  93. btnMake(n, __('Table'), __('Insert table template'), __('\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n'), '', true);
  94. btnMake(n, __('Code'), __('Apply CODE markdown to selected text'),
  95. function(e){
  96. var ed = edInit(e.target);
  97. if (ed.sel.indexOf('\n') < 0)
  98. edWrapInTag('`', '`', ed);
  99. else
  100. edWrapInTag(((ed.sel1==0) || (ed.text.charAt(ed.sel1-1) == '\n') ? '' : '\n') + '```' + (ed.sel.charAt(0) == '\n' ? '' : '\n'),
  101. (ed.sel.substr(-1) == '\n' ? '' : '\n') + '```' + (ed.text.substr(ed.sel2,1) == '\n' ? '' : '\n'),
  102. ed);
  103. });
  104. }
  105.  
  106. function btnMake(afterNode, label, title, tag1_or_cb, tag2, noWrap) {
  107. var a = document.createElement('a');
  108. a.className = 'Button';
  109. a.innerHTML = label;
  110. a.title = title;
  111. if (inForum)
  112. a.style.setProperty('float','right');
  113. a.addEventListener('click',
  114. typeof(tag1_or_cb) == 'function'
  115. ? tag1_or_cb
  116. : noWrap ? function(e){edInsertText(tag1_or_cb, edInit(e.target))}
  117. : function(e){edWrapInTag(tag1_or_cb, tag2, edInit(e.target))});
  118. var nparent = afterNode.parentNode;
  119. a.textAreaNode = nparent.textAreaNode;
  120. inForum ? nparent.insertBefore(a, afterNode.nextElementSibling) : nparent.appendChild(a);
  121. }
  122.  
  123. function edInit(btn) {
  124. var ed = {node: btn.textAreaNode || btn.parentNode.textAreaNode}
  125. ed.sel1 = ed.node.selectionStart;
  126. ed.sel2 = ed.node.selectionEnd,
  127. ed.text = ed.node.value;
  128. ed.sel = ed.text.substring(ed.sel1, ed.sel2);
  129. return ed;
  130. }
  131.  
  132. function edWrapInTag(tag1, tag2, ed) {
  133. ed.node.value = ed.text.substr(0, ed.sel1) + tag1 + ed.sel + (tag2?tag2:tag1) + ed.text.substr(ed.sel2);
  134. ed.node.setSelectionRange(ed.sel1 + tag1.length, ed.sel1 + tag1.length + ed.sel.length);
  135. ed.node.focus();
  136. }
  137.  
  138. function edInsertText(text, ed) {
  139. ed.node.value = ed.text.substr(0, ed.sel2) + text + ed.text.substr(ed.sel2);
  140. ed.node.setSelectionRange(ed.sel2 + text.length, ed.sel2 + text.length);
  141. ed.node.focus();
  142. }
  143.  
  144. var __ = (function (l, langs) {
  145. var lang = langs[l] || langs[l.replace(/-.+/, '')];
  146. return lang ? function (text) { return lang[text] || text; }
  147. : function (text) { return text; } // No matching language, fallback to english
  148. })(location.pathname.match(/^\/(.+?)\//)[1], {
  149. // Can be full name, or just the beginning part.
  150. 'zh-CN': {
  151. 'Bold': '粗体',
  152. 'Italic': '斜体',
  153. 'Underline': '下划线',
  154. 'Strikethrough': '删除线',
  155. 'Force line break': '强制换行',
  156. 'Horizontal line': '水平分割线',
  157. 'URL': '链接',
  158. 'Add URL to selected text': '为所选文字添加链接',
  159. 'Image (https)': '图片 (https)',
  160. 'Convert selected https://url to inline image': '将所选地址转换为行内图片',
  161. 'image': '图片描述', // Default image alt value
  162. 'Table': '表格',
  163. 'Insert table template': '插入表格模板',
  164. 'Code': '代码',
  165. 'Apply CODE markdown to selected text': '将选中代码围起来',
  166.  
  167. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  168. '\n| 表头 1 | 表头 2 |\n|-------|-------|\n| 表格 1 | 表格 2 |\n| 表格 3 | 表格 4 |\n'
  169. },
  170. 'ru': {
  171. 'B': 'Ж',
  172. 'I': 'К',
  173. 'U': 'Ч',
  174. 'S': 'П',
  175. 'Bold': 'Жирный',
  176. 'Italic': 'Курсив',
  177. 'Underline': 'Подчеркнутый',
  178. 'Strikethrough': 'Перечеркнутый',
  179. 'Force line break': 'Новая строка',
  180. 'Horizontal line': 'Горизонтальная линия',
  181. 'URL': 'ссылка',
  182. 'Add URL to selected text': 'Добавить ссылку к выделенному тексту',
  183. 'Image (https)': 'Картинка (https)',
  184. 'Convert selected https://url to inline image': 'Преобразовать выделенный https:// адрес в картинку',
  185. 'image': 'картинка', // Default image alt value
  186. 'Table': 'Таблица',
  187. 'Insert table template': 'Вставить шаблон таблицы',
  188. 'Code': 'Код',
  189. 'Apply CODE markdown to selected text': 'Пометить выделенный фрагмент как программный код',
  190.  
  191. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  192. '\n| заголовок1 | заголовок2 |\n|-------|-------|\n| ячейка1 | ячейка2 |\n| ячейка3 | ячейка4 |\n'
  193. }
  194. });