GreasyFork Code: Syntax Highlight by CodeMirror

To syntax highlight GreasyFork Code by CodeMirror

Verze ze dne 24. 01. 2024. Zobrazit nejnovější verzi.

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by CodeMirror
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.4.1
  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. html .CodeMirror .CodeMirror-activeline-background[class] {
  236. background: inherit;
  237. background-color: #8fd9da17;
  238. }
  239.  
  240. div.code-container .CodeMirror .CodeMirror-lines {
  241. padding: 0;
  242. }
  243.  
  244. div.code-container .CodeMirror {
  245. font-family: monospace;
  246. font-size: 13px;
  247. font-variant-ligatures: contextual;
  248. line-height: 1.15rem;
  249. text-shadow: none !important;
  250. }
  251.  
  252.  
  253. `;
  254.  
  255. const Promise = (async function () { })().constructor;
  256.  
  257. const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
  258.  
  259. const PromiseExternal = ((resolve_, reject_) => {
  260. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  261. return class PromiseExternal extends Promise {
  262. constructor(cb = h) {
  263. super(cb);
  264. if (cb === h) {
  265. /** @type {(value: any) => void} */
  266. this.resolve = resolve_;
  267. /** @type {(reason?: any) => void} */
  268. this.reject = reject_;
  269. }
  270. }
  271. };
  272. })();
  273.  
  274. const pScript = new PromiseExternal();
  275. const pElementQuery = new PromiseExternal();
  276.  
  277. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName;
  278. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName;
  279.  
  280. HTMLElement.prototype.getElementsByTagName = getElementsByTagName;
  281. Document.prototype.getElementsByTagName = getElementsByTagName;
  282.  
  283. let byPass = true;
  284.  
  285. const observablePromise = (proc, timeoutPromise) => {
  286. let promise = null;
  287. return {
  288. obtain() {
  289. if (!promise) {
  290. promise = new Promise(resolve => {
  291. let mo = null;
  292. const f = () => {
  293. let t = proc();
  294. if (t) {
  295. mo.disconnect();
  296. mo.takeRecords();
  297. mo = null;
  298. resolve(t);
  299. }
  300. }
  301. mo = new MutationObserver(f);
  302. mo.observe(document, { subtree: true, childList: true })
  303. f();
  304. timeoutPromise && timeoutPromise.then(() => {
  305. resolve(null)
  306. });
  307. });
  308. }
  309. return promise
  310. }
  311. }
  312. }
  313.  
  314. const documentReady = new Promise(resolve => {
  315. Promise.resolve().then(() => {
  316. if (document.readyState !== 'loading') {
  317. resolve();
  318. } else {
  319. window.addEventListener("DOMContentLoaded", resolve, false);
  320. }
  321. });
  322. });
  323.  
  324. function getElementsByTagName(tag) {
  325. if (byPass) {
  326. if (tag === 'pre' || tag === 'code' || tag === 'xmp') {
  327. if (location.pathname.endsWith('/code')) {
  328. pElementQuery.resolve();
  329. return [];
  330. }
  331. }
  332. }
  333. return this.getElementsByTagName331(tag);
  334. }
  335.  
  336. async function onBodyHeadReadyAsync() {
  337. await observablePromise(() => document.body && document.head).obtain();
  338. }
  339.  
  340.  
  341. // Load CSS
  342. function loadJS(href) {
  343.  
  344. return new Promise(resolve => {
  345.  
  346. const script = document.createElement('script');
  347. script.src = href;
  348. script.onload = () => {
  349. resolve(script);
  350. };
  351. document.head.appendChild(script);
  352.  
  353. });
  354.  
  355. }
  356.  
  357. // Load CSS
  358. function loadCSS(href) {
  359. const link = document.createElement('link');
  360. link.rel = 'stylesheet';
  361. link.href = href;
  362. document.head.appendChild(link);
  363. return link;
  364. }
  365.  
  366.  
  367.  
  368.  
  369.  
  370.  
  371. /** @param {HTMLElement} pre */
  372. async function prepareCodeAreaAsync(pre) {
  373.  
  374. if (pre.isConnected === false) return;
  375.  
  376. for (const li of pre.querySelectorAll('li')) {
  377. li.append(document.createTextNode('\n'));
  378. }
  379.  
  380. const codeElement = document.createElement('code');
  381. // codeElement.classList.add('language-javascript');
  382. codeElement.innerHTML = pre.innerHTML;
  383.  
  384. // Clearing the original code container and appending the new one
  385. // pre.classList = '';
  386. pre.innerHTML = '';
  387. // pre.appendChild(codeElement);
  388.  
  389. // if (pre.querySelector('code')) return;
  390. const code = codeElement;
  391.  
  392. const codeContainer = pre.closest('.code-container');
  393. if (codeContainer && codeContainer.querySelector('.code-container>pre:only-child')) {
  394. // avoid selection to the outside by mouse dragging
  395. codeContainer.setAttribute('contenteditable', '');
  396. codeContainer.querySelector('.code-container>pre:only-child').setAttribute('contenteditable', 'false');
  397. }
  398.  
  399.  
  400. // let parentNode = code.parentNode;
  401. // let nextNode = code.nextSibling;
  402.  
  403. // code.remove();
  404. let parentNode = pre;
  405. let nextNode = null;
  406. await Promise.resolve().then();
  407.  
  408. // preset language
  409. /*
  410. const text = codeElement.textContent;
  411. if(/(^|\n)\s*\/\/\s+==UserScript==\s*\n/.test(text)){
  412. codeElement.classList.add('language-javascript');
  413. }else if(/(^|\n)\s*\/\*\s+==UserStyle==\s*\n/.test(text)){
  414. codeElement.classList.add('language-css');
  415. }
  416. */
  417. let className = '';
  418. if (pre.classList.contains('lang-js')) {
  419. className = 'language-javascript';
  420. } else if (pre.classList.contains('lang-css')) {
  421.  
  422. const text = codeElement.textContent;
  423. let m = /\n@preprocessor\s+([-_a-zA-Z]{3,8})\s*\n/.exec(text);
  424. className = 'language-css'
  425. if (m) {
  426. const preprocessor = m[1];
  427. if (preprocessor === 'stylus') {
  428. className = 'language-stylus';
  429. } else if (preprocessor === 'uso') {
  430. className = 'language-stylus';
  431. } else if (preprocessor === 'less') {
  432. className = 'language-less';
  433. } else if (preprocessor === 'default') {
  434. className = 'language-stylus';
  435. } else {
  436. className = 'language-stylus';
  437. }
  438. }
  439.  
  440.  
  441. }
  442.  
  443.  
  444. if (!className) return;
  445.  
  446. let mode = '';
  447. if (className === 'language-javascript') mode = 'javascript';
  448. if (className === 'language-stylus') mode = 'stylus';
  449. if (className === 'language-less') mode = 'less';
  450. if (className === 'language-css') mode = 'css';
  451.  
  452. if (!mode) return;
  453.  
  454.  
  455.  
  456. let textarea = document.createElement('textarea');
  457. textarea.value = `${code.textContent}`;
  458. textarea.readOnly = true;
  459. textarea.id = 'editor651';
  460.  
  461.  
  462. // textarea.classList.add('code-container')
  463.  
  464. textarea.style.width = '100%';
  465. textarea.style.height = '100vh';
  466.  
  467. parentNode.insertBefore(textarea, nextNode);
  468.  
  469.  
  470. let editor651 = CodeMirror.fromTextArea(document.querySelector('#editor651'), {
  471.  
  472. mode: mode,
  473. theme: document.documentElement.hasAttribute('dark') ? 'material' : '',
  474.  
  475. readOnly: true,
  476. styleActiveLine: true,
  477. lineNumbers: true,
  478. extraKeys: { "Alt-F": "findPersistent" }
  479. });
  480. editor651.save();
  481.  
  482.  
  483.  
  484. }
  485.  
  486. const documentBodyHeadReady = onBodyHeadReadyAsync();
  487.  
  488. documentBodyHeadReady.then(async () => {
  489.  
  490. if (!location.pathname.endsWith('/code')) {
  491. return;
  492. }
  493.  
  494. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd()}`;
  495.  
  496. await loadJS(resoruces['codemirror.min.js']);
  497.  
  498. await Promise.all([
  499. loadJS(resoruces['javascript.min.js']),
  500. loadJS(resoruces['css.min.js']),
  501. loadJS(resoruces['stylus.min.js']),
  502. loadJS(resoruces['active-line.min.js']),
  503. loadJS(resoruces['search.js']),
  504. loadJS(resoruces['searchcursor.js']),
  505. loadJS(resoruces['jump-to-line.js']),
  506. loadJS(resoruces['dialog.js'])
  507. ]);
  508.  
  509. if (document.documentElement.hasAttribute('dark')) {
  510.  
  511. // TBC
  512. loadCSS(resoruces['codemirror.min.css']);
  513. loadCSS(resoruces['dialog.css']);
  514. loadCSS(resoruces['material.css']);
  515.  
  516. } else {
  517.  
  518. loadCSS(resoruces['codemirror.min.css']);
  519. loadCSS(resoruces['dialog.css']);
  520. }
  521.  
  522.  
  523. pScript.resolve();
  524.  
  525.  
  526.  
  527.  
  528. });
  529.  
  530. let keydownActive = false;
  531.  
  532. documentReady.then(async () => {
  533.  
  534. if (!location.pathname.endsWith('/code')) {
  535. byPass = false;
  536. return;
  537. }
  538.  
  539. await pScript.then();
  540.  
  541. await Promise.race([pElementQuery, delayPn(800)]);
  542.  
  543. const targets = document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css');
  544.  
  545. if (targets.length === 0) return;
  546.  
  547. await delayPn(40);
  548.  
  549. document.head.appendChild(document.createElement('style')).textContent = doActionCSS();
  550.  
  551. await delayPn(40);
  552.  
  553. byPass = false;
  554.  
  555. // Code highlighting
  556. const promises = [...targets].map(prepareCodeAreaAsync)
  557. await Promise.all(promises);
  558.  
  559. await delayPn(40);
  560. document.documentElement.setAttribute('dkkfv', '');
  561. keydownActive = true;
  562.  
  563. });
  564.  
  565. function selectAllWithinElement(element) {
  566. window.getSelection().removeAllRanges();
  567. let range = document.createRange();
  568. if (element) {
  569. range.selectNodeContents(element);
  570. window.getSelection().addRange(range);
  571. } else {
  572. console.error('Element not found with ID:', element);
  573. }
  574. }
  575. document.addEventListener('keydown', (e) => {
  576. if (keydownActive && e && e.code === 'KeyA' && e.isTrusted && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
  577.  
  578. const target = e.target;
  579. const container = target ? target.closest('div.code-container') : null;
  580. const code = container ? container.querySelector('code') : null;
  581.  
  582. if (container && code) {
  583.  
  584. e.preventDefault();
  585. e.stopPropagation();
  586. e.stopImmediatePropagation();
  587.  
  588. setTimeout(() => {
  589. selectAllWithinElement(code);
  590. }, 1)
  591.  
  592. }
  593.  
  594. }
  595. }, true);
  596.  
  597.  
  598. const cmLineNumberAppearFn = (evt) => {
  599. const elm = evt.target;
  600. if (!(elm instanceof HTMLElement)) return;
  601.  
  602. elm.setAttribute('marker-text', elm.textContent.trim());
  603. elm.textContent = '';
  604. }
  605.  
  606. document.addEventListener('animationstart', (evt) => {
  607. const animationName = evt.animationName;
  608. if (!animationName) return;
  609. if (animationName === 'cmLineNumberAppear') cmLineNumberAppearFn(evt);
  610. }, { capture: true, passive: true });
  611.  
  612.  
  613. })();