GreasyFork Code: Syntax Highlight by CodeMirror

To syntax highlight GreasyFork Code by CodeMirror

As of 2024-01-28. See the latest version.

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by CodeMirror
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.4.4
  6. // @author CY Fung
  7. // @description To syntax highlight GreasyFork Code by CodeMirror
  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 cdn = 'https://cdn.jsdelivr.net/npm/codemirror@5.65.16';
  21. const resoruces = {
  22. 'codemirror.min.js': `${cdn}/lib/codemirror.min.js`,
  23. 'javascript.min.js': `${cdn}/mode/javascript/javascript.min.js`,
  24. 'css.min.js': `${cdn}/mode/css/css.min.js`,
  25. 'stylus.min.js': `${cdn}/mode/stylus/stylus.min.js`,
  26. 'active-line.min.js': `${cdn}/addon/selection/active-line.min.js`,
  27. 'search.js': `${cdn}/addon/search/search.js`,
  28. 'searchcursor.js': `${cdn}/addon/search/searchcursor.js`,
  29. 'jump-to-line.js': `${cdn}/addon/search/jump-to-line.js`,
  30. 'dialog.js': `${cdn}/addon/dialog/dialog.js`,
  31. 'codemirror.min.css': `${cdn}/lib/codemirror.min.css`,
  32. 'dialog.css': `${cdn}/addon/dialog/dialog.css`,
  33. 'material.css': `${cdn}/theme/material.css`,
  34. }
  35.  
  36. const doActionCSS = () => `
  37.  
  38. .code-container{
  39. height:100vh;
  40. }
  41. .code-container .CodeMirror, .code-container textarea{
  42. height:100%;
  43. }
  44. `;
  45.  
  46.  
  47. const global_css = () => `
  48.  
  49. html {
  50. line-height: 1.5;
  51. -webkit-text-size-adjust: 100%;
  52. -moz-tab-size: 4;
  53. -o-tab-size: 4;
  54. tab-size: 4;
  55. 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;
  56. font-feature-settings: normal;
  57. font-variation-settings: normal
  58. }
  59.  
  60. .code-container code, .code-container kbd, .code-container pre, .code-container samp {
  61. font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;
  62. font-size: 1em
  63. }
  64.  
  65. #script-content > .code-container[class] {
  66. width: 100%;
  67. }
  68.  
  69. .code-container[class] {
  70. border-radius: 0;
  71. }
  72.  
  73. .code-container[class] {
  74. border-radius: 0;
  75. }
  76.  
  77. .code-container > pre:only-child{
  78. padding:0;
  79. }
  80.  
  81. code.syntax-highlighted[class] {
  82. font-family: monospace;
  83. font-size: 13px;
  84. font-variant-ligatures: contextual;
  85. line-height: 1.15rem;
  86. text-shadow: none !important;
  87. }
  88.  
  89. .hljs-comment[class], .hljs-quote[class] {
  90. font-style: inherit;
  91. color: #259789;
  92. }
  93.  
  94. .hljs-add-marker-width .marker-fixed-width[class] {
  95. user-select: none !important;
  96. width: calc(var(--hljs-marker-width, 0em) + 16px);
  97. background: #f4f4f4;
  98. padding-right: 6px;
  99. margin-right: 4px;
  100. contain: paint style;
  101. }
  102.  
  103. [dark] .hljs-add-marker-width .marker-fixed-width[class] {
  104. background: #242424;
  105. color: #b6b2b2;
  106. }
  107.  
  108. .marker-fixed-width[marker-text]::before {
  109. content: attr(marker-text);
  110. }
  111.  
  112.  
  113. @keyframes cmLineNumberAppear {
  114. from {
  115. background-position-x: 3px;
  116. }
  117. to {
  118. background-position-x: 4px;
  119. }
  120. }
  121.  
  122. .CodeMirror-linenumber:not(:empty){
  123. animation: cmLineNumberAppear 1ms linear 0s 1 normal forwards;
  124. }
  125.  
  126. .CodeMirror-linenumber[marker-text]::before {
  127. content: attr(marker-text);
  128. }
  129.  
  130. `;
  131.  
  132.  
  133. const cssForCodePage = () => /\/scripts\/\d+[^\s\/\\]*\/code(\/|$)/.test(location.href) ? `
  134.  
  135. html:not([dkkfv]) div.code-container {
  136. visibility: collapse;
  137. }
  138.  
  139. .code-container,
  140. .code-container pre:only-child,
  141. .code-container pre:only-child code:only-child {
  142. max-height: calc(100vh + 4px);
  143. max-width: calc(100vw + 4px);
  144. }
  145. ` : '';
  146.  
  147.  
  148. const cssAdd = () => `
  149.  
  150. ${global_css()}
  151.  
  152. ${cssForCodePage()}
  153.  
  154. .code-container {
  155. max-width: 100%;
  156. display: inline-flex;
  157. flex-direction: column;
  158. overflow: auto;
  159. border-radius: 8px;
  160. max-height: 100%;
  161. overflow: visible;
  162. }
  163. .code-container > pre:only-child {
  164. max-width: 100%;
  165. display: inline-flex;
  166. flex-direction: column;
  167. flex-grow: 1;
  168. height: 0;
  169. }
  170. .code-container > pre:only-child > code:only-child {
  171. max-width: 100%;
  172. flex-grow: 1;
  173. height: 0;
  174. }
  175. .code-container pre code {
  176. padding: 0;
  177. font-family: Consolas;
  178. cursor: text;
  179. overflow: auto;
  180. box-sizing: border-box;
  181. }
  182. .code-container pre code .marker {
  183. display: inline-block;
  184. color: #636d83;
  185. text-align: right;
  186. padding-right: 20px;
  187. user-select: none;
  188. cursor: auto;
  189. }
  190.  
  191. .code-container[contenteditable]{
  192. outline: 0 !important;
  193. contain: strict;
  194. box-sizing: border-box;
  195. }
  196.  
  197. .code-container[contenteditable]>pre[contenteditable="false"]{
  198. contain: strict;
  199. width: initial;
  200. box-sizing: border-box;
  201. }
  202.  
  203. html {
  204. --token-color-comment: #259789;
  205.  
  206. }
  207.  
  208. [dark] {
  209. --token-color-comment:#59c6b9;
  210. }
  211.  
  212.  
  213. .CodeMirror .cm-comment[class] {
  214. color: var(--token-color-comment);
  215. }
  216.  
  217.  
  218. html .CodeMirror .CodeMirror-linenumber[class] {
  219. background: #f4f4f4;
  220. color: #636d83;
  221. padding-right: 6px;
  222. margin-right: 4px;
  223. contain: paint style;
  224. user-select: none !important;
  225. }
  226.  
  227. [dark] .CodeMirror .CodeMirror-linenumber[class] {
  228. background: #242424;
  229. color: #b6b2b2;
  230. }
  231.  
  232. html .CodeMirror[class] {
  233. background-color: inherit;
  234. }
  235.  
  236. html .CodeMirror[class] .CodeMirror-dialog[class] {
  237. background-color: #fefefe;
  238. }
  239.  
  240. [dark] .CodeMirror[class] .CodeMirror-dialog[class] {
  241. background-color: #25262d;
  242. }
  243.  
  244. html .CodeMirror .CodeMirror-activeline-background[class] {
  245. background: inherit;
  246. background-color: #8fd9da17;
  247. }
  248.  
  249. div.code-container .CodeMirror .CodeMirror-lines {
  250. padding: 0;
  251. }
  252.  
  253. div.code-container .CodeMirror {
  254. font-family: monospace;
  255. font-size: 13px;
  256. font-variant-ligatures: contextual;
  257. line-height: 1.15rem;
  258. text-shadow: none !important;
  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. const pScript = new PromiseExternal();
  284. const pElementQuery = new PromiseExternal();
  285.  
  286. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName;
  287. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName;
  288.  
  289. HTMLElement.prototype.getElementsByTagName = getElementsByTagName;
  290. Document.prototype.getElementsByTagName = getElementsByTagName;
  291.  
  292. let byPass = true;
  293.  
  294. const observablePromise = (proc, timeoutPromise) => {
  295. let promise = null;
  296. return {
  297. obtain() {
  298. if (!promise) {
  299. promise = new Promise(resolve => {
  300. let mo = null;
  301. const f = () => {
  302. let t = proc();
  303. if (t) {
  304. mo.disconnect();
  305. mo.takeRecords();
  306. mo = null;
  307. resolve(t);
  308. }
  309. }
  310. mo = new MutationObserver(f);
  311. mo.observe(document, { subtree: true, childList: true })
  312. f();
  313. timeoutPromise && timeoutPromise.then(() => {
  314. resolve(null)
  315. });
  316. });
  317. }
  318. return promise
  319. }
  320. }
  321. }
  322.  
  323. const documentReady = new Promise(resolve => {
  324. Promise.resolve().then(() => {
  325. if (document.readyState !== 'loading') {
  326. resolve();
  327. } else {
  328. window.addEventListener("DOMContentLoaded", resolve, false);
  329. }
  330. });
  331. });
  332.  
  333. function getElementsByTagName(tag) {
  334. if (byPass) {
  335. if (tag === 'pre' || tag === 'code' || tag === 'xmp') {
  336. if (location.pathname.endsWith('/code')) {
  337. pElementQuery.resolve();
  338. return [];
  339. }
  340. }
  341. }
  342. return this.getElementsByTagName331(tag);
  343. }
  344.  
  345. async function onBodyHeadReadyAsync() {
  346. await observablePromise(() => document.body && document.head).obtain();
  347. }
  348.  
  349.  
  350. // Load CSS
  351. function loadJS(href) {
  352.  
  353. return new Promise(resolve => {
  354.  
  355. const script = document.createElement('script');
  356. script.src = href;
  357. script.onload = () => {
  358. resolve(script);
  359. };
  360. document.head.appendChild(script);
  361.  
  362. });
  363.  
  364. }
  365.  
  366. // Load CSS
  367. function loadCSS(href) {
  368. const link = document.createElement('link');
  369. link.rel = 'stylesheet';
  370. link.href = href;
  371. document.head.appendChild(link);
  372. return link;
  373. }
  374.  
  375.  
  376.  
  377.  
  378.  
  379.  
  380. /** @param {HTMLElement} pre */
  381. async function prepareCodeAreaAsync(pre) {
  382.  
  383. if (pre.isConnected === false) return;
  384.  
  385. for (const li of pre.querySelectorAll('li')) {
  386. li.append(document.createTextNode('\n'));
  387. }
  388.  
  389. const codeElement = document.createElement('code');
  390. // codeElement.classList.add('language-javascript');
  391. codeElement.innerHTML = pre.innerHTML;
  392.  
  393. // Clearing the original code container and appending the new one
  394. // pre.classList = '';
  395. pre.innerHTML = '';
  396. // pre.appendChild(codeElement);
  397.  
  398. // if (pre.querySelector('code')) return;
  399. const code = codeElement;
  400.  
  401. const codeContainer = pre.closest('.code-container');
  402. if (codeContainer && codeContainer.querySelector('.code-container>pre:only-child')) {
  403. // avoid selection to the outside by mouse dragging
  404. codeContainer.setAttribute('contenteditable', '');
  405. codeContainer.querySelector('.code-container>pre:only-child').setAttribute('contenteditable', 'false');
  406. }
  407.  
  408.  
  409. // let parentNode = code.parentNode;
  410. // let nextNode = code.nextSibling;
  411.  
  412. // code.remove();
  413. let parentNode = pre;
  414. let nextNode = null;
  415. await Promise.resolve().then();
  416.  
  417. // preset language
  418. /*
  419. const text = codeElement.textContent;
  420. if(/(^|\n)\s*\/\/\s+==UserScript==\s*\n/.test(text)){
  421. codeElement.classList.add('language-javascript');
  422. }else if(/(^|\n)\s*\/\*\s+==UserStyle==\s*\n/.test(text)){
  423. codeElement.classList.add('language-css');
  424. }
  425. */
  426. let className = '';
  427. if (pre.classList.contains('lang-js')) {
  428. className = 'language-javascript';
  429. } else if (pre.classList.contains('lang-css')) {
  430.  
  431. const text = codeElement.textContent;
  432. let m = /\n@preprocessor\s+([-_a-zA-Z]{3,8})\s*\n/.exec(text);
  433. className = 'language-css'
  434. if (m) {
  435. const preprocessor = m[1];
  436. if (preprocessor === 'stylus') {
  437. className = 'language-stylus';
  438. } else if (preprocessor === 'uso') {
  439. className = 'language-stylus';
  440. } else if (preprocessor === 'less') {
  441. className = 'language-less';
  442. } else if (preprocessor === 'default') {
  443. className = 'language-stylus';
  444. } else {
  445. className = 'language-stylus';
  446. }
  447. }
  448.  
  449.  
  450. }
  451.  
  452.  
  453. if (!className) return;
  454.  
  455. let mode = '';
  456. if (className === 'language-javascript') mode = 'javascript';
  457. if (className === 'language-stylus') mode = 'stylus';
  458. if (className === 'language-less') mode = 'less';
  459. if (className === 'language-css') mode = 'css';
  460.  
  461. if (!mode) return;
  462.  
  463.  
  464.  
  465. let textarea = document.createElement('textarea');
  466. textarea.value = `${code.textContent}`;
  467. textarea.readOnly = true;
  468. textarea.id = 'editor651';
  469.  
  470.  
  471. // textarea.classList.add('code-container')
  472.  
  473. textarea.style.width = '100%';
  474. textarea.style.height = '100vh';
  475.  
  476. parentNode.insertBefore(textarea, nextNode);
  477.  
  478.  
  479. let editor651 = CodeMirror.fromTextArea(document.querySelector('#editor651'), {
  480.  
  481. mode: mode,
  482. theme: document.documentElement.hasAttribute('dark') ? 'material' : 'default',
  483.  
  484. readOnly: true,
  485. styleActiveLine: true,
  486. lineNumbers: true,
  487. extraKeys: { "Alt-F": "findPersistent" }
  488. });
  489. editor651.save();
  490.  
  491.  
  492.  
  493. }
  494.  
  495. const documentBodyHeadReady = onBodyHeadReadyAsync();
  496.  
  497. documentBodyHeadReady.then(async () => {
  498.  
  499. if (!location.pathname.endsWith('/code')) {
  500. return;
  501. }
  502.  
  503. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd()}`;
  504.  
  505. await loadJS(resoruces['codemirror.min.js']);
  506.  
  507. await Promise.all([
  508. loadJS(resoruces['javascript.min.js']),
  509. loadJS(resoruces['css.min.js']),
  510. loadJS(resoruces['stylus.min.js']),
  511. loadJS(resoruces['active-line.min.js']),
  512. loadJS(resoruces['search.js']),
  513. loadJS(resoruces['searchcursor.js']),
  514. loadJS(resoruces['jump-to-line.js']),
  515. loadJS(resoruces['dialog.js'])
  516. ]);
  517.  
  518. if (document.documentElement.hasAttribute('dark')) {
  519.  
  520. // TBC
  521. loadCSS(resoruces['codemirror.min.css']);
  522. loadCSS(resoruces['dialog.css']);
  523. loadCSS(resoruces['material.css']);
  524.  
  525. } else {
  526.  
  527. loadCSS(resoruces['codemirror.min.css']);
  528. loadCSS(resoruces['dialog.css']);
  529. }
  530.  
  531.  
  532. pScript.resolve();
  533.  
  534.  
  535.  
  536.  
  537. });
  538.  
  539. let keydownActive = false;
  540.  
  541. documentReady.then(async () => {
  542.  
  543. if (!location.pathname.endsWith('/code')) {
  544. byPass = false;
  545. return;
  546. }
  547.  
  548. await pScript.then();
  549.  
  550. await Promise.race([pElementQuery, delayPn(800)]);
  551.  
  552. const targets = document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css');
  553.  
  554. if (targets.length === 0) return;
  555.  
  556. await delayPn(40);
  557.  
  558. document.head.appendChild(document.createElement('style')).textContent = doActionCSS();
  559.  
  560. await delayPn(40);
  561.  
  562. byPass = false;
  563.  
  564. // Code highlighting
  565. const promises = [...targets].map(prepareCodeAreaAsync)
  566. await Promise.all(promises);
  567.  
  568. await delayPn(40);
  569. document.documentElement.setAttribute('dkkfv', '');
  570. keydownActive = true;
  571.  
  572. });
  573.  
  574. function selectAllWithinElement(element) {
  575. window.getSelection().removeAllRanges();
  576. let range = document.createRange();
  577. if (element) {
  578. range.selectNodeContents(element);
  579. window.getSelection().addRange(range);
  580. } else {
  581. console.error('Element not found with ID:', element);
  582. }
  583. }
  584. document.addEventListener('keydown', (e) => {
  585. if (keydownActive && e && e.code === 'KeyA' && e.isTrusted && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
  586.  
  587. const target = e.target;
  588. const container = target ? target.closest('div.code-container') : null;
  589. const code = container ? container.querySelector('code') : null;
  590.  
  591. if (container && code) {
  592.  
  593. e.preventDefault();
  594. e.stopPropagation();
  595. e.stopImmediatePropagation();
  596.  
  597. setTimeout(() => {
  598. selectAllWithinElement(code);
  599. }, 1)
  600.  
  601. }
  602.  
  603. }
  604. }, true);
  605.  
  606.  
  607. const cmLineNumberAppearFn = (evt) => {
  608. const elm = evt.target;
  609. if (!(elm instanceof HTMLElement)) return;
  610.  
  611. elm.setAttribute('marker-text', elm.textContent.trim());
  612. elm.textContent = '';
  613. }
  614.  
  615. document.addEventListener('animationstart', (evt) => {
  616. const animationName = evt.animationName;
  617. if (!animationName) return;
  618. if (animationName === 'cmLineNumberAppear') cmLineNumberAppearFn(evt);
  619. }, { capture: true, passive: true });
  620.  
  621.  
  622. })();