GreasyFork markdown

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

目前為 2014-12-23 提交的版本,檢視 最新版本

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