Custom Logo picker for twitter.com

We've got birds! old birds, new birds, even pigeons! new competitors, dead competitors, federated competitors!

  1. // ==UserScript==
  2. // @name Custom Logo picker for twitter.com
  3. // @namespace Itsnotlupus Industries
  4. // @match https://*.twitter.com/*
  5. // @match https://*.x.com/*
  6. // @version 4.1
  7. // @author Itsnotlupus
  8. // @license MIT
  9. // @description We've got birds! old birds, new birds, even pigeons! new competitors, dead competitors, federated competitors!
  10. // @icon https://abs.twimg.com/favicons/twitter.2.ico
  11. // @require https://greatest.deepsurf.us/scripts/468394-itsnotlupus-tiny-utilities/code/utils.js
  12. // @require https://greatest.deepsurf.us/scripts/471000-itsnotlupus-i18n-support/code/i18n.js
  13. // @run-at document-start
  14. // @resource old_twitter_favicon https://i.imgur.com/74OBSr6.png
  15. // @resource old_twitter_favicon_dot https://i.imgur.com/Yr0Gl7L.png
  16. // @resource older_twitter_logo https://i.imgur.com/NTT40TK.png
  17. // @resource older_twitter_favicon https://i.imgur.com/SYEM2RA.png
  18. // @resource older_twitter_favicon_dot https://i.imgur.com/VEnAuI0.png
  19. // @resource pigeon_logo https://i.imgur.com/CUspx8m.gif
  20. // @resource bluesky_logo https://i.imgur.com/fEq4EKr.png
  21. // @resource bluesky_favicon https://i.imgur.com/nCi5pTh.png
  22. // @resource threads_favicon https://i.imgur.com/Bv9o1px.png
  23. // @resource mastodon_favicon https://i.imgur.com/nKmYnXd.png
  24. // @resource parler_favicon https://i.imgur.com/hc5ccuN.png
  25. // @resource truthsocial_logo https://i.imgur.com/glC142w.png
  26. // @resource reddit_favicon https://i.imgur.com/oZcNyNR.png
  27. // @grant GM_setValue
  28. // @grant GM_getValue
  29. // @grant GM_addValueChangeListener
  30. // @grant GM_getResourceURL
  31. // @grant GM_addElement
  32. // @grant GM_xmlhttpRequest
  33. // @grant GM_registerMenuCommand
  34. // ==/UserScript==
  35.  
  36. /* jshint esversion:11 */
  37. /* jshint -W083 */
  38. /* eslint no-return-assign:0, no-loop-func:0 */
  39. /* global i18n, t, $, $$, $$$, observeDOM, untilDOM, sleep, until, crel, memoize, events, fastDebounce */
  40. /* human it's fine, it's fine, I promise. */
  41.  
  42. // utilities
  43. const res = memoize(id => GM_getResourceURL(id)); // ensure we get the same URL for the same id. it helps with stuff.
  44. const fav = memoize(id => GM_getResourceURL(id, false)); // favicons can't be blob: URIs. fine.
  45. const mkNode = html => crel('div', { innerHTML: html}).firstChild;
  46. const cssVars = o => Object.keys(o).forEach(k=>document.documentElement.style.setProperty(k,o[k]));
  47. const testCSSHasSelector = () => { try { $`body:has(*)`; return true } catch { return false } }
  48.  
  49. // Localizable strings
  50. const strings = {
  51. logo_menu_label: "Open/Close Logo Menu",
  52. toggle_branding_changes: "Enable/Disable Brand Changes"
  53. };
  54.  
  55. // Boring Pre-Musk branding.
  56. const brand = { site: 'Twitter', action: 'Tweet', item: 'Tweet', items: 'Tweets', reaction: 'Retweet', reactions: 'Retweets' };
  57. // Commonly found logos
  58. const X_PATH = "M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z";
  59. const BIRD_PATH = "M23.643 4.937c-.835.37-1.732.62-2.675.733.962-.576 1.7-1.49 2.048-2.578-.9.534-1.897.922-2.958 1.13-.85-.904-2.06-1.47-3.4-1.47-2.572 0-4.658 2.086-4.658 4.66 0 .364.042.718.12 1.06-3.873-.195-7.304-2.05-9.602-4.868-.4.69-.63 1.49-.63 2.342 0 1.616.823 3.043 2.072 3.878-.764-.025-1.482-.234-2.11-.583v.06c0 2.257 1.605 4.14 3.737 4.568-.392.106-.803.162-1.227.162-.3 0-.593-.028-.877-.082.593 1.85 2.313 3.198 4.352 3.234-1.595 1.25-3.604 1.995-5.786 1.995-.376 0-.747-.022-1.112-.065 2.062 1.323 4.51 2.093 7.14 2.093 8.57 0 13.255-7.098 13.255-13.254 0-.2-.005-.402-.014-.602.91-.658 1.7-1.477 2.323-2.41z";
  60. // Cheap way to identify uncorrected logos. Twitter currently uses a mix of both of those.
  61. const legacyLogosSelector = [
  62. `svg:not([class*="hidden"]):not([class*="twitter-x"]) path[d="${X_PATH}"]`,
  63. `svg:not([class*="hidden"]):not([class*="twitter-bird"]) path[d="${BIRD_PATH}"]`
  64. ].join();
  65.  
  66. const LOGOS_CUTOFF = 4; // The first 4 logos are or were Twitter logos. The rest, well..
  67. const LOGOS = [
  68. {
  69. // visionary new X logo
  70. label: "𝕏",
  71. brand: { site: "X", action: "eXecrate", item: 'eXecration', items: "eXecrations", reaction: "ReeXecrate", reactions: "ReeXecrations" },
  72. html: `<svg viewBox="0 0 24 24" aria-hidden="true" class="twitter-x"><path d="${X_PATH}"></path></svg>`,
  73. favicon: "https://abs.twimg.com/favicons/twitter.3.ico",
  74. faviconDot: "https://abs.twimg.com/favicons/twitter-pip.3.ico"
  75. },
  76. {
  77. // old twitter bird logo
  78. label: "Twitter",
  79. brand,
  80. html: `<svg viewBox="0 0 24 24" aria-hidden="true" class="twitter-bird"><path d="${BIRD_PATH}"></path></svg>`,
  81. favicon: "https://abs.twimg.com/favicons/twitter.2.ico",
  82. faviconDot: "https://abs.twimg.com/favicons/twitter-pip.2.ico",
  83. },
  84. { // even older twitter bird logo
  85. label: "Old Twitter",
  86. brand,
  87. html: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="twitter-bird" viewBox="0 0 380 380"><defs><linearGradient id="d"><stop offset="0%" stop-color="#157bab"></stop><stop offset="100%" stop-color="#599dd1"></stop></linearGradient><linearGradient xlink:href="#d" id="e" x1="0" x2="0" y1="0" y2="1" gradientTransform="rotate(154 1 1)" gradientUnits="objectBoundingBox"></linearGradient></defs><path d="M180 137c12-38 27-63 44-81 13-13 20-18 12-3l12-8c21-10 20-2 5 7 39-14 38 4-3 13 33 1 70 22 80 68 1 6 0 6 6 7 14 2 27 2 40-2-1 10-14 16-33 20-8 1-9 1 0 3 10 2 22 3 35 2-10 12-26 18-45 18-12 44-40 76-75 96-83 47-203 40-263-45 40 31 98 38 142-6-29 0-36-21-14-32-21-1-35-7-42-20-4-4-4-5 1-8 6-4 13-6 21-6-22-7-36-18-40-34-2-5-2-5 3-6l18-2c-18-11-28-24-31-38-2-14 0-10 10-6 45 17 90 36 117 63z" style="fill:url(#e)"></path></svg>`,
  88. favicon: fav`old_twitter_favicon`,
  89. faviconDot: fav`old_twitter_favicon_dot`
  90. },
  91. { // antediluvian twitter bird logo
  92. label: "Older Twitter",
  93. brand,
  94. html: `<img class="twitter-classic" src="${res`older_twitter_logo`}">`,
  95. logo: res`older_twitter_logo`,
  96. favicon: fav`older_twitter_favicon`,
  97. faviconDot: fav`older_twitter_favicon_dot`
  98. },
  99. // From the shallow end of nostalgia to the deep end.
  100. // Those logos are only shown in the dropdown if you press the `Shift` key while opening it.
  101. // Great care was taken in researching proper branding for each one.
  102. {
  103. label: "Pigeon",
  104. brand: { site: 'Pigeon', action: 'Coo', item: 'Coo', items: 'Coos', reaction: 'Grunt', reactions: 'Grunts' },
  105. html: `<img class="twitter-classic" src="${res`pigeon_logo`}">`,
  106. logo: res`pigeon_logo`,
  107. favicon: fav`pigeon_logo`
  108. },
  109. {
  110. label: "Bluesky",
  111. brand: { site: 'Bluesky', action: 'Skeet', item: 'Skeet', items: 'Skeets', reaction: 'Reskeet', reactions: 'Reskeets' },
  112. html: `<img class="twitter-classic" src="${res`bluesky_logo`}">`,
  113. logo: res`bluesky_logo`,
  114. favicon: fav`bluesky_favicon`
  115. },
  116. {
  117. label: "Threads",
  118. brand: { site: 'Threads', action: 'Post', item: 'Post', items: 'Posts', reaction: 'Repost', reactions: 'Reposts' },
  119. html: `<svg xmlns="http://www.w3.org/2000/svg" class="threads-squiggly" viewBox="0 0 192 192"><path d="m142 89-3-1c-1-27-16-43-41-43h-1c-15 0-27 6-35 18l14 9a24 24 0 0 1 21-10c9 0 15 2 19 7 3 3 5 8 6 14-7-1-15-2-24-1-24 1-39 15-38 34 1 10 5 19 14 24 7 5 16 7 25 6 13 0 23-5 29-14 6-6 9-15 10-26 6 4 11 9 13 14 4 10 4 26-8 39-12 11-25 16-46 16-23 0-40-7-51-22a93 93 0 0 1-16-57c0-25 5-44 16-57 11-15 28-22 51-22s41 7 52 22c6 7 10 16 13 26l16-4c-3-13-9-24-16-33A80 80 0 0 0 97 0C69 0 47 10 33 28 20 44 13 67 13 96s7 52 20 68c14 18 36 28 64 28 25 0 43-7 57-21a50 50 0 0 0-12-82Zm-44 41c-10 0-21-5-21-15-1-7 5-15 22-16a101 101 0 0 1 23 1c-2 25-13 29-24 30Z"></path></svg>`,
  120. favicon: fav`threads_favicon`
  121. },
  122. {
  123. label: "Mastodon",
  124. brand: { site: 'Mastodon', action: 'Toot', item: 'Toot', items: 'Toots', reaction: 'Retoot', reactions: 'Retoots' },
  125. html: `<svg xmlns="http://www.w3.org/2000/svg" class="twitter-bird" viewBox="0 0 75 79"><path fill="url(#a)" d="M74 17C73 9 65 2 57 1L36 0 19 1C11 2 3 8 1 17L0 30l1 19 2 12c2 7 9 13 16 16a43 43 0 0 0 26 0l6-2v-7c-5 2-10 2-15 2-9 0-12-4-12-6a19 19 0 0 1-1-5c5 2 10 2 15 2h4l15-1h1c7-2 15-7 16-19V17Z"></path><path fill="#fff" d="M61 27v21h-8V28c0-5-2-7-6-7s-6 3-6 8v11h-8V29c0-5-2-8-6-8s-5 2-5 7v20h-9V27c0-4 1-8 4-10 2-3 5-4 9-4s7 2 9 5l2 3 2-3c3-3 6-5 10-5s7 1 9 4c2 2 3 6 3 10Z"></path><defs><linearGradient id="a" x1="37.1" x2="37.1" y1="0" y2="79" gradientUnits="userSpaceOnUse"><stop stop-color="#6364FF"></stop><stop offset="1" stop-color="#563ACC"></stop></linearGradient></defs></svg>`,
  126. favicon: fav`mastodon_favicon`
  127. },
  128. {
  129. label: "Parler",
  130. brand: { site: 'Parler', action: 'Twat', item: 'Twat', items: 'Twats', reaction: 'Echo', reactions: 'Echoes' },
  131. html: `<svg xmlns="http://www.w3.org/2000/svg" class="twitter-bird" viewBox="0 0 500 500"><g clip-path="url(#c)"><path fill="url(#b)" d="M200 300v-50h100a50 50 0 0 0 0-100H0C0 67 67 0 150 0h150a200 200 0 1 1 0 400c-55 0-100-45-100-100Zm-50 50V200C67 200 0 267 0 350v150c83 0 150-67 150-150Z"></path></g><defs><linearGradient id="b" x1="0" x2="500" y1="0" y2="500" gradientUnits="userSpaceOnUse"><stop stop-color="#892E5E"></stop><stop offset="1" stop-color="#E90039"></stop></linearGradient><clipPath id="c"><path fill="#fff" d="M0 0h1646v500H0z"></path></clipPath></defs></svg>`,
  132. favicon: fav`parler_favicon`,
  133. dot: "#77f"
  134. },
  135. {
  136. label: "Truth Social",
  137. brand: { site: 'Truth Social', action: 'Truth', item: 'Truth', items: 'Truths', reaction: 'ReTruth', reactions: 'ReTruths' },
  138. html: `<img class="twitter-classic" src="${res`truthsocial_logo`}">`,
  139. logo: res`truthsocial_logo`,
  140. favicon: fav`truthsocial_logo`
  141. },
  142. {
  143. label: "Reddit",
  144. brand: { site: 'Reddit', action: 'Spez', item: 'Spez', items: 'Spezz', reaction: 'Respez', reactions: 'Respezz' },
  145. html: `<svg class="twitter-bird" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 810 810"><circle cx="406.6" cy="405.6" r="402.3" fill="#ff4500"></circle><path d="M675 406a59 59 0 0 0-99-41c-46-31-100-48-155-49l26-126 86 18a40 40 0 1 0 5-24l-98-20c-7-1-14 3-15 10l-30 139c-56 1-111 18-157 50a59 59 0 1 0-65 96v18c0 90 105 163 235 163s234-73 234-163v-18c21-10 33-31 33-53zm-402 40a40 40 0 0 1 80 0 40 40 0 0 1-80 0zm233 111c-28 21-63 32-99 31-36 1-71-10-100-31-3-5-3-12 2-16 4-3 10-3 14 0 24 18 54 27 84 26 30 1 59-7 84-25 4-4 11-4 16 0s4 12-1 16v-1zm-7-69a40 40 0 0 1 0-81c22 0 40 18 40 40 1 23-16 41-38 42h-2v-1z" fill="#fff"></path></svg>`,
  146. favicon: fav`reddit_favicon`,
  147. dot: "#77f"
  148. }
  149. ];
  150.  
  151. const MY_CSS = `
  152. header[role="banner"] h1[role="heading"] {
  153. flex-direction: row;
  154. }
  155. header[role="banner"] h1[role="heading"]:hover .logo-dropdown-arrow,
  156. header[role="banner"] h1[role="heading"] a:active + .logo-dropdown-arrow,
  157. body.logo-dropdown-open .logo-dropdown-arrow {
  158. opacity: 1;
  159. }
  160. .logo-dropdown-anchor {
  161. height: initial !important;
  162. }
  163. .logo-dropdown-arrow {
  164. opacity: 0;
  165. transition: all 250ms;
  166. width: 20px;
  167. height: 20px;
  168. line-height: 22px;
  169. margin-right: -20px;
  170. text-align: center;
  171. color: var(--twitter-icon-color);
  172. border-radius: 9px;
  173. background: var(--twitter-bg-color);
  174. }
  175. .logo-dropdown-arrow:hover {
  176. background: var(--icon-hover-bg);
  177. }
  178. .logo-dropdown-backdrop {
  179. position: fixed;
  180. inset: 0;
  181. background: rgba(0,0,0,0);
  182. }
  183. .logo-dropdown {
  184. position: fixed;
  185. width: 3rem;
  186. background: var(--twitter-bg-color);
  187. padding: 0.5em;
  188. border-radius: 5px;
  189. box-shadow: var(--dropdown-box-1) 0px 0px 15px, var(--dropdown-box-2) 0px 0px 3px 1px;
  190. }
  191. .logo-dropdown-item {
  192. cursor: pointer;
  193. height: 2rem;
  194. margin-top: 0.5em;
  195. margin-bottom: 0.5em;
  196. padding: 8px;
  197. transition: all 250ms;
  198. border-radius: 999px;
  199. }
  200. .logo-dropdown-item:hover, .logo-dropdown-item:focus {
  201. background: var(--icon-hover-bg);
  202. }
  203.  
  204. /* custom CSS for each logo */
  205. .twitter-x {
  206. height: 2rem;
  207. -ms-flex-positive: 1;
  208. -webkit-box-flex: 1;
  209. -webkit-flex-grow: 1;
  210. flex-grow: 1;
  211. color: var(--twitter-icon-color);
  212. -moz-user-select: none;
  213. -ms-user-select: none;
  214. -webkit-user-select: none;
  215. user-select: none;
  216. vertical-align: text-bottom;
  217. position: relative;
  218. max-width: 100%;
  219. fill: currentcolor;
  220. display: inline-block;
  221. }
  222.  
  223. /* can probably be used with any SVG logo */
  224. .twitter-bird {
  225. height: 2rem;
  226. color: rgba(29,155,240,1.00) !important;
  227. vertical-align: text-bottom;
  228. position: relative;
  229. max-width: 100%;
  230. fill: currentcolor;
  231. -moz-user-select: none;
  232. -ms-user-select: none;
  233. -webkit-user-select: none;
  234. user-select: none;
  235. display: inline-block;
  236. pointer-events: none;
  237. }
  238.  
  239. /* can probably be used with any bitmap logo */
  240. .twitter-classic {
  241. max-width: 2rem;
  242. vertical-align: text-bottom;
  243. position: relative;
  244. -moz-user-select: none;
  245. -ms-user-select: none;
  246. -webkit-user-select: none;
  247. user-select: none;
  248. display: inline-block;
  249. pointer-events: none;
  250. }
  251.  
  252. .threads-squiggly {
  253. height: 2rem;
  254. fill: var(--twitter-icon-color);
  255. }
  256.  
  257. .hidden {
  258. display: none !important;
  259. }
  260. `;
  261.  
  262. class CustomLogoPicker {
  263. // Which logo is currently shown
  264. logo = {};
  265. // Whether silly branding should be shown
  266. branding = true;
  267. // A flag to pick a faster path where possible
  268. canUseHasSelector = testCSSHasSelector(); // :has() selector. useful, but not super well supported yet.
  269.  
  270. constructor() {
  271.  
  272. this.initI18N();
  273.  
  274. this.applyState();
  275. this.applyFavicon();
  276. this.applyLogo();
  277.  
  278. // insert styles. because this runs very early, document.head may be null.
  279. untilDOM("head").then(head=> head.prepend(crel('style', { textContent: MY_CSS })));
  280.  
  281. // setup event listeners
  282. GM_addValueChangeListener("logo", this.stateChangeListener);
  283. GM_addValueChangeListener("branding", this.stateChangeListener);
  284. observeDOM(fastDebounce(this.DOMChangeListener));
  285. events({ keypress: this.keyPressListener });
  286.  
  287. // start our threads
  288. this.runThemeWatcher();
  289. this.runDesktopDropdownWatcher();
  290. this.runMobileDropdownWatcher();
  291. this.runKeyboardShortcutDialogWatcher();
  292. }
  293.  
  294. async initI18N() {
  295. await i18n.init({ strings });
  296. GM_registerMenuCommand(t`toggle_branding_changes`, () => {
  297. GM_setValue('branding', !GM_getValue("branding", true));
  298. this.DOMChangeListener();
  299. });
  300. }
  301.  
  302. applyState() {
  303. const logoLabel = GM_getValue("logo")?.label ?? "Twitter";
  304. const l = LOGOS.find(logo => logo.label === logoLabel) ?? LOGOS[1];
  305. this.branding = GM_getValue("branding", true);
  306. this.applyBrand(this.logo.brand ?? brand, l.brand ?? brand);
  307. this.logo = l;
  308. }
  309.  
  310. async applyFavicon () {
  311. const hasNotification = document.title[0] == "(";
  312. let icon = this.logo.favicon;
  313. if (hasNotification) {
  314. if (!this.logo.faviconDot) {
  315. // slap a dot on the favicon
  316. const img = await new Promise(r => crel('img', { src: icon, onload: e=>r(e.target) }));
  317. const { width, height } = img;
  318. const canvas = crel('canvas', { width, height });
  319. const ctx = canvas.getContext("2d");
  320. ctx.drawImage(img, 0, 0);
  321. ctx.fillStyle = this.logo.dot ?? "red";
  322. ctx.arc(width*3/4, height/4, width/5, 0, Math.PI*2);
  323. ctx.fill();
  324. this.logo.faviconDot = canvas.toDataURL();
  325. }
  326. icon = this.logo.faviconDot;
  327. }
  328. $$`link[rel="shortcut icon"],link[rel="icon"]`.forEach(link => {
  329. if (link.href !== icon) link.href = icon;
  330. });
  331. }
  332.  
  333. applyLogo() {
  334. if (!this.logo.html) return;
  335. // initial sweep of legacy logos
  336. $$(legacyLogosSelector).forEach(path=> {
  337. const svg = path.closest`svg`;
  338. this.replaceLegacyLogo(svg, svg.getAttribute("class") ?? '');
  339. });
  340. // further updates of legacy logos when user picks another logo
  341. $$`.legacy-logo`.forEach(l => {
  342. if (l.outerHTML.replace(/ (data-class|class|style|id)=".*?"/g,'') !== this.logo.html.replace(/ (class|style|id)=".*?"/g,'')) {
  343. this.replaceLegacyLogo(l, l.dataset.class);
  344. }
  345. });
  346. // special case primary logos on various other twitter pages
  347. const l = ($`.twtr-grid [aria-label$=" home"]` ?? $`.logo-title .logo` ?? $`[class$="_twitter-logo"]`)?.firstElementChild;
  348. if (l && !l.classList.contains('hidden') && l.outerHTML !== this.logo.html) {
  349. l.classList.add('hidden');
  350. if (this.logo.logo) {
  351. l.after(GM_addElement('img', { class: 'twitter-classic legacy-logo', src: this.logo.logo }))
  352. } else {
  353. const logoElt = mkNode(this.logo.html);
  354. logoElt.classList.add("legacy-logo");
  355. l.after(logoElt);
  356. }
  357. }
  358. // on Mobile, logos can disappear, and we need to keep up.
  359. $$`.legacy-logo`.forEach(l => {
  360. const previous = l.previousElementSibling;
  361. if (!previous || !previous.classList.contains("hidden")) {
  362. l.remove();
  363. }
  364. });
  365. }
  366.  
  367. applyBrand(from, to) {
  368. // the silly branding variants only make sense in English, don't butcher other languages.
  369. const isEnglish = /^en([-_].*)?$/i.test(document.documentElement.lang);
  370. if (!this.branding) {
  371. // force default brand instead of our silly variants
  372. to = brand;
  373. }
  374. // nothing more confusing than a logo that doesn't match its copy. let's help!
  375. if (!to) return;
  376.  
  377. // avoid querying the DOM separately for each word. tweak things to find and replace all words in one shot.
  378. const dict = { X: to.site, Post: to.action, Repost: to.reaction }; // X shenanigans to keep up with Elon's evolving non-sense.
  379.  
  380. (isEnglish?["site","reactions","reaction","items","item","action"]:["site"]).forEach(key => {
  381. const word = from[key], betterWord = to[key];
  382. if (!word || !betterWord || word == betterWord) return;
  383. dict[word] = betterWord;
  384. });
  385. const keys = Object.keys(dict);
  386. if (keys.length==0) return;
  387. const regexp = new RegExp('\\b'+keys.join('\\b|\\b')+'\\b','g');
  388.  
  389. // non-trivial Xpath evaluations are slow. matching CSS selectors, even with additional JS filters are often much faster.
  390. (this.canUseHasSelector
  391. ? [...$$`:is(div,span,title,a,b,button,h1,h2,p):not(:has(> *))`]
  392. .filter(e=>!e.closest`article[data-testid="tweet"],div[data-testid^="User"]`)
  393. : [...$$`div,span,title,a,b,button,h1,h2,p`]
  394. .filter(e=>!e.childElementCount && !e.closest`article[data-testid="tweet"],div[data-testid^="User"]`)
  395. )
  396. .filter(e => e.textContent.match(regexp))
  397. .forEach(elt => this.replaceBrandWord(elt, regexp, dict));
  398. $$$(`//span[text()="${keys.join('" or text()="')}"]`)
  399. .filter(e => !e.closest`[data-testid="tweetText"`)
  400. .forEach(elt => this.replaceBrandWord(elt, regexp, dict));
  401. $$(`[placeholder*="${keys.join('"],[placeholder*="')}"]`)
  402. .forEach(elt => {
  403. const newText = elt.placeholder.replace(regexp, w => dict[w]);
  404. if (elt.placeholder !== newText) elt.placeholder = newText;
  405. });
  406. }
  407.  
  408. /** utility method to traverse a DOM subtree, look for text node matching a regexp, and replace matches with a dictionary */
  409. replaceBrandWord(elt, regexp, dict) {
  410. // update text without damaging the DOM tree.
  411. if (elt.childNodes.length>0) {
  412. elt.childNodes.forEach(e => this.replaceBrandWord(e, regexp, dict));
  413. } else {
  414. const newText = elt.textContent.replace(regexp, w => dict[w]);
  415. if (elt.textContent !== newText) elt.textContent = newText;
  416. }
  417. }
  418.  
  419. /** utility method to replace a logo with the currently chosen logo (and carry some classes on the replacement logo) */
  420. replaceLegacyLogo(oldLogo, classes) {
  421. const logoElt = this.logo.logo ? GM_addElement('img', { class: 'twitter-classic', src: this.logo.logo }) : mkNode(this.logo.html);
  422. if (oldLogo.classList.contains("legacy-logo")) {
  423. // it's one of ours, safe to blow up
  424. oldLogo.replaceWith(logoElt);
  425. } else {
  426. // this may be a React node. hide but don't destroy.
  427. oldLogo.classList.add('hidden');
  428. oldLogo.after(logoElt);
  429. }
  430. logoElt.dataset.class = classes;
  431. logoElt.setAttribute('class', logoElt.getAttribute('class') + ' ' + classes + ' legacy-logo');
  432. logoElt.setAttribute('style', "max-height: initial;max-width:999px;padding: 0 10px");
  433. }
  434.  
  435. /** show the logo dropdown anchored to the logo, in front of an invisible backdrop (to catch clicks), and hook pointer, key and focus events */
  436. openLogoDropDown(full, focus) {
  437. if (!$`.logo-dropdown-anchor`) return;
  438. let index = LOGOS.findIndex(l => this.logo.label === l.label);
  439. if (index==-1) index = 0;
  440. if (index >= LOGOS_CUTOFF) full = true;
  441. const disconnect = observeDOM(() => {
  442. const { bottom, left } = $`.logo-dropdown-anchor`.getBoundingClientRect();
  443. const dropdown = $`.logo-dropdown`;
  444. if (dropdown.style.top !== `${bottom}px`) dropdown.style.top = `${bottom}px`;
  445. if (dropdown.style.left !== `${left}px`) dropdown.style.left = `${left}px`;
  446. });
  447. const cleanupEventListener = events({
  448. keydown(e) {
  449. const a = document.activeElement, active = a.parentElement == dropdown ? a : dropdown.childNodes[index];
  450. switch (e.code) {
  451. case 'Escape': backdrop.parentElement && backdrop.click(); e.preventDefault(); break;
  452. case 'ArrowUp': active.previousSibling?.focus(); e.preventDefault(); break;
  453. case 'ArrowDown': active.nextSibling?.focus(); e.preventDefault(); break;
  454. }
  455. }
  456. });
  457. const backdrop = crel('div', {
  458. className: "logo-dropdown-backdrop",
  459. ariaHaspopup: "true",
  460. ariaControls: "menu",
  461. onclick() {
  462. disconnect();
  463. backdrop.remove();
  464. dropdown.remove();
  465. document.body.classList.remove('logo-dropdown-open');
  466. cleanupEventListener();
  467. }
  468. });
  469. const dropdown = crel('div', {
  470. className: "logo-dropdown",
  471. role: "menu",
  472. ariaLabel: 'Logo Picker',
  473. tabIndex: "-1",
  474. }, ...LOGOS.slice(0,full?void 0:LOGOS_CUTOFF).map(l => crel('div', {
  475. className: 'logo-dropdown-item',
  476. role: "menuitem",
  477. ariaLabel: l.label,
  478. title: l.label,
  479. tabIndex: "0",
  480. onclick() {
  481. backdrop.click();
  482. },
  483. onfocus: () => {
  484. this.applyBrand(this.logo.brand ?? brand, l.brand ?? brand);
  485. this.logo = l;
  486. GM_setValue("logo", {label: this.logo.label}); // don't store more than needed.
  487. },
  488. onkeypress(e) {
  489. if (e.code == "Enter" || e.code =="Space") {
  490. e.target.click();
  491. e.preventDefault();
  492. }
  493. }
  494. }, l.logo ? GM_addElement('img', { class: "twitter-classic", src: l.logo}): mkNode(l.html))));
  495. document.body.append(backdrop, dropdown);
  496. document.body.classList.add('logo-dropdown-open');
  497. if (focus) dropdown.childNodes[index].focus();
  498. }
  499.  
  500. // # Event Listeners
  501.  
  502. /** this fires where stored userscript data has changed (ie the logo or some settings have changed from another tab) */
  503. stateChangeListener = () => {
  504. this.applyState();
  505. this.DOMChangeListener();
  506. };
  507.  
  508. /** this fires where the DOM has changed. it is also called manually in places where an update is needed. */
  509. DOMChangeListener = () => {
  510. this.applyFavicon();
  511. this.applyLogo();
  512. this.applyBrand(brand, this.logo.brand);
  513. };
  514.  
  515. /** this fires when a key is pressed. this is used to react to the "Q" key being pressed. */
  516. keyPressListener = e => {
  517. const a = document.activeElement;
  518. if (a.contentEditable == 'true' || a.tagName == 'INPUT' || a.tagName == 'TEXTAREA') return;
  519. if (e.code == 'KeyQ') {
  520. if ($`.logo-dropdown`) {
  521. $`.logo-dropdown-backdrop`?.click();
  522. } else {
  523. this.openLogoDropDown(e.shiftKey, true);
  524. }
  525. }
  526. };
  527.  
  528. // # Threads - methods that never return, typically watching and reacting to some changes.
  529.  
  530. /** detect a theme change (Twitter's white/dim/black, or even extensions like Dark Reader messing with it.) */
  531. async runThemeWatcher() {
  532. const bodyStyles = getComputedStyle(await until('body'));
  533. while (true) {
  534. var bgColor = await until((bg = bodyStyles.backgroundColor) => bg !== bgColor && bg);
  535. const isDarkMode = bgColor.replace(/[rgba( )]+/g,'').split(',').reduce((v,a)=>+a+v, 0) < 255;
  536. cssVars({
  537. "--twitter-bg-color": bgColor,
  538. "--twitter-icon-color": isDarkMode ? "#d6d9db" : "#242e36",
  539. "--icon-hover-bg": isDarkMode ? "rgba(239, 243, 244, 0.1)" : "rgba(15, 20, 25, 0.1)",
  540. "--dropdown-bg-color": isDarkMode ? "#111" : "#fff",
  541. "--dropdown-box-1": isDarkMode ? "rgba(255, 255, 255, 0.2)" : "rgba(101, 119, 134, 0.2)",
  542. "--dropdown-box-2": isDarkMode ? "rgba(255, 255, 255, 0.15)" : "rgba(101, 119, 134, 0.15)"
  543. })
  544. }
  545. }
  546.  
  547. /** install a dropdown arrow next to the logo and hook some events */
  548. async runDesktopDropdownWatcher() {
  549. while (true) {
  550. const heading = await untilDOM(`header[role="banner"] h1[role="heading"]`);
  551. heading.append(crel('a', {
  552. className: "logo-dropdown-arrow logo-dropdown-anchor",
  553. textContent: '▾',
  554. onclick: e => this.openLogoDropDown(e.shiftKey)
  555. }));
  556. const logo = heading.firstChild;
  557. const cleanupEventListener = events({
  558. keypress: e => {
  559. if (e.code == 'Space' || e.code == 'Enter') {
  560. this.openLogoDropDown(e.shiftKey, true);
  561. e.preventDefault();
  562. }
  563. }
  564. }, logo);
  565.  
  566. logo.tabIndex = "0";
  567. // wait until our dropdown gets wiped by React, and reapply our tweaks
  568. await untilDOM(()=>!$`.logo-dropdown-anchor`);
  569. cleanupEventListener();
  570. }
  571. }
  572.  
  573. /** hook single tap and long press events on the mobile logo to show our dropdown */
  574. async runMobileDropdownWatcher() {
  575. while (true) {
  576. const logo = await untilDOM(() => $`[data-testid="TopNavBar"] :not([role="button"]) > div > svg`?.parentElement);
  577. logo.classList.add("logo-dropdown-anchor");
  578. let longPressTimer;
  579. const cleanupEventListeners = events({
  580. touchstart: () => {
  581. longPressTimer = setTimeout(() => this.openLogoDropDown(true), 500);
  582. },
  583. touchend(e) {
  584. clearTimeout(longPressTimer);
  585. if ($`.logo-dropdown`) {
  586. e.preventDefault();
  587. e.stopPropagation();
  588. }
  589. },
  590. click: e => {
  591. this.openLogoDropDown()
  592. e.stopImmediatePropagation();
  593. },
  594. contextmenu(e) { e.preventDefault() }
  595. }, logo);
  596. // wait until React wipes us out to reapply our tweaks
  597. await untilDOM(()=>!$`.logo-dropdown-anchor`);
  598. // `logo` isn't our node, clean up.
  599. cleanupEventListeners();
  600. }
  601. }
  602.  
  603. /** wait for the Keyboard Shortcut list to show up, and inject our shortcut in it. */
  604. async runKeyboardShortcutDialogWatcher() {
  605. while (true) {
  606. // wait until something we see that has the shape of a keyboard shortcut modal, and grab the last "Actions" shortcut from it.
  607. // this unwiedly selector looks for the spot we want in desktop mode first, then in mobile device mode.
  608. const lastActionsRow = await untilDOM(`
  609. #layers [role="dialog"][aria-labelledby] [data-viewportview]>div:last-child>div:nth-child(2) [role="row"]:last-child,
  610. main[role="main"] div>div>div:last-child>div:nth-child(2) [role="row"]:last-child`);
  611. const label = lastActionsRow.innerText.split('\n')[0];
  612. if (label == t`logo_menu_label`) { // we already have our shortcut label shown. chill.
  613. await sleep(500);
  614. continue;
  615. }
  616. // clone, customize and insert our own action shortcut.
  617. const newRow = lastActionsRow.cloneNode(true);
  618. $('span', newRow).textContent = t`logo_menu_label`;
  619. $('[role="cell"]>div', newRow).textContent = 'q';
  620. lastActionsRow.after(newRow);
  621. }
  622. }
  623. }
  624.  
  625. const main = new CustomLogoPicker();