2ch code preview

Add code preview to 2ch.hk

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

  1. // ==UserScript==
  2. // @name 2ch code preview
  3. // @author 7sIV799F
  4. // @version 0.4.0
  5. // @include /https:\/\/2ch\.(hk|pm|re|tf|wj)/
  6. // @include http://2-ch.so
  7. // @grant none
  8. // @description Add code preview to 2ch.hk
  9. // @namespace https://greasyfork.org/users/10379
  10. // ==/UserScript==
  11.  
  12. $(function() {
  13. $('<button>', {
  14. text: 'code',
  15. click: function() {
  16. var ta = $('#shampoo')[0],
  17. start = ta.selectionStart,
  18. end = ta.selectionEnd;
  19.  
  20. ta.value =
  21. ta.value.slice(0, start) +
  22. '[code]\n' +
  23. ta.value.slice(start, end)
  24. // replace * with look like * symbol
  25. .replace(/\*/g, '٭')
  26. // add zero-width space to BB-code
  27. .replace(/\[([bius])\]/g, '[​$1]')
  28. .replace(/\t/g, '  ')
  29. // replace space with non-break space
  30. .replace(/ /g, ' ') +
  31. '\n[/code]' +
  32. ta.value.slice(end)
  33. ;
  34.  
  35. return false;
  36. }
  37. }).appendTo('.symbol-counter');
  38.  
  39. getIframe();
  40.  
  41. $('.posts').bind('DOMSubtreeModified', getIframe);
  42. });
  43.  
  44. function getIframe() {
  45. var re = new RegExp(
  46. '(pastebin\\.com|ideone\\.com|jsfiddle\\.net|codepen\\.io)\/' +
  47. '(\\w+\/pen\/)?' + // http://codepen.io/(username/pen/)id
  48. '(\\w+\/)?' + // http://jsfiddle.net/(username/)id
  49. '(\\w+)\/?$' // id
  50. );
  51.  
  52. $('a[href^="http"')
  53. .filter(function() {
  54. return !$(this).hasClass('code-embedded') && re.test(this.href);
  55. })
  56. .addClass('code-embedded')
  57. .after(' <button class="embed-code">view code</button>')
  58. .next('button.embed-code')
  59. .click(function() {
  60. var $this = $(this),
  61. match = $this.prev().attr('href').match(re);
  62.  
  63. if (!match) return;
  64.  
  65. var host = match[1],
  66. id = match[4],
  67. src = {
  68. 'pastebin.com': '//pastebin.com/embed_iframe.php?i=' + id,
  69. 'ideone.com' : '//ideone.com/embed/' + id,
  70. 'jsfiddle.net': '//jsfiddle.net/' + id + '/embedded/',
  71. 'codepen.io' : '//codepen.io/anon/embed/' + id + '/?height=500'
  72. };
  73.  
  74. $('<div>', {
  75. class: 'code-embedded',
  76. html: $('<iframe>', {
  77. src : src[host],
  78. style: 'border:none; width:800px; height:500px'
  79. })
  80. }).insertAfter($this);
  81.  
  82. $this.remove();
  83. })
  84. ;
  85.  
  86. $('.post-message:contains("[code"):not(.compiled)')
  87. .addClass('compiled')
  88. .html(function(_i, html) {
  89. return html
  90. .replace(/\[code[^\]]*\]/g, '<pre class="code">')
  91. .replace(/<br>/g, '\n')
  92. .replace(/(<\/?em>|٭)/g, '*')
  93. .replace(/\t/g, ' ')
  94. .replace(/\[\/code\]/g, '</pre>')
  95. ;
  96. });
  97. }