GreasyFork+UserStyles.org markdown

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

当前为 2015-11-27 提交的版本,查看 最新版本

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