GreasyFork Code: Syntax Highlight by CodeMirror

To syntax highlight GreasyFork Code by CodeMirror

Fra 28.01.2024. Se den seneste versjonen.

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by CodeMirror
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.4.5
  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.  
  134. const cssForCodePage = () => /\/scripts\/\d+[^\s\/\\]*\/code(\/|$)/.test(location.href) ? `
  135.  
  136. html:not([dkkfv]) div.code-container {
  137. visibility: collapse;
  138. }
  139.  
  140. .code-container,
  141. .code-container pre:only-child,
  142. .code-container pre:only-child code:only-child {
  143. max-height: calc(100vh + 4px);
  144. max-width: calc(100vw + 4px);
  145. }
  146. ` : '';
  147.  
  148.  
  149. const cssAdd = () => `
  150.  
  151. ${global_css()}
  152.  
  153. ${cssForCodePage()}
  154.  
  155. .code-container {
  156. max-width: 100%;
  157. display: inline-flex;
  158. flex-direction: column;
  159. overflow: auto;
  160. border-radius: 8px;
  161. max-height: 100%;
  162. overflow: visible;
  163. }
  164. .code-container > pre:only-child {
  165. max-width: 100%;
  166. display: inline-flex;
  167. flex-direction: column;
  168. flex-grow: 1;
  169. height: 0;
  170. }
  171. .code-container > pre:only-child > code:only-child {
  172. max-width: 100%;
  173. flex-grow: 1;
  174. height: 0;
  175. }
  176. .code-container pre code {
  177. padding: 0;
  178. font-family: Consolas;
  179. cursor: text;
  180. overflow: auto;
  181. box-sizing: border-box;
  182. }
  183. .code-container pre code .marker {
  184. display: inline-block;
  185. color: #636d83;
  186. text-align: right;
  187. padding-right: 20px;
  188. user-select: none;
  189. cursor: auto;
  190. }
  191.  
  192. .code-container[contenteditable]{
  193. outline: 0 !important;
  194. contain: strict;
  195. box-sizing: border-box;
  196. }
  197.  
  198. .code-container[contenteditable]>pre[contenteditable="false"]{
  199. contain: strict;
  200. width: initial;
  201. box-sizing: border-box;
  202. }
  203.  
  204. html {
  205. --token-color-comment: #259789;
  206. --cm-dialog-background-color: #fefefe;
  207. --cm-linenumber-background-color: #f4f4f4;
  208. --cm-linenumber-text-color: #636d83;
  209. --cm-search-color: #ffeb3ab8;
  210. }
  211.  
  212. [dark] {
  213. --token-color-comment:#59c6b9;
  214. --cm-dialog-background-color: #25262d;
  215. --cm-linenumber-background-color: #242424;
  216. --cm-linenumber-text-color: #b6b2b2;
  217. --cm-search-color: #b25f06b8;
  218. }
  219.  
  220.  
  221. .CodeMirror .cm-comment[class] {
  222. color: var(--token-color-comment);
  223. }
  224.  
  225.  
  226. html .CodeMirror .CodeMirror-linenumber[class] {
  227. background: var(--cm-linenumber-background-color);
  228. color: var(--cm-linenumber-text-color);
  229. padding-right: 6px;
  230. margin-right: 4px;
  231. contain: paint style;
  232. user-select: none !important;
  233. }
  234.  
  235. html .CodeMirror[class] {
  236. background-color: inherit;
  237. }
  238.  
  239. .CodeMirror[class] .cm-searching {
  240. background-color: var(--cm-search-color);
  241. }
  242.  
  243. .CodeMirror[class] .CodeMirror-dialog[class] {
  244. background-color: var(--cm-dialog-background-color);
  245. }
  246.  
  247. html .CodeMirror .CodeMirror-activeline-background[class] {
  248. background: inherit;
  249. background-color: #8fd9da17;
  250. }
  251.  
  252. div.code-container .CodeMirror .CodeMirror-lines {
  253. padding: 0;
  254. }
  255.  
  256. div.code-container .CodeMirror {
  257. font-family: monospace;
  258. font-size: 13px;
  259. font-variant-ligatures: contextual;
  260. line-height: 1.15rem;
  261. text-shadow: none !important;
  262. }
  263.  
  264.  
  265. `;
  266.  
  267. const Promise = (async function () { })().constructor;
  268.  
  269. const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
  270.  
  271. const PromiseExternal = ((resolve_, reject_) => {
  272. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  273. return class PromiseExternal extends Promise {
  274. constructor(cb = h) {
  275. super(cb);
  276. if (cb === h) {
  277. /** @type {(value: any) => void} */
  278. this.resolve = resolve_;
  279. /** @type {(reason?: any) => void} */
  280. this.reject = reject_;
  281. }
  282. }
  283. };
  284. })();
  285.  
  286. const pScript = new PromiseExternal();
  287. const pElementQuery = new PromiseExternal();
  288.  
  289. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName;
  290. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName;
  291.  
  292. HTMLElement.prototype.getElementsByTagName = getElementsByTagName;
  293. Document.prototype.getElementsByTagName = getElementsByTagName;
  294.  
  295. let byPass = true;
  296.  
  297. const observablePromise = (proc, timeoutPromise) => {
  298. let promise = null;
  299. return {
  300. obtain() {
  301. if (!promise) {
  302. promise = new Promise(resolve => {
  303. let mo = null;
  304. const f = () => {
  305. let t = proc();
  306. if (t) {
  307. mo.disconnect();
  308. mo.takeRecords();
  309. mo = null;
  310. resolve(t);
  311. }
  312. }
  313. mo = new MutationObserver(f);
  314. mo.observe(document, { subtree: true, childList: true })
  315. f();
  316. timeoutPromise && timeoutPromise.then(() => {
  317. resolve(null)
  318. });
  319. });
  320. }
  321. return promise
  322. }
  323. }
  324. }
  325.  
  326. const documentReady = new Promise(resolve => {
  327. Promise.resolve().then(() => {
  328. if (document.readyState !== 'loading') {
  329. resolve();
  330. } else {
  331. window.addEventListener("DOMContentLoaded", resolve, false);
  332. }
  333. });
  334. });
  335.  
  336. function getElementsByTagName(tag) {
  337. if (byPass) {
  338. if (tag === 'pre' || tag === 'code' || tag === 'xmp') {
  339. if (location.pathname.endsWith('/code')) {
  340. pElementQuery.resolve();
  341. return [];
  342. }
  343. }
  344. }
  345. return this.getElementsByTagName331(tag);
  346. }
  347.  
  348. async function onBodyHeadReadyAsync() {
  349. await observablePromise(() => document.body && document.head).obtain();
  350. }
  351.  
  352.  
  353. // Load CSS
  354. function loadJS(href) {
  355.  
  356. return new Promise(resolve => {
  357.  
  358. const script = document.createElement('script');
  359. script.src = href;
  360. script.onload = () => {
  361. resolve(script);
  362. };
  363. document.head.appendChild(script);
  364.  
  365. });
  366.  
  367. }
  368.  
  369. // Load CSS
  370. function loadCSS(href) {
  371. const link = document.createElement('link');
  372. link.rel = 'stylesheet';
  373. link.href = href;
  374. document.head.appendChild(link);
  375. return link;
  376. }
  377.  
  378.  
  379.  
  380.  
  381.  
  382.  
  383. /** @param {HTMLElement} pre */
  384. async function prepareCodeAreaAsync(pre) {
  385.  
  386. if (pre.isConnected === false) return;
  387.  
  388. for (const li of pre.querySelectorAll('li')) {
  389. li.append(document.createTextNode('\n'));
  390. }
  391.  
  392. const codeElement = document.createElement('code');
  393. // codeElement.classList.add('language-javascript');
  394. codeElement.innerHTML = pre.innerHTML;
  395.  
  396. // Clearing the original code container and appending the new one
  397. // pre.classList = '';
  398. pre.innerHTML = '';
  399. // pre.appendChild(codeElement);
  400.  
  401. // if (pre.querySelector('code')) return;
  402. const code = codeElement;
  403.  
  404. const codeContainer = pre.closest('.code-container');
  405. if (codeContainer && codeContainer.querySelector('.code-container>pre:only-child')) {
  406. // avoid selection to the outside by mouse dragging
  407. codeContainer.setAttribute('contenteditable', '');
  408. codeContainer.querySelector('.code-container>pre:only-child').setAttribute('contenteditable', 'false');
  409. }
  410.  
  411.  
  412. // let parentNode = code.parentNode;
  413. // let nextNode = code.nextSibling;
  414.  
  415. // code.remove();
  416. let parentNode = pre;
  417. let nextNode = null;
  418. await Promise.resolve().then();
  419.  
  420. // preset language
  421. /*
  422. const text = codeElement.textContent;
  423. if(/(^|\n)\s*\/\/\s+==UserScript==\s*\n/.test(text)){
  424. codeElement.classList.add('language-javascript');
  425. }else if(/(^|\n)\s*\/\*\s+==UserStyle==\s*\n/.test(text)){
  426. codeElement.classList.add('language-css');
  427. }
  428. */
  429. let className = '';
  430. if (pre.classList.contains('lang-js')) {
  431. className = 'language-javascript';
  432. } else if (pre.classList.contains('lang-css')) {
  433.  
  434. const text = codeElement.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.  
  455.  
  456. if (!className) return;
  457.  
  458. let mode = '';
  459. if (className === 'language-javascript') mode = 'javascript';
  460. if (className === 'language-stylus') mode = 'stylus';
  461. if (className === 'language-less') mode = 'less';
  462. if (className === 'language-css') mode = 'css';
  463.  
  464. if (!mode) return;
  465.  
  466.  
  467.  
  468. let textarea = document.createElement('textarea');
  469. textarea.value = `${code.textContent}`;
  470. textarea.readOnly = true;
  471. textarea.id = 'editor651';
  472.  
  473.  
  474. // textarea.classList.add('code-container')
  475.  
  476. textarea.style.width = '100%';
  477. textarea.style.height = '100vh';
  478.  
  479. parentNode.insertBefore(textarea, nextNode);
  480.  
  481.  
  482. let editor651 = CodeMirror.fromTextArea(document.querySelector('#editor651'), {
  483.  
  484. mode: mode,
  485. theme: document.documentElement.hasAttribute('dark') ? 'material' : 'default',
  486.  
  487. readOnly: true,
  488. styleActiveLine: true,
  489. lineNumbers: true,
  490. extraKeys: { "Alt-F": "findPersistent" }
  491. });
  492. editor651.save();
  493.  
  494.  
  495.  
  496. }
  497.  
  498. const documentBodyHeadReady = onBodyHeadReadyAsync();
  499.  
  500. documentBodyHeadReady.then(async () => {
  501.  
  502. if (!location.pathname.endsWith('/code')) {
  503. return;
  504. }
  505.  
  506. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd()}`;
  507.  
  508. await loadJS(resoruces['codemirror.min.js']);
  509.  
  510. await Promise.all([
  511. loadJS(resoruces['javascript.min.js']),
  512. loadJS(resoruces['css.min.js']),
  513. loadJS(resoruces['stylus.min.js']),
  514. loadJS(resoruces['active-line.min.js']),
  515. loadJS(resoruces['search.js']),
  516. loadJS(resoruces['searchcursor.js']),
  517. loadJS(resoruces['jump-to-line.js']),
  518. loadJS(resoruces['dialog.js'])
  519. ]);
  520.  
  521. if (document.documentElement.hasAttribute('dark')) {
  522.  
  523. // TBC
  524. loadCSS(resoruces['codemirror.min.css']);
  525. loadCSS(resoruces['dialog.css']);
  526. loadCSS(resoruces['material.css']);
  527.  
  528. } else {
  529.  
  530. loadCSS(resoruces['codemirror.min.css']);
  531. loadCSS(resoruces['dialog.css']);
  532. }
  533.  
  534.  
  535. pScript.resolve();
  536.  
  537.  
  538.  
  539.  
  540. });
  541.  
  542. let keydownActive = false;
  543.  
  544. documentReady.then(async () => {
  545.  
  546. if (!location.pathname.endsWith('/code')) {
  547. byPass = false;
  548. return;
  549. }
  550.  
  551. await pScript.then();
  552.  
  553. await Promise.race([pElementQuery, delayPn(800)]);
  554.  
  555. const targets = document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css');
  556.  
  557. if (targets.length === 0) return;
  558.  
  559. await delayPn(40);
  560.  
  561. document.head.appendChild(document.createElement('style')).textContent = doActionCSS();
  562.  
  563. await delayPn(40);
  564.  
  565. byPass = false;
  566.  
  567. // Code highlighting
  568. const promises = [...targets].map(prepareCodeAreaAsync)
  569. await Promise.all(promises);
  570.  
  571. await delayPn(40);
  572. document.documentElement.setAttribute('dkkfv', '');
  573. keydownActive = true;
  574.  
  575. });
  576.  
  577. function selectAllWithinElement(element) {
  578. window.getSelection().removeAllRanges();
  579. let range = document.createRange();
  580. if (element) {
  581. range.selectNodeContents(element);
  582. window.getSelection().addRange(range);
  583. } else {
  584. console.error('Element not found with ID:', element);
  585. }
  586. }
  587. document.addEventListener('keydown', (e) => {
  588. if (keydownActive && e && e.code === 'KeyA' && e.isTrusted && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
  589.  
  590. const target = e.target;
  591. const container = target ? target.closest('div.code-container') : null;
  592. const code = container ? container.querySelector('code') : null;
  593.  
  594. if (container && code) {
  595.  
  596. e.preventDefault();
  597. e.stopPropagation();
  598. e.stopImmediatePropagation();
  599.  
  600. setTimeout(() => {
  601. selectAllWithinElement(code);
  602. }, 1)
  603.  
  604. }
  605.  
  606. }
  607. }, true);
  608.  
  609.  
  610. const cmLineNumberAppearFn = (evt) => {
  611. const elm = evt.target;
  612. if (!(elm instanceof HTMLElement)) return;
  613.  
  614. elm.setAttribute('marker-text', elm.textContent.trim());
  615. elm.textContent = '';
  616. }
  617.  
  618. document.addEventListener('animationstart', (evt) => {
  619. const animationName = evt.animationName;
  620. if (!animationName) return;
  621. if (animationName === 'cmLineNumberAppear') cmLineNumberAppearFn(evt);
  622. }, { capture: true, passive: true });
  623.  
  624.  
  625. })();