GreasyFork Code: Syntax Highlight by PrismJS

To syntax highlight GreasyFork Code by PrismJS

2023-12-17 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by PrismJS
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.2.4
  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. // ==/UserScript==
  15.  
  16.  
  17. (() => {
  18. let byPass = true;
  19.  
  20. const cdn = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0';
  21. const resoruces = {
  22. 'prism-core.js': `${cdn}/components/prism-core.js`,
  23. 'prism-clike.js': `${cdn}/components/prism-clike.min.js`,
  24. 'prism-javascript.js': `${cdn}/components/prism-javascript.min.js`,
  25. 'prism-css.js': `${cdn}/components/prism-css.min.js`,
  26. 'prism-stylus.js': `${cdn}/components/prism-stylus.min.js`,
  27. 'prism.css': `${cdn}/themes/prism.min.css`,
  28. 'prism-dark.css': `${cdn}/themes/prism-dark.min.css`,
  29. }
  30.  
  31. function selectAllWithinElement(element) {
  32. // Clear any current selections
  33. window.getSelection().removeAllRanges();
  34.  
  35. // Create a new range
  36. let range = document.createRange();
  37.  
  38. // Check if the element exists
  39. if (element) {
  40. // Select all content within the element
  41. range.selectNodeContents(element);
  42.  
  43. // Add the range to the selection
  44. window.getSelection().addRange(range);
  45. } else {
  46. console.error('Element not found with ID:', element);
  47. }
  48. }
  49. document.addEventListener('keydown', (e) => {
  50. if (e && e.code === 'KeyA' && e.isTrusted && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
  51.  
  52. const target = e.target;
  53. const container = target ? target.closest('div.code-container') : null;
  54. const code = container ? container.querySelector('code') : null;
  55.  
  56. if (container && code) {
  57.  
  58. e.preventDefault();
  59. e.stopPropagation();
  60. e.stopImmediatePropagation();
  61.  
  62. setTimeout(() => {
  63. selectAllWithinElement(code);
  64. }, 1)
  65.  
  66. }
  67.  
  68. }
  69. }, true)
  70.  
  71.  
  72. const Promise = (async function () { })().constructor;
  73.  
  74.  
  75. const PromiseExternal = ((resolve_, reject_) => {
  76. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  77. return class PromiseExternal extends Promise {
  78. constructor(cb = h) {
  79. super(cb);
  80. if (cb === h) {
  81. /** @type {(value: any) => void} */
  82. this.resolve = resolve_;
  83. /** @type {(reason?: any) => void} */
  84. this.reject = reject_;
  85. }
  86. }
  87. };
  88. })();
  89.  
  90. const documentReady = new Promise(resolve => {
  91. Promise.resolve().then(() => {
  92. if (document.readyState !== 'loading') {
  93. resolve();
  94. } else {
  95. window.addEventListener("DOMContentLoaded", resolve, false);
  96. }
  97. });
  98. });
  99.  
  100.  
  101. async function doAction() {
  102.  
  103. await new Promise(r => setTimeout(r, 1));
  104.  
  105. document.head.appendChild(document.createElement('style')).textContent = `
  106.  
  107. .code-container{
  108. height:100vh;
  109. }
  110. .code-container .CodeMirror, .code-container textarea{
  111. height:100%;
  112. }
  113. `;
  114.  
  115. if (window.requestIdleCallback) await new Promise(r => !!window.requestIdleCallback(r));
  116. else {
  117. await new Promise(r => !!window.requestAnimationFrame(r));
  118. await new Promise(r => !!window.setTimeout(r, 170));
  119. await new Promise(r => !!window.requestAnimationFrame(r));
  120. }
  121.  
  122. byPass = false;
  123.  
  124. }
  125.  
  126.  
  127. let mgg = 0;
  128. async function mTz() {
  129. if (mgg) return;
  130. mgg = 1;
  131. documentReady.then(doAction);
  132. }
  133.  
  134. function getElementsByTagName(tag) {
  135. if (byPass) {
  136. if (tag === 'pre' || tag === 'code' || tag === 'xmp') {
  137. if (location.pathname.endsWith('/code')) {
  138. setTimeout(mTz, 100)
  139. return [];
  140. }
  141. }
  142. }
  143. return this.getElementsByTagName331(tag);
  144. }
  145.  
  146. async function onBodyHeadReadyAsync() {
  147.  
  148. if (document.body && document.head) {
  149.  
  150.  
  151. } else {
  152.  
  153. const promiseBegin = new Promise(resolve => {
  154.  
  155. let mo = new MutationObserver(() => {
  156. if (document.body && document.head) {
  157. mo.disconnect();
  158. mo.takeRecords();
  159. mo = null;
  160. resolve();
  161. }
  162.  
  163. });
  164. mo.observe(document, { subtree: true, childList: true });
  165.  
  166. });
  167.  
  168. await promiseBegin.then();
  169.  
  170. }
  171.  
  172. }
  173.  
  174.  
  175. // Load CSS
  176. function loadJS(href) {
  177.  
  178. return new Promise(resolve => {
  179.  
  180. const script = document.createElement('script');
  181. script.src = href;
  182. script.onload = () => {
  183. resolve(script);
  184. };
  185. document.head.appendChild(script);
  186.  
  187. });
  188.  
  189. }
  190.  
  191. // Load CSS
  192. function loadCSS(href) {
  193. const link = document.createElement('link');
  194. link.rel = 'stylesheet';
  195. link.href = href;
  196. document.head.appendChild(link);
  197. return link;
  198. }
  199.  
  200. const global_css = `
  201.  
  202. html {
  203. line-height: 1.5;
  204. -webkit-text-size-adjust: 100%;
  205. -moz-tab-size: 4;
  206. -o-tab-size: 4;
  207. tab-size: 4;
  208. 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;
  209. font-feature-settings: normal;
  210. font-variation-settings: normal
  211. }
  212. /*
  213. body {
  214. margin: 0;
  215. line-height: inherit
  216. }
  217.  
  218. hr {
  219. height: 0;
  220. color: inherit;
  221. border-top-width: 1px
  222. }
  223.  
  224. abbr:where([title]) {
  225. -webkit-text-decoration: underline dotted;
  226. text-decoration: underline dotted
  227. }
  228.  
  229. h1,h2,h3,h4,h5,h6 {
  230. font-size: inherit;
  231. font-weight: inherit
  232. }
  233.  
  234.  
  235. b,strong {
  236. font-weight: bolder
  237. }
  238. */
  239. .code-container code, .code-container kbd, .code-container pre, .code-container samp {
  240. font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;
  241. font-size: 1em
  242. }
  243. /*
  244. small {
  245. font-size: 80%
  246. }
  247.  
  248. sub,sup {
  249. font-size: 75%;
  250. line-height: 0;
  251. position: relative;
  252. vertical-align: baseline
  253. }
  254.  
  255. sub {
  256. bottom: -.25em
  257. }
  258.  
  259. sup {
  260. top: -.5em
  261. }
  262.  
  263. table {
  264. text-indent: 0;
  265. border-color: inherit;
  266. border-collapse: collapse
  267. }
  268.  
  269. button,input,optgroup,select,textarea {
  270. font-family: inherit;
  271. font-feature-settings: inherit;
  272. font-variation-settings: inherit;
  273. font-size: 100%;
  274. font-weight: inherit;
  275. line-height: inherit;
  276. color: inherit;
  277. margin: 0;
  278. padding: 0
  279. }
  280.  
  281. button,select {
  282. text-transform: none
  283. }
  284.  
  285. :-moz-focusring {
  286. outline: auto
  287. }
  288.  
  289. :-moz-ui-invalid {
  290. box-shadow: none
  291. }
  292.  
  293. progress {
  294. vertical-align: baseline
  295. }
  296.  
  297. ::-webkit-inner-spin-button,::-webkit-outer-spin-button {
  298. height: auto
  299. }
  300.  
  301. [type=search] {
  302. -webkit-appearance: textfield;
  303. outline-offset: -2px
  304. }
  305.  
  306. ::-webkit-search-decoration {
  307. -webkit-appearance: none
  308. }
  309.  
  310. ::-webkit-file-upload-button {
  311. -webkit-appearance: button;
  312. font: inherit
  313. }
  314.  
  315. summary {
  316. display: list-item
  317. }
  318.  
  319. blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre {
  320. margin: 0
  321. }
  322.  
  323. fieldset {
  324. margin: 0
  325. }
  326.  
  327. fieldset,legend {
  328. padding: 0
  329. }
  330.  
  331. menu,ol,ul {
  332. list-style: none;
  333. margin: 0;
  334. padding: 0
  335. }
  336. textarea {
  337. resize: vertical
  338. }
  339.  
  340. input::-moz-placeholder,textarea::-moz-placeholder {
  341. opacity: 1;
  342. color: #9ca3af
  343. }
  344.  
  345. input::placeholder,textarea::placeholder {
  346. opacity: 1;
  347. color: #9ca3af
  348. }
  349. */
  350.  
  351. #script-content > .code-container[class] {
  352. width: 100%;
  353. }
  354.  
  355. .code-container[class] {
  356. border-radius: 0;
  357. }
  358.  
  359. .code-container[class] {
  360. border-radius: 0;
  361. }
  362.  
  363. .code-container > pre:only-child{
  364. padding:0;
  365. }
  366.  
  367. code.syntax-highlighted[class] {
  368. /*
  369. font-family: ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace !important;
  370. font-size: 9pt;
  371. */
  372. font-family: monospace;
  373. font-size: 13px;
  374. font-variant-ligatures: contextual;
  375. line-height: 1.15rem;
  376. }
  377.  
  378.  
  379.  
  380.  
  381.  
  382. .hljs-comment[class], .hljs-quote[class] {
  383. font-style: inherit;
  384. color: #259789;
  385. }
  386.  
  387. .hljs-add-marker-width .marker-fixed-width[class] {
  388. user-select: none !important;
  389. width: calc(var(--hljs-marker-width, 0em) + 16px);
  390. background: #f4f4f4;
  391. padding-right: 6px;
  392. margin-right: 4px;
  393. contain: paint style;
  394. }
  395.  
  396.  
  397. [dark] .hljs-add-marker-width .marker-fixed-width[class] {
  398.  
  399. background: #242424;
  400. color: #b6b2b2;
  401. }
  402.  
  403. `;
  404.  
  405.  
  406. const cssForCodePage = /\/scripts\/\d+[^\s\/\\]*\/code(\/|$)/.test(location.href) ? `
  407.  
  408. html:not([dkkfv]) div.code-container {
  409. position: absolute !important;
  410. display: none;
  411. }
  412.  
  413. html:not([dkkfv]) div.code-container > pre{
  414. display:none;
  415. }
  416.  
  417.  
  418. html:not([dkkfv]) code:only-child {
  419. display:none;
  420. }
  421.  
  422.  
  423. .code-container,
  424. .code-container pre:only-child,
  425. .code-container pre:only-child code:only-child {
  426. max-height: calc(100vh + 4px);
  427. max-width: calc(100vw + 4px);
  428. }
  429. ` : '';
  430.  
  431.  
  432. const cssAdd = `
  433.  
  434. ${global_css}
  435.  
  436. ${cssForCodePage}
  437.  
  438. .code-container {
  439. max-width: 100%;
  440. display: inline-flex;
  441. flex-direction: column;
  442. overflow: auto;
  443. border-radius: 8px;
  444. max-height: 100%;
  445. overflow: visible;
  446. }
  447. .code-container > pre:only-child {
  448. max-width: 100%;
  449. display: inline-flex;
  450. flex-direction: column;
  451. flex-grow: 1;
  452. height: 0;
  453. }
  454. .code-container > pre:only-child > code:only-child {
  455. max-width: 100%;
  456. flex-grow: 1;
  457. height: 0;
  458. }
  459. .code-container pre code {
  460. padding: 0;
  461. font-family: Consolas;
  462. cursor: text;
  463. overflow: auto;
  464. }
  465. .code-container pre code .marker {
  466. display: inline-block;
  467. color: #636d83;
  468. text-align: right;
  469. padding-right: 20px;
  470. user-select: none;
  471. cursor: auto;
  472. }
  473.  
  474. .code-container[contenteditable]{
  475. outline: 0 !important;
  476. contain: strict;
  477. }
  478.  
  479. .code-container[contenteditable]>pre[contenteditable="false"]{
  480. contain: strict;
  481. }
  482.  
  483.  
  484.  
  485.  
  486. html {
  487.  
  488. --token-color-keyword: #07a;
  489. --token-color-punctuation: #1415ec;
  490. --token-color-comment: #259789;
  491. --token-color-function: #da204f;
  492. }
  493.  
  494. [dark] {
  495.  
  496. --token-color-keyword: #898af2;
  497. --token-color-punctuation: #fadbdb;
  498. --token-color-comment:#59c6b9;
  499. --token-color-function: #e98aa2;
  500.  
  501. }
  502.  
  503.  
  504. body .token.comment {
  505. color: var(--token-color-comment);
  506. }
  507.  
  508. body .token.atrule, body .token.attr-value, body .token.keyword {
  509. color: #1415ec;
  510. color: var(--token-color-keyword);
  511. }
  512.  
  513.  
  514. .language-stylus .token.atrule, .language-stylus .token.attr-value, .language-stylus .token.keyword {
  515. color: #700d0d;
  516. }
  517.  
  518.  
  519. body .token.punctuation{
  520. color: var(--token-color-punctuation);
  521. }
  522.  
  523.  
  524. body .token.variable-declaration,
  525. body .token.variable {
  526. color: #0d10cd;
  527. }
  528.  
  529. body .token.selector{
  530. color: #1373bb;
  531. }
  532.  
  533.  
  534. body .token.function {
  535. color:var(--token-color-function);
  536. }
  537.  
  538.  
  539.  
  540. .language-stylus .token.variable-declaration,
  541. .language-stylus .token.variable {
  542. color: #0d10cd;
  543. }
  544.  
  545. .language-stylus .token.selector{
  546. color: #1373bb;
  547. }
  548.  
  549. .language-stylus .token.punctuation{
  550. color:#700d0d;
  551. }
  552.  
  553.  
  554. .language-stylus .token.function {
  555. color:#da204f
  556. }
  557.  
  558.  
  559.  
  560.  
  561. `;
  562.  
  563.  
  564.  
  565.  
  566. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName
  567. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName
  568.  
  569. HTMLElement.prototype.getElementsByTagName = getElementsByTagName
  570. Document.prototype.getElementsByTagName = getElementsByTagName
  571.  
  572.  
  573. const pScript = new PromiseExternal();
  574.  
  575. onBodyHeadReadyAsync().then(async () => {
  576.  
  577. if (!location.pathname.endsWith('/code')) {
  578. return;
  579. }
  580.  
  581. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd}`;
  582.  
  583. self.Prism = self.Prism || {};
  584. self.Prism.manual = true;
  585. await loadJS(resoruces['prism-core.js']);
  586. await loadJS(resoruces['prism-clike.js']);
  587. await loadJS(resoruces['prism-javascript.js']);
  588. await loadJS(resoruces['prism-css.js']);
  589. await loadJS(resoruces['prism-stylus.js']);
  590.  
  591. if (document.documentElement.hasAttribute('dark')) {
  592.  
  593. loadCSS(resoruces['prism-dark.css']);
  594. } else {
  595.  
  596. loadCSS(resoruces['prism.css']);
  597. }
  598.  
  599. pScript.resolve();
  600.  
  601.  
  602.  
  603.  
  604. });
  605.  
  606.  
  607. /** @param {HTMLElement} pre */
  608. async function prepareCodeAreaAsync(pre) {
  609.  
  610. for (const li of pre.querySelectorAll('li')) {
  611. li.append(document.createTextNode('\n'));
  612. }
  613.  
  614. const codeElement = document.createElement('code');
  615. // codeElement.classList.add('language-javascript');
  616. codeElement.innerHTML = pre.innerHTML;
  617.  
  618. // Clearing the original code container and appending the new one
  619. // pre.classList = '';
  620. pre.innerHTML = '';
  621. // pre.appendChild(codeElement);
  622.  
  623. // if (pre.querySelector('code')) return;
  624. const code = codeElement;
  625.  
  626. const codeContainer = pre.closest('.code-container');
  627. if (codeContainer && codeContainer.querySelector('.code-container>pre:only-child')) {
  628. // avoid selection to the outside by mouse dragging
  629. codeContainer.setAttribute('contenteditable', '');
  630. codeContainer.querySelector('.code-container>pre:only-child').setAttribute('contenteditable', 'false');
  631. }
  632.  
  633.  
  634. // let parentNode = code.parentNode;
  635. // let nextNode = code.nextSibling;
  636.  
  637. // code.remove();
  638. let parentNode = pre;
  639. let nextNode = null;
  640. await Promise.resolve().then();
  641.  
  642. // preset language
  643. /*
  644. const text = codeElement.textContent;
  645. if(/(^|\n)\s*\/\/\s+==UserScript==\s*\n/.test(text)){
  646. codeElement.classList.add('language-javascript');
  647. }else if(/(^|\n)\s*\/\*\s+==UserStyle==\s*\n/.test(text)){
  648. codeElement.classList.add('language-css');
  649. }
  650. */
  651. let className = '';
  652. if (pre.classList.contains('lang-js')) {
  653. className = 'language-javascript';
  654. codeElement.classList.add();
  655. } else if (pre.classList.contains('lang-css')) {
  656.  
  657. const text = codeElement.textContent;
  658. let m = /\n\@preprocessor\s+([-_a-zA-Z]{3,8})\s*\n/.exec(text);
  659. className = 'language-css'
  660. if (m) {
  661. const preprocessor = m[1];
  662. if (preprocessor === 'stylus') {
  663. className = 'language-stylus';
  664. } else if (preprocessor === 'uso') {
  665. className = 'language-stylus';
  666. } else if (preprocessor === 'less') {
  667. className = 'language-less';
  668. } else if (preprocessor === 'default') {
  669. className = 'language-stylus';
  670. } else {
  671. className = 'language-stylus';
  672. }
  673. }
  674.  
  675.  
  676. }
  677.  
  678.  
  679. if (!className) return;
  680.  
  681.  
  682.  
  683.  
  684. codeElement.classList.add(className);
  685. codeElement.classList.add('syntax-highlighted')
  686.  
  687. let htmlCode = '';
  688.  
  689. if (className === 'language-javascript') {
  690.  
  691.  
  692. htmlCode = Prism.highlight(code.textContent, Prism.languages.javascript, 'javascript');
  693. } else if (className === 'language-stylus') {
  694.  
  695. htmlCode = Prism.highlight(code.textContent, Prism.languages.stylus, 'stylus');
  696. } else if (className === 'language-less') {
  697.  
  698. htmlCode = Prism.highlight(code.textContent, Prism.languages.less, 'less');
  699.  
  700. } else {
  701.  
  702. htmlCode = Prism.highlight(code.textContent, Prism.languages.css, 'css');
  703. }
  704.  
  705.  
  706.  
  707. // Adding line numbers
  708. htmlCode = htmlCode || '';
  709. const htmlSplit = htmlCode ? htmlCode.split('\n') : [];
  710. const totalLines = htmlSplit.length;
  711.  
  712. let mwStyle = '';
  713.  
  714. if (totalLines >= 1) {
  715. code.classList.add('hljs-add-marker-width');
  716. const len = `${totalLines}`.length * 0.5;
  717. mwStyle = `${len}em`;
  718. htmlCode = htmlSplit.map((n, i) => `<span class="marker marker-fixed-width">${i + 1}</span>${n}`).join('\n');
  719.  
  720. } else {
  721.  
  722. code.classList.remove('hljs-add-marker-width');
  723. }
  724.  
  725. let targetCode = code;
  726.  
  727. if (htmlCode) {
  728.  
  729. const template = document.createElement('template');
  730.  
  731. template.innerHTML = `<code>${htmlCode}</code>`;
  732. const code2 = template.content.firstChild;
  733. for (const className of code.classList) {
  734. code2.classList.add(className);
  735. }
  736.  
  737. targetCode = code2;
  738. } else {
  739. code.innerHTML = "";
  740. targetCode = code;
  741. }
  742.  
  743. targetCode.style.setProperty('--hljs-marker-width', mwStyle);
  744.  
  745. parentNode.insertBefore(targetCode, nextNode);
  746.  
  747.  
  748.  
  749. }
  750. documentReady.then(async () => {
  751.  
  752. if (!location.pathname.endsWith('/code')) {
  753. byPass = false;
  754. return;
  755. }
  756.  
  757. await pScript.then();
  758.  
  759. // Code highlighting
  760. const promises = [...document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css')].map(prepareCodeAreaAsync)
  761. Promise.all(promises).then(() => {
  762. setTimeout(() => {
  763. document.documentElement.setAttribute('dkkfv', '');
  764. }, 1);
  765. })
  766.  
  767. });
  768.  
  769.  
  770. })();
  771.