// ==UserScript== // @name GitHub Monospace Font Toggle // @version 1.1.0 // @description A userscript that adds monospace font toggle to comments // @license https://creativecommons.org/licenses/by-sa/4.0/ // @namespace https://github.com/StylishThemes // @include https://github.com/* // @grant GM_addStyle // @run-at document-end // @author StylishThemes // @downloadURL none // ==/UserScript== /* global GM_addStyle */ /* jshint esnext:true, unused:true */ (function() { "use strict"; /* This code is also part of the GitHub-Dark Script (https://github.com/StylishThemes/GitHub-Dark-Script) Extracted out into a separate userscript in case users only want to add this functionality */ let busy = false; const icon = ` `; // Add monospace font toggle function addMonospaceToggle() { busy = true; const button = document.createElement("button"); button.type = "button"; button.className = "ghd-monospace toolbar-item tooltipped tooltipped-n"; button.setAttribute("aria-label", "Toggle monospaced font"); button.setAttribute("tabindex", "-1"); button.innerHTML = icon; Array.from( document.querySelectorAll(".toolbar-commenting") ).forEach(el => { if (el && !el.querySelector(".ghd-monospace")) { el.insertBefore(button.cloneNode(true), el.childNodes[0]); } }); busy = false; } function closest(el, selector) { while (el && el.nodeName !== "BODY" && !el.matches(selector)) { el = el.parentNode; } return el && el.matches(selector) ? el : []; } function addBindings() { document.querySelector("body").addEventListener("click", function(event) { var textarea, active, target = event.target; if (target && target.classList.contains("ghd-monospace")) { textarea = closest(target, ".previewable-comment-form"); textarea = textarea.querySelector(".comment-form-textarea"); textarea.classList.toggle("ghd-monospace-font"); textarea.focus(); active = textarea.classList.contains("ghd-monospace-font"); target.classList[active ? "add" : "remove"]("text-blue"); return false; } }); } // don't initialize if GitHub Dark Script is active if (!document.querySelector("#ghd-menu")) { // monospace font toggle GM_addStyle(` .ghd-monospace-font { font-family: Menlo, Inconsolata, "Droid Mono", monospace !important; font-size: 1em !important; } .ghd-monospace > svg { pointer-events: none; } `); Array.from( document.querySelectorAll(` #js-repo-pjax-container, #js-pjax-container, .js-preview-body `) ).forEach(target => { new MutationObserver(mutations => { mutations.forEach(mutation => { if (!busy && mutation.target === target) { addMonospaceToggle(); } }); }).observe(target, { childList: true, subtree: true }); }); addBindings(); addMonospaceToggle(); } })();