GreasyFork Code: Syntax Highlight by PrismJS

To syntax highlight GreasyFork Code by PrismJS

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by PrismJS
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.4.2
  6. // @author CY Fung
  7. // @description To syntax highlight GreasyFork Code by PrismJS
  8. // @run-at document-start
  9. // @inject-into page
  10. // @unwrap
  11. // @license MIT
  12. // @match https://greatest.deepsurf.us/*
  13. // @match https://sleazyfork.org/*
  14. //
  15. // ==/UserScript==
  16.  
  17.  
  18. (() => {
  19.  
  20. const USE_SHADOW_MODE = true; // performance fix for long coding
  21.  
  22. const cdn = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0';
  23. const resoruces = {
  24. 'prism-core.js': `${cdn}/components/prism-core.js`,
  25. 'prism-clike.js': `${cdn}/components/prism-clike.min.js`,
  26. 'prism-javascript.js': `${cdn}/components/prism-javascript.min.js`,
  27. 'prism-css.js': `${cdn}/components/prism-css.min.js`,
  28. 'prism-stylus.js': `${cdn}/components/prism-stylus.min.js`,
  29. 'prism.css': `${cdn}/themes/prism.min.css`,
  30. 'prism-dark.css': `${cdn}/themes/prism-dark.min.css`,
  31. }
  32.  
  33. const doActionCSS = () => `
  34.  
  35. .code-container, .code-container-shadow{
  36. height:100vh;
  37. }
  38. .code-container .CodeMirror, .code-container textarea{
  39. height:100%;
  40. }
  41. `;
  42.  
  43.  
  44. const global_css = () =>`
  45.  
  46. html {
  47. line-height: 1.5;
  48. -webkit-text-size-adjust: 100%;
  49. -moz-tab-size: 4;
  50. -o-tab-size: 4;
  51. tab-size: 4;
  52. font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;
  53. font-feature-settings: normal;
  54. font-variation-settings: normal
  55. }
  56.  
  57. .code-container code, .code-container kbd, .code-container pre, .code-container samp,
  58. .code-container-pre, .code-container-pre code, .code-container-pre pre {
  59. font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;
  60. font-size: 1em
  61. }
  62.  
  63. #script-content > .code-container[class] {
  64. width: 100%;
  65. }
  66.  
  67. .code-container[class], .code-container-shadow[class] {
  68. border-radius: 0;
  69. }
  70.  
  71. .code-container > pre:only-child, .code-container-pre{
  72. padding:0;
  73. }
  74.  
  75. pre.code-container-pre[class]{
  76.  
  77. padding: 0;
  78. border: 0;
  79. margin: 0;
  80. }
  81.  
  82. code.syntax-highlighted[class] {
  83. font-family: monospace;
  84. font-size: 13px;
  85. font-variant-ligatures: contextual;
  86. line-height: 1.15rem;
  87. text-shadow: none !important;
  88. }
  89.  
  90. .hljs-comment[class], .hljs-quote[class] {
  91. font-style: inherit;
  92. color: #259789;
  93. }
  94.  
  95. .hljs-add-marker-width .marker-fixed-width[class] {
  96. user-select: none !important;
  97. width: calc(var(--hljs-marker-width, 0em) + 16px);
  98. background: var(--marker-color-background, #f4f4f4);
  99. padding-right: 6px;
  100. margin-right: 4px;
  101. contain: paint style;
  102. color: var(--marker-color-text, inherit);
  103. }
  104.  
  105. .marker-fixed-width[marker-text]::before {
  106. content:attr(marker-text);
  107. }
  108.  
  109. `;
  110.  
  111.  
  112. const cssForCodePage = () => /\/scripts\/\d+[^\s\/\\]*\/code(\/|$)/.test(location.href) ? `
  113.  
  114. html:not([dkkfv]) div.code-container {
  115. display:none;
  116. }
  117.  
  118. .code-container,
  119. .code-container pre:only-child,
  120. .code-container pre:only-child code:only-child,
  121. .code-container-pre {
  122. max-height: calc(100vh + 4px);
  123. max-width: calc(100vw + 4px);
  124. }
  125. ` : '';
  126.  
  127.  
  128. const cssAdd = () =>`
  129.  
  130. ${global_css()}
  131.  
  132. ${cssForCodePage()}
  133.  
  134. .code-container, .code-container-shadow {
  135. max-width: 100%;
  136. display: inline-flex;
  137. flex-direction: column;
  138. overflow: auto;
  139. border-radius: 8px;
  140. max-height: 100%;
  141. overflow: visible;
  142. }
  143. .code-container > pre:only-child, .code-container-pre {
  144. max-width: 100%;
  145. display: inline-flex;
  146. flex-direction: column;
  147. flex-grow: 1;
  148. height: 0;
  149. }
  150. .code-container > pre:only-child > code:only-child, .code-container-pre > code:only-child{
  151. max-width: 100%;
  152. flex-grow: 1;
  153. height: 0;
  154. }
  155. .code-container pre code, .code-container-pre code {
  156. padding: 0;
  157. font-family: Consolas;
  158. cursor: text;
  159. overflow: auto;
  160. box-sizing: border-box;
  161. }
  162. .code-container pre code .marker, .code-container-pre code .marker {
  163. display: inline-block;
  164. color: #636d83;
  165. text-align: right;
  166. padding-right: 20px;
  167. user-select: none;
  168. cursor: auto;
  169. }
  170.  
  171. .code-container[contenteditable]{
  172. outline: 0 !important;
  173. contain: strict;
  174. box-sizing: border-box;
  175. }
  176.  
  177. .code-container[contenteditable]>pre[contenteditable="false"]{
  178. contain: strict;
  179. width: initial;
  180. box-sizing: border-box;
  181. }
  182.  
  183.  
  184.  
  185.  
  186. html {
  187.  
  188. --token-color-keyword: #07a;
  189. --token-color-punctuation: #1415ec;
  190. --token-color-comment: #259789;
  191. --token-color-function: #da204f;
  192. }
  193.  
  194. [dark] {
  195.  
  196. --token-color-keyword: #898af2;
  197. --token-color-punctuation: #fadbdb;
  198. --token-color-comment:#59c6b9;
  199. --token-color-function: #e98aa2;
  200.  
  201. --marker-color-background: #242424;
  202. --marker-color-text: #b6b2b2;
  203.  
  204. }
  205.  
  206.  
  207. code .token.comment {
  208. color: var(--token-color-comment);
  209. }
  210.  
  211. code .token.atrule, code .token.attr-value, code .token.keyword {
  212. color: #1415ec;
  213. color: var(--token-color-keyword);
  214. }
  215.  
  216.  
  217. .language-stylus .token.atrule, .language-stylus .token.attr-value, .language-stylus .token.keyword {
  218. color: #700d0d;
  219. }
  220.  
  221.  
  222. code .token.punctuation{
  223. color: var(--token-color-punctuation);
  224. }
  225.  
  226.  
  227. code .token.variable-declaration,
  228. code .token.variable {
  229. color: #0d10cd;
  230. }
  231.  
  232. code .token.selector{
  233. color: #1373bb;
  234. }
  235.  
  236.  
  237. code .token.function {
  238. color:var(--token-color-function);
  239. }
  240.  
  241.  
  242.  
  243. .language-stylus .token.variable-declaration,
  244. .language-stylus .token.variable {
  245. color: #0d10cd;
  246. }
  247.  
  248. .language-stylus .token.selector{
  249. color: #1373bb;
  250. }
  251.  
  252. .language-stylus .token.punctuation{
  253. color:#700d0d;
  254. }
  255.  
  256.  
  257. .language-stylus .token.function {
  258. color:#da204f
  259. }
  260.  
  261.  
  262. .token, span.marker {
  263. contain: content;
  264. }
  265.  
  266. .prettyprint.prettyprint {
  267. background-color: transparent;
  268. }
  269.  
  270. `;
  271.  
  272.  
  273. const Promise = (async function () { })().constructor;
  274.  
  275. const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
  276.  
  277. const PromiseExternal = ((resolve_, reject_) => {
  278. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  279. return class PromiseExternal extends Promise {
  280. constructor(cb = h) {
  281. super(cb);
  282. if (cb === h) {
  283. /** @type {(value: any) => void} */
  284. this.resolve = resolve_;
  285. /** @type {(reason?: any) => void} */
  286. this.reject = reject_;
  287. }
  288. }
  289. };
  290. })();
  291.  
  292. // -------- fix requestIdleCallback issue for long coding --------
  293.  
  294. const pud = new PromiseExternal();
  295. if (typeof window.requestIdleCallback === 'function' && !window.requestIdleCallback842 && window.requestIdleCallback.length === 1) {
  296. window.requestIdleCallback842 = window.requestIdleCallback;
  297. window.requestIdleCallback = function (callback, ...args) {
  298. console.error(322)
  299. return (this || window).requestIdleCallback842(async function () {
  300. await pud.then();
  301. setTimeout(()=>{
  302. callback.apply(this, arguments);
  303. });
  304. }, ...args);
  305. }
  306. }
  307.  
  308. // -------- fix requestIdleCallback issue for long coding --------
  309.  
  310. const pScript = new PromiseExternal();
  311. const pElementQuery = new PromiseExternal();
  312.  
  313. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName;
  314. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName;
  315.  
  316. HTMLElement.prototype.getElementsByTagName = getElementsByTagName;
  317. Document.prototype.getElementsByTagName = getElementsByTagName;
  318.  
  319. let byPass = true;
  320.  
  321. const observablePromise = (proc, timeoutPromise) => {
  322. let promise = null;
  323. return {
  324. obtain() {
  325. if (!promise) {
  326. promise = new Promise(resolve => {
  327. let mo = null;
  328. const f = () => {
  329. let t = proc();
  330. if (t) {
  331. mo.disconnect();
  332. mo.takeRecords();
  333. mo = null;
  334. resolve(t);
  335. }
  336. }
  337. mo = new MutationObserver(f);
  338. mo.observe(document, { subtree: true, childList: true })
  339. f();
  340. timeoutPromise && timeoutPromise.then(() => {
  341. resolve(null)
  342. });
  343. });
  344. }
  345. return promise
  346. }
  347. }
  348. }
  349.  
  350. const documentReady = new Promise(resolve => {
  351. Promise.resolve().then(() => {
  352. if (document.readyState !== 'loading') {
  353. resolve();
  354. } else {
  355. window.addEventListener("DOMContentLoaded", resolve, false);
  356. }
  357. });
  358. });
  359.  
  360. documentReady.then(async () => {
  361. pud.resolve();
  362. });
  363.  
  364. function getElementsByTagName(tag) {
  365. if (byPass) {
  366. if (tag === 'pre' || tag === 'code' || tag === 'xmp') {
  367. if (location.pathname.endsWith('/code')) {
  368. pElementQuery.resolve();
  369. return [];
  370. }
  371. }
  372. }
  373. return this.getElementsByTagName331(tag);
  374. }
  375.  
  376. async function onBodyHeadReadyAsync() {
  377. await observablePromise(() => document.body && document.head).obtain();
  378. }
  379.  
  380.  
  381. // Load CSS
  382. function loadJS(href) {
  383.  
  384. return new Promise(resolve => {
  385.  
  386. const script = document.createElement('script');
  387. script.src = href;
  388. script.onload = () => {
  389. resolve(script);
  390. };
  391. document.head.appendChild(script);
  392.  
  393. });
  394.  
  395. }
  396.  
  397. // Load CSS
  398. function loadCSS(href) {
  399. const link = document.createElement('link');
  400. link.rel = 'stylesheet';
  401. link.href = href;
  402. document.head.appendChild(link);
  403. return link;
  404. }
  405.  
  406.  
  407.  
  408.  
  409.  
  410. function getLangClassName(pre, textContent){
  411.  
  412.  
  413.  
  414. let className = '';
  415. let preLang = '';
  416.  
  417. if (pre.classList.contains('lang-js')) {
  418. preLang = 'lang-js';
  419. } else if (pre.classList.contains('lang-css')) {
  420. preLang = 'lang-css';
  421. } else if (pre.classList.contains('uglyprint')){
  422. let m =/\/\/\s*={2,9}(\w+)={2,9}\s*[\r\n]/.exec(pre.textContent);
  423. if(m){
  424. m = m[1];
  425. if(m === 'UserScript') preLang = 'lang-js';
  426. if(m === 'UserStyle') preLang = 'lang-css';
  427. }
  428. }
  429.  
  430. if (preLang === 'lang-js') {
  431. className = 'language-javascript';
  432. } else if (preLang === 'lang-css') {
  433.  
  434. const text = textContent;
  435. let m = /\n@preprocessor\s+([-_a-zA-Z]{3,8})\s*\n/.exec(text);
  436. className = 'language-css'
  437. if (m) {
  438. const preprocessor = m[1];
  439. if (preprocessor === 'stylus') {
  440. className = 'language-stylus';
  441. } else if (preprocessor === 'uso') {
  442. className = 'language-stylus';
  443. } else if (preprocessor === 'less') {
  444. className = 'language-less';
  445. } else if (preprocessor === 'default') {
  446. className = 'language-stylus';
  447. } else {
  448. className = 'language-stylus';
  449. }
  450. }
  451.  
  452. }
  453.  
  454. return className;
  455.  
  456.  
  457. }
  458.  
  459. /** @param {HTMLElement} pre */
  460. function prepareCodeAreaAsync(pre) {
  461.  
  462. if (pre.isConnected === false) return;
  463. const preParentNode = pre.parentNode;
  464. const preNextNode = pre.nextSibling;
  465.  
  466. const codeContainer = pre.closest('.code-container');
  467. const doContentEditable = codeContainer && codeContainer.querySelector('.code-container>pre:only-child');
  468.  
  469. pre.remove();
  470.  
  471. for (const li of pre.querySelectorAll('li')) {
  472. li.append(document.createTextNode('\n'));
  473. }
  474.  
  475. const textContent = pre.textContent;
  476.  
  477. const className = getLangClassName(pre, textContent);
  478.  
  479. if (!className) return;
  480.  
  481. if (doContentEditable) {
  482. // avoid selection to the outside by mouse dragging
  483. codeContainer.setAttribute('contenteditable', '');
  484. pre.setAttribute('contenteditable', 'false');
  485. }
  486.  
  487. const code = document.createElement('code');
  488.  
  489. code.classList.add(className);
  490. code.classList.add('syntax-highlighted')
  491.  
  492. let htmlCode = '';
  493.  
  494. if (className === 'language-javascript') {
  495. htmlCode = Prism.highlight(textContent, Prism.languages.javascript, 'javascript');
  496. } else if (className === 'language-stylus') {
  497. htmlCode = Prism.highlight(textContent, Prism.languages.stylus, 'stylus');
  498. } else if (className === 'language-less') {
  499. htmlCode = Prism.highlight(textContent, Prism.languages.less, 'less');
  500. } else {
  501. htmlCode = Prism.highlight(textContent, Prism.languages.css, 'css');
  502. }
  503.  
  504. // Adding line numbers
  505. htmlCode = htmlCode || '';
  506. const htmlSplit = htmlCode ? htmlCode.split('\n') : [];
  507. const totalLines = htmlSplit.length;
  508.  
  509. let mwStyle = '';
  510.  
  511. if (totalLines >= 1) {
  512. code.classList.add('hljs-add-marker-width');
  513. const len = `${totalLines}`.length * 0.5;
  514. mwStyle = `${len}em`;
  515. htmlCode = htmlSplit.map((n, i) => `<span class="marker marker-fixed-width" marker-text="${i + 1}"></span>${n}`).join('\n') || '';
  516.  
  517. } else {
  518.  
  519. code.classList.remove('hljs-add-marker-width');
  520. }
  521.  
  522. code.innerHTML = htmlCode;
  523. code.style.setProperty('--hljs-marker-width', mwStyle);
  524.  
  525.  
  526.  
  527. if(pre.firstChild === pre.lastChild && pre.firstChild instanceof Node){
  528. pre.firstChild.replaceWith(code);
  529. }else{
  530. pre.innerHTML = '';
  531. pre.appendChild(code);
  532. }
  533. pre.classList.add('code-container-pre');
  534.  
  535.  
  536. if(USE_SHADOW_MODE){
  537.  
  538. const shadowDiv = document.createElement("div");
  539. shadowDiv.classList.add('code-container-shadow')
  540.  
  541. const shadow = shadowDiv.attachShadow({ mode: "open" });
  542.  
  543. const styles = document.querySelectorAll('link, style');
  544. for(style of styles) {
  545. if(style.classList.contains("stylus")) continue;
  546. if(style.nodeName === 'LINK' && style.rel !== 'stylesheet') continue;
  547. shadow.appendChild(style.cloneNode(true))
  548. }
  549.  
  550. shadow.appendChild(pre)
  551. preParentNode.insertBefore(shadowDiv, preNextNode);
  552. }else{
  553.  
  554. preParentNode.insertBefore(pre, preNextNode);
  555. }
  556.  
  557.  
  558.  
  559.  
  560. }
  561.  
  562. const documentBodyHeadReady = onBodyHeadReadyAsync();
  563.  
  564. documentBodyHeadReady.then(async () => {
  565.  
  566. if (!location.pathname.endsWith('/code')) {
  567. return;
  568. }
  569.  
  570. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd()}`;
  571.  
  572. self.Prism = self.Prism || {};
  573. self.Prism.manual = true;
  574. await loadJS(resoruces['prism-core.js']);
  575. await loadJS(resoruces['prism-clike.js']);
  576. await loadJS(resoruces['prism-javascript.js']);
  577. await loadJS(resoruces['prism-css.js']);
  578. await loadJS(resoruces['prism-stylus.js']);
  579.  
  580. if (document.documentElement.hasAttribute('dark')) {
  581.  
  582. loadCSS(resoruces['prism-dark.css']);
  583. } else {
  584.  
  585. loadCSS(resoruces['prism.css']);
  586. }
  587.  
  588. pScript.resolve();
  589.  
  590.  
  591.  
  592.  
  593. });
  594.  
  595. let keydownActive = false;
  596.  
  597. documentReady.then(async () => {
  598.  
  599. if (!location.pathname.endsWith('/code')) {
  600. byPass = false;
  601. return;
  602. }
  603. await pScript.then();
  604.  
  605. await Promise.race([pElementQuery, delayPn(800)]);
  606.  
  607. const targets = document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css, .code-container pre.uglyprint');
  608. // pre.uglyprint : too long code ; see https://greatest.deepsurf.us/zh-CN/scripts/24204-picviewer-ce/code
  609.  
  610. if (targets.length === 0) return;
  611.  
  612. await delayPn(40);
  613.  
  614. document.head.appendChild(document.createElement('style')).textContent = doActionCSS();
  615.  
  616. await delayPn(40);
  617.  
  618. byPass = false;
  619.  
  620. // Code highlighting
  621. const promises = [...targets].map(prepareCodeAreaAsync)
  622. await Promise.all(promises);
  623.  
  624. await delayPn(40);
  625. document.documentElement.setAttribute('dkkfv', '');
  626. keydownActive = true;
  627.  
  628. });
  629.  
  630. function selectAllWithinElement(element) {
  631. window.getSelection().removeAllRanges();
  632. let range = document.createRange();
  633. if (element) {
  634. range.selectNodeContents(element);
  635. window.getSelection().addRange(range);
  636. } else {
  637. console.error('Element not found with ID:', element);
  638. }
  639. }
  640. document.addEventListener('keydown', (e) => {
  641. if (keydownActive && e && e.code === 'KeyA' && e.isTrusted && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
  642.  
  643. const target = e.target;
  644. const container = target ? target.closest('div.code-container') : null;
  645. const code = container ? container.querySelector('code') : null;
  646.  
  647. if (container && code) {
  648.  
  649. e.preventDefault();
  650. e.stopPropagation();
  651. e.stopImmediatePropagation();
  652.  
  653. setTimeout(() => {
  654. selectAllWithinElement(code);
  655. }, 1)
  656.  
  657. }
  658.  
  659. }
  660. }, true);
  661.  
  662.  
  663. })();