Greasy Fork is available in English.

GreasyFork Code: Syntax Highlight by PrismJS

To syntax highlight GreasyFork Code by PrismJS

Verze ze dne 20. 12. 2023. Zobrazit nejnovější verzi.

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by PrismJS
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.2.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. // ==/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. text-shadow: none !important;
  377. }
  378.  
  379.  
  380.  
  381.  
  382.  
  383. .hljs-comment[class], .hljs-quote[class] {
  384. font-style: inherit;
  385. color: #259789;
  386. }
  387.  
  388. .hljs-add-marker-width .marker-fixed-width[class] {
  389. user-select: none !important;
  390. width: calc(var(--hljs-marker-width, 0em) + 16px);
  391. background: #f4f4f4;
  392. padding-right: 6px;
  393. margin-right: 4px;
  394. contain: paint style;
  395. }
  396.  
  397.  
  398. [dark] .hljs-add-marker-width .marker-fixed-width[class] {
  399.  
  400. background: #242424;
  401. color: #b6b2b2;
  402. }
  403.  
  404. `;
  405.  
  406.  
  407. const cssForCodePage = /\/scripts\/\d+[^\s\/\\]*\/code(\/|$)/.test(location.href) ? `
  408.  
  409. html:not([dkkfv]) div.code-container {
  410. position: absolute !important;
  411. display: none;
  412. }
  413.  
  414. html:not([dkkfv]) div.code-container > pre{
  415. display:none;
  416. }
  417.  
  418.  
  419. html:not([dkkfv]) code:only-child {
  420. display:none;
  421. }
  422.  
  423.  
  424. .code-container,
  425. .code-container pre:only-child,
  426. .code-container pre:only-child code:only-child {
  427. max-height: calc(100vh + 4px);
  428. max-width: calc(100vw + 4px);
  429. }
  430. ` : '';
  431.  
  432.  
  433. const cssAdd = `
  434.  
  435. ${global_css}
  436.  
  437. ${cssForCodePage}
  438.  
  439. .code-container {
  440. max-width: 100%;
  441. display: inline-flex;
  442. flex-direction: column;
  443. overflow: auto;
  444. border-radius: 8px;
  445. max-height: 100%;
  446. overflow: visible;
  447. }
  448. .code-container > pre:only-child {
  449. max-width: 100%;
  450. display: inline-flex;
  451. flex-direction: column;
  452. flex-grow: 1;
  453. height: 0;
  454. }
  455. .code-container > pre:only-child > code:only-child {
  456. max-width: 100%;
  457. flex-grow: 1;
  458. height: 0;
  459. }
  460. .code-container pre code {
  461. padding: 0;
  462. font-family: Consolas;
  463. cursor: text;
  464. overflow: auto;
  465. }
  466. .code-container pre code .marker {
  467. display: inline-block;
  468. color: #636d83;
  469. text-align: right;
  470. padding-right: 20px;
  471. user-select: none;
  472. cursor: auto;
  473. }
  474.  
  475. .code-container[contenteditable]{
  476. outline: 0 !important;
  477. contain: strict;
  478. }
  479.  
  480. .code-container[contenteditable]>pre[contenteditable="false"]{
  481. contain: strict;
  482. }
  483.  
  484.  
  485.  
  486.  
  487. html {
  488.  
  489. --token-color-keyword: #07a;
  490. --token-color-punctuation: #1415ec;
  491. --token-color-comment: #259789;
  492. --token-color-function: #da204f;
  493. }
  494.  
  495. [dark] {
  496.  
  497. --token-color-keyword: #898af2;
  498. --token-color-punctuation: #fadbdb;
  499. --token-color-comment:#59c6b9;
  500. --token-color-function: #e98aa2;
  501.  
  502. }
  503.  
  504.  
  505. body .token.comment {
  506. color: var(--token-color-comment);
  507. }
  508.  
  509. body .token.atrule, body .token.attr-value, body .token.keyword {
  510. color: #1415ec;
  511. color: var(--token-color-keyword);
  512. }
  513.  
  514.  
  515. .language-stylus .token.atrule, .language-stylus .token.attr-value, .language-stylus .token.keyword {
  516. color: #700d0d;
  517. }
  518.  
  519.  
  520. body .token.punctuation{
  521. color: var(--token-color-punctuation);
  522. }
  523.  
  524.  
  525. body .token.variable-declaration,
  526. body .token.variable {
  527. color: #0d10cd;
  528. }
  529.  
  530. body .token.selector{
  531. color: #1373bb;
  532. }
  533.  
  534.  
  535. body .token.function {
  536. color:var(--token-color-function);
  537. }
  538.  
  539.  
  540.  
  541. .language-stylus .token.variable-declaration,
  542. .language-stylus .token.variable {
  543. color: #0d10cd;
  544. }
  545.  
  546. .language-stylus .token.selector{
  547. color: #1373bb;
  548. }
  549.  
  550. .language-stylus .token.punctuation{
  551. color:#700d0d;
  552. }
  553.  
  554.  
  555. .language-stylus .token.function {
  556. color:#da204f
  557. }
  558.  
  559.  
  560.  
  561.  
  562. `;
  563.  
  564.  
  565.  
  566.  
  567. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName
  568. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName
  569.  
  570. HTMLElement.prototype.getElementsByTagName = getElementsByTagName
  571. Document.prototype.getElementsByTagName = getElementsByTagName
  572.  
  573.  
  574. const pScript = new PromiseExternal();
  575.  
  576. onBodyHeadReadyAsync().then(async () => {
  577.  
  578. if (!location.pathname.endsWith('/code')) {
  579. return;
  580. }
  581.  
  582. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd}`;
  583.  
  584. self.Prism = self.Prism || {};
  585. self.Prism.manual = true;
  586. await loadJS(resoruces['prism-core.js']);
  587. await loadJS(resoruces['prism-clike.js']);
  588. await loadJS(resoruces['prism-javascript.js']);
  589. await loadJS(resoruces['prism-css.js']);
  590. await loadJS(resoruces['prism-stylus.js']);
  591.  
  592. if (document.documentElement.hasAttribute('dark')) {
  593.  
  594. loadCSS(resoruces['prism-dark.css']);
  595. } else {
  596.  
  597. loadCSS(resoruces['prism.css']);
  598. }
  599.  
  600. pScript.resolve();
  601.  
  602.  
  603.  
  604.  
  605. });
  606.  
  607.  
  608. /** @param {HTMLElement} pre */
  609. async function prepareCodeAreaAsync(pre) {
  610.  
  611. for (const li of pre.querySelectorAll('li')) {
  612. li.append(document.createTextNode('\n'));
  613. }
  614.  
  615. const codeElement = document.createElement('code');
  616. // codeElement.classList.add('language-javascript');
  617. codeElement.innerHTML = pre.innerHTML;
  618.  
  619. // Clearing the original code container and appending the new one
  620. // pre.classList = '';
  621. pre.innerHTML = '';
  622. // pre.appendChild(codeElement);
  623.  
  624. // if (pre.querySelector('code')) return;
  625. const code = codeElement;
  626.  
  627. const codeContainer = pre.closest('.code-container');
  628. if (codeContainer && codeContainer.querySelector('.code-container>pre:only-child')) {
  629. // avoid selection to the outside by mouse dragging
  630. codeContainer.setAttribute('contenteditable', '');
  631. codeContainer.querySelector('.code-container>pre:only-child').setAttribute('contenteditable', 'false');
  632. }
  633.  
  634.  
  635. // let parentNode = code.parentNode;
  636. // let nextNode = code.nextSibling;
  637.  
  638. // code.remove();
  639. let parentNode = pre;
  640. let nextNode = null;
  641. await Promise.resolve().then();
  642.  
  643. // preset language
  644. /*
  645. const text = codeElement.textContent;
  646. if(/(^|\n)\s*\/\/\s+==UserScript==\s*\n/.test(text)){
  647. codeElement.classList.add('language-javascript');
  648. }else if(/(^|\n)\s*\/\*\s+==UserStyle==\s*\n/.test(text)){
  649. codeElement.classList.add('language-css');
  650. }
  651. */
  652. let className = '';
  653. if (pre.classList.contains('lang-js')) {
  654. className = 'language-javascript';
  655. codeElement.classList.add();
  656. } else if (pre.classList.contains('lang-css')) {
  657.  
  658. const text = codeElement.textContent;
  659. let m = /\n\@preprocessor\s+([-_a-zA-Z]{3,8})\s*\n/.exec(text);
  660. className = 'language-css'
  661. if (m) {
  662. const preprocessor = m[1];
  663. if (preprocessor === 'stylus') {
  664. className = 'language-stylus';
  665. } else if (preprocessor === 'uso') {
  666. className = 'language-stylus';
  667. } else if (preprocessor === 'less') {
  668. className = 'language-less';
  669. } else if (preprocessor === 'default') {
  670. className = 'language-stylus';
  671. } else {
  672. className = 'language-stylus';
  673. }
  674. }
  675.  
  676.  
  677. }
  678.  
  679.  
  680. if (!className) return;
  681.  
  682.  
  683.  
  684.  
  685. codeElement.classList.add(className);
  686. codeElement.classList.add('syntax-highlighted')
  687.  
  688. let htmlCode = '';
  689.  
  690. if (className === 'language-javascript') {
  691.  
  692.  
  693. htmlCode = Prism.highlight(code.textContent, Prism.languages.javascript, 'javascript');
  694. } else if (className === 'language-stylus') {
  695.  
  696. htmlCode = Prism.highlight(code.textContent, Prism.languages.stylus, 'stylus');
  697. } else if (className === 'language-less') {
  698.  
  699. htmlCode = Prism.highlight(code.textContent, Prism.languages.less, 'less');
  700.  
  701. } else {
  702.  
  703. htmlCode = Prism.highlight(code.textContent, Prism.languages.css, 'css');
  704. }
  705.  
  706.  
  707.  
  708. // Adding line numbers
  709. htmlCode = htmlCode || '';
  710. const htmlSplit = htmlCode ? htmlCode.split('\n') : [];
  711. const totalLines = htmlSplit.length;
  712.  
  713. let mwStyle = '';
  714.  
  715. if (totalLines >= 1) {
  716. code.classList.add('hljs-add-marker-width');
  717. const len = `${totalLines}`.length * 0.5;
  718. mwStyle = `${len}em`;
  719. htmlCode = htmlSplit.map((n, i) => `<span class="marker marker-fixed-width">${i + 1}</span>${n}`).join('\n');
  720.  
  721. } else {
  722.  
  723. code.classList.remove('hljs-add-marker-width');
  724. }
  725.  
  726. let targetCode = code;
  727.  
  728. if (htmlCode) {
  729.  
  730. const template = document.createElement('template');
  731.  
  732. template.innerHTML = `<code>${htmlCode}</code>`;
  733. const code2 = template.content.firstChild;
  734. for (const className of code.classList) {
  735. code2.classList.add(className);
  736. }
  737.  
  738. targetCode = code2;
  739. } else {
  740. code.innerHTML = "";
  741. targetCode = code;
  742. }
  743.  
  744. targetCode.style.setProperty('--hljs-marker-width', mwStyle);
  745.  
  746. parentNode.insertBefore(targetCode, nextNode);
  747.  
  748.  
  749.  
  750. }
  751. documentReady.then(async () => {
  752.  
  753. if (!location.pathname.endsWith('/code')) {
  754. byPass = false;
  755. return;
  756. }
  757.  
  758. await pScript.then();
  759.  
  760. // Code highlighting
  761. const promises = [...document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css')].map(prepareCodeAreaAsync)
  762. Promise.all(promises).then(() => {
  763. setTimeout(() => {
  764. document.documentElement.setAttribute('dkkfv', '');
  765. }, 1);
  766. })
  767.  
  768. });
  769.  
  770.  
  771. })();
  772.