GreasyFork Code: Syntax Highlight by PrismJS

To syntax highlight GreasyFork Code by PrismJS

Verze ze dne 10. 07. 2024. Zobrazit nejnovější verzi.

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by PrismJS
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.3.5
  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.  
  263.  
  264. const Promise = (async function () { })().constructor;
  265.  
  266. const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
  267.  
  268. const PromiseExternal = ((resolve_, reject_) => {
  269. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  270. return class PromiseExternal extends Promise {
  271. constructor(cb = h) {
  272. super(cb);
  273. if (cb === h) {
  274. /** @type {(value: any) => void} */
  275. this.resolve = resolve_;
  276. /** @type {(reason?: any) => void} */
  277. this.reject = reject_;
  278. }
  279. }
  280. };
  281. })();
  282.  
  283. // -------- fix requestIdleCallback issue for long coding --------
  284.  
  285. const pud = new PromiseExternal();
  286. if (typeof window.requestIdleCallback === 'function' && !window.requestIdleCallback842 && window.requestIdleCallback.length === 1) {
  287. window.requestIdleCallback842 = window.requestIdleCallback;
  288. window.requestIdleCallback = function (callback, ...args) {
  289. console.error(322)
  290. return (this || window).requestIdleCallback842(async function () {
  291. await pud.then();
  292. setTimeout(()=>{
  293. callback.apply(this, arguments);
  294. });
  295. }, ...args);
  296. }
  297. }
  298.  
  299. // -------- fix requestIdleCallback issue for long coding --------
  300.  
  301. const pScript = new PromiseExternal();
  302. const pElementQuery = new PromiseExternal();
  303.  
  304. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName;
  305. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName;
  306.  
  307. HTMLElement.prototype.getElementsByTagName = getElementsByTagName;
  308. Document.prototype.getElementsByTagName = getElementsByTagName;
  309.  
  310. let byPass = true;
  311.  
  312. const observablePromise = (proc, timeoutPromise) => {
  313. let promise = null;
  314. return {
  315. obtain() {
  316. if (!promise) {
  317. promise = new Promise(resolve => {
  318. let mo = null;
  319. const f = () => {
  320. let t = proc();
  321. if (t) {
  322. mo.disconnect();
  323. mo.takeRecords();
  324. mo = null;
  325. resolve(t);
  326. }
  327. }
  328. mo = new MutationObserver(f);
  329. mo.observe(document, { subtree: true, childList: true })
  330. f();
  331. timeoutPromise && timeoutPromise.then(() => {
  332. resolve(null)
  333. });
  334. });
  335. }
  336. return promise
  337. }
  338. }
  339. }
  340.  
  341. const documentReady = new Promise(resolve => {
  342. Promise.resolve().then(() => {
  343. if (document.readyState !== 'loading') {
  344. resolve();
  345. } else {
  346. window.addEventListener("DOMContentLoaded", resolve, false);
  347. }
  348. });
  349. });
  350.  
  351. documentReady.then(async () => {
  352. pud.resolve();
  353. });
  354.  
  355. function getElementsByTagName(tag) {
  356. if (byPass) {
  357. if (tag === 'pre' || tag === 'code' || tag === 'xmp') {
  358. if (location.pathname.endsWith('/code')) {
  359. pElementQuery.resolve();
  360. return [];
  361. }
  362. }
  363. }
  364. return this.getElementsByTagName331(tag);
  365. }
  366.  
  367. async function onBodyHeadReadyAsync() {
  368. await observablePromise(() => document.body && document.head).obtain();
  369. }
  370.  
  371.  
  372. // Load CSS
  373. function loadJS(href) {
  374.  
  375. return new Promise(resolve => {
  376.  
  377. const script = document.createElement('script');
  378. script.src = href;
  379. script.onload = () => {
  380. resolve(script);
  381. };
  382. document.head.appendChild(script);
  383.  
  384. });
  385.  
  386. }
  387.  
  388. // Load CSS
  389. function loadCSS(href) {
  390. const link = document.createElement('link');
  391. link.rel = 'stylesheet';
  392. link.href = href;
  393. document.head.appendChild(link);
  394. return link;
  395. }
  396.  
  397.  
  398.  
  399.  
  400.  
  401. function getLangClassName(pre, textContent){
  402.  
  403.  
  404.  
  405. let className = '';
  406. let preLang = '';
  407.  
  408. if (pre.classList.contains('lang-js')) {
  409. preLang = 'lang-js';
  410. } else if (pre.classList.contains('lang-css')) {
  411. preLang = 'lang-css';
  412. } else if (pre.classList.contains('uglyprint')){
  413. let m =/\/\/\s*={2,9}(\w+)={2,9}\s*[\r\n]/.exec(pre.textContent);
  414. if(m){
  415. m = m[1];
  416. if(m === 'UserScript') preLang = 'lang-js';
  417. if(m === 'UserStyle') preLang = 'lang-css';
  418. }
  419. }
  420.  
  421. if (preLang === 'lang-js') {
  422. className = 'language-javascript';
  423. } else if (preLang === 'lang-css') {
  424.  
  425. const text = textContent;
  426. let m = /\n@preprocessor\s+([-_a-zA-Z]{3,8})\s*\n/.exec(text);
  427. className = 'language-css'
  428. if (m) {
  429. const preprocessor = m[1];
  430. if (preprocessor === 'stylus') {
  431. className = 'language-stylus';
  432. } else if (preprocessor === 'uso') {
  433. className = 'language-stylus';
  434. } else if (preprocessor === 'less') {
  435. className = 'language-less';
  436. } else if (preprocessor === 'default') {
  437. className = 'language-stylus';
  438. } else {
  439. className = 'language-stylus';
  440. }
  441. }
  442.  
  443. }
  444.  
  445. return className;
  446.  
  447.  
  448. }
  449.  
  450. /** @param {HTMLElement} pre */
  451. function prepareCodeAreaAsync(pre) {
  452.  
  453. if (pre.isConnected === false) return;
  454. const preParentNode = pre.parentNode;
  455. const preNextNode = pre.nextSibling;
  456.  
  457. const codeContainer = pre.closest('.code-container');
  458. const doContentEditable = codeContainer && codeContainer.querySelector('.code-container>pre:only-child');
  459.  
  460. pre.remove();
  461.  
  462. for (const li of pre.querySelectorAll('li')) {
  463. li.append(document.createTextNode('\n'));
  464. }
  465.  
  466. const textContent = pre.textContent;
  467.  
  468. const className = getLangClassName(pre, textContent);
  469.  
  470. if (!className) return;
  471.  
  472. if (doContentEditable) {
  473. // avoid selection to the outside by mouse dragging
  474. codeContainer.setAttribute('contenteditable', '');
  475. pre.setAttribute('contenteditable', 'false');
  476. }
  477.  
  478. const code = document.createElement('code');
  479.  
  480. code.classList.add(className);
  481. code.classList.add('syntax-highlighted')
  482.  
  483. let htmlCode = '';
  484.  
  485. if (className === 'language-javascript') {
  486. htmlCode = Prism.highlight(textContent, Prism.languages.javascript, 'javascript');
  487. } else if (className === 'language-stylus') {
  488. htmlCode = Prism.highlight(textContent, Prism.languages.stylus, 'stylus');
  489. } else if (className === 'language-less') {
  490. htmlCode = Prism.highlight(textContent, Prism.languages.less, 'less');
  491. } else {
  492. htmlCode = Prism.highlight(textContent, Prism.languages.css, 'css');
  493. }
  494.  
  495. // Adding line numbers
  496. htmlCode = htmlCode || '';
  497. const htmlSplit = htmlCode ? htmlCode.split('\n') : [];
  498. const totalLines = htmlSplit.length;
  499.  
  500. let mwStyle = '';
  501.  
  502. if (totalLines >= 1) {
  503. code.classList.add('hljs-add-marker-width');
  504. const len = `${totalLines}`.length * 0.5;
  505. mwStyle = `${len}em`;
  506. htmlCode = htmlSplit.map((n, i) => `<span class="marker marker-fixed-width" marker-text="${i + 1}"></span>${n}`).join('\n') || '';
  507.  
  508. } else {
  509.  
  510. code.classList.remove('hljs-add-marker-width');
  511. }
  512.  
  513. code.innerHTML = htmlCode;
  514. code.style.setProperty('--hljs-marker-width', mwStyle);
  515.  
  516.  
  517.  
  518. if(pre.firstChild === pre.lastChild && pre.firstChild instanceof Node){
  519. pre.firstChild.replaceWith(code);
  520. }else{
  521. pre.innerHTML = '';
  522. pre.appendChild(code);
  523. }
  524. pre.classList.add('code-container-pre');
  525.  
  526.  
  527. if(USE_SHADOW_MODE){
  528.  
  529. const shadowDiv = document.createElement("div");
  530. shadowDiv.classList.add('code-container-shadow')
  531.  
  532. const shadow = shadowDiv.attachShadow({ mode: "open" });
  533.  
  534. const styles = document.querySelectorAll('link, style');
  535. for(style of styles) {
  536. if(style.classList.contains("stylus")) continue;
  537. if(style.nodeName === 'LINK' && style.rel !== 'stylesheet') continue;
  538. shadow.appendChild(style.cloneNode(true))
  539. }
  540.  
  541. shadow.appendChild(pre)
  542. preParentNode.insertBefore(shadowDiv, preNextNode);
  543. }else{
  544.  
  545. preParentNode.insertBefore(pre, preNextNode);
  546. }
  547.  
  548.  
  549.  
  550.  
  551. }
  552.  
  553. const documentBodyHeadReady = onBodyHeadReadyAsync();
  554.  
  555. documentBodyHeadReady.then(async () => {
  556.  
  557. if (!location.pathname.endsWith('/code')) {
  558. return;
  559. }
  560.  
  561. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd()}`;
  562.  
  563. self.Prism = self.Prism || {};
  564. self.Prism.manual = true;
  565. await loadJS(resoruces['prism-core.js']);
  566. await loadJS(resoruces['prism-clike.js']);
  567. await loadJS(resoruces['prism-javascript.js']);
  568. await loadJS(resoruces['prism-css.js']);
  569. await loadJS(resoruces['prism-stylus.js']);
  570.  
  571. if (document.documentElement.hasAttribute('dark')) {
  572.  
  573. loadCSS(resoruces['prism-dark.css']);
  574. } else {
  575.  
  576. loadCSS(resoruces['prism.css']);
  577. }
  578.  
  579. pScript.resolve();
  580.  
  581.  
  582.  
  583.  
  584. });
  585.  
  586. let keydownActive = false;
  587.  
  588. documentReady.then(async () => {
  589.  
  590. if (!location.pathname.endsWith('/code')) {
  591. byPass = false;
  592. return;
  593. }
  594. await pScript.then();
  595.  
  596. await Promise.race([pElementQuery, delayPn(800)]);
  597.  
  598. const targets = document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css, .code-container pre.uglyprint');
  599. // pre.uglyprint : too long code ; see https://greatest.deepsurf.us/zh-CN/scripts/24204-picviewer-ce/code
  600.  
  601. if (targets.length === 0) return;
  602.  
  603. await delayPn(40);
  604.  
  605. document.head.appendChild(document.createElement('style')).textContent = doActionCSS();
  606.  
  607. await delayPn(40);
  608.  
  609. byPass = false;
  610.  
  611. // Code highlighting
  612. const promises = [...targets].map(prepareCodeAreaAsync)
  613. await Promise.all(promises);
  614.  
  615. await delayPn(40);
  616. document.documentElement.setAttribute('dkkfv', '');
  617. keydownActive = true;
  618.  
  619. });
  620.  
  621. function selectAllWithinElement(element) {
  622. window.getSelection().removeAllRanges();
  623. let range = document.createRange();
  624. if (element) {
  625. range.selectNodeContents(element);
  626. window.getSelection().addRange(range);
  627. } else {
  628. console.error('Element not found with ID:', element);
  629. }
  630. }
  631. document.addEventListener('keydown', (e) => {
  632. if (keydownActive && e && e.code === 'KeyA' && e.isTrusted && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
  633.  
  634. const target = e.target;
  635. const container = target ? target.closest('div.code-container') : null;
  636. const code = container ? container.querySelector('code') : null;
  637.  
  638. if (container && code) {
  639.  
  640. e.preventDefault();
  641. e.stopPropagation();
  642. e.stopImmediatePropagation();
  643.  
  644. setTimeout(() => {
  645. selectAllWithinElement(code);
  646. }, 1)
  647.  
  648. }
  649.  
  650. }
  651. }, true);
  652.  
  653.  
  654. })();