Custom Logo picker for twitter.com

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

当前为 2023-07-31 提交的版本,查看 最新版本

  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 3.0.3
  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://greasyfork.org/scripts/468394-itsnotlupus-tiny-utilities/code/utils.js
  12. // @require https://greasyfork.org/scripts/471000-itsnotlupus-i18n-support/code/i18n.js
  13. // @run-at document-start
  14. // @noframes
  15. // @resource old_twitter_favicon https://i.imgur.com/74OBSr6.png
  16. // @resource old_twitter_favicon_dot https://i.imgur.com/Yr0Gl7L.png
  17. // @resource older_twitter_logo https://i.imgur.com/NTT40TK.png
  18. // @resource older_twitter_favicon https://i.imgur.com/SYEM2RA.png
  19. // @resource older_twitter_favicon_dot https://i.imgur.com/VEnAuI0.png
  20. // @resource pigeon_logo https://i.imgur.com/CUspx8m.gif
  21. // @resource bluesky_logo https://i.imgur.com/fEq4EKr.png
  22. // @resource bluesky_favicon https://i.imgur.com/nCi5pTh.png
  23. // @resource threads_favicon https://i.imgur.com/Bv9o1px.png
  24. // @resource mastodon_favicon https://i.imgur.com/nKmYnXd.png
  25. // @resource parler_favicon https://i.imgur.com/hc5ccuN.png
  26. // @resource truthsocial_logo https://i.imgur.com/glC142w.png
  27. // @resource reddit_favicon https://i.imgur.com/oZcNyNR.png
  28. // @grant GM_setValue
  29. // @grant GM_getValue
  30. // @grant GM_addValueChangeListener
  31. // @grant GM_getResourceURL
  32. // @grant GM_addElement
  33. // @grant GM_xmlhttpRequest
  34. // @grant GM_registerMenuCommand
  35. // ==/UserScript==
  36. /* jshint esversion:11 */
  37. /* eslint no-return-assign:0, no-loop-func:0 */
  38. /* global i18n, t, $, $$, $$$, observeDOM, untilDOM, sleep, until, crel, memoize, events */
  39.  
  40. // Localizable strings
  41. const strings = {
  42. logo_menu_label: "Open/Close Logo Menu",
  43. toggle_branding_changes: "Enable/Disable Brand Changes"
  44. };
  45.  
  46. i18n.init({ strings }).then(() => {
  47. GM_registerMenuCommand(t`toggle_branding_changes`, () =>{
  48. GM_setValue('branding', !GM_getValue("branding", true));
  49. // emit a DOM mutation to trigger our observers and update everything.
  50. document.body.classList.toggle('logoChanged');
  51. })
  52. });
  53.  
  54. // Boring Pre-Musk branding.
  55. const brand = { site: 'Twitter', action: 'Tweet', actions: 'Tweets', reaction: 'Retweet', reactions: 'Retweets' };
  56. // Commonly found logos
  57. 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";
  58. 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";
  59. // Cheap way to identify uncorrected logos. Twitter currently uses a mix of both of those.
  60. const legacyLogosSelector = [
  61. `svg:not([class*="hidden"]) path[d="${X_PATH}"]`,
  62. `svg:not([class*="hidden"]) path[d="${BIRD_PATH}"]`
  63. ].join();
  64.  
  65. const res = memoize(id => GM_getResourceURL(id)); // ensure we get the same URL for the same id. it helps with stuff.
  66. const fav = memoize(id => GM_getResourceURL(id, false)); // favicons can't be blob: URIs. fine.
  67.  
  68. const LOGOS_CUTOFF = 4; // The first 4 logos are or were Twitter logos. The rest, well..
  69. const LOGOS = [
  70. {
  71. // visionary new X logo
  72. label: "𝕏",
  73. brand: { site: "X\u200b", action: "eXecrate", actions: "eXecrations", reaction: "ReeXecrate", reactions: "ReeXecrations" },
  74. html: `<svg viewBox="0 0 24 24" aria-hidden="true" class="twitter-x"><g><path d=" ${X_PATH}"></path></g></svg>`,
  75. favicon: "https://abs.twimg.com/favicons/twitter.3.ico",
  76. faviconDot: "https://abs.twimg.com/favicons/twitter-pip.3.ico"
  77. },
  78. {
  79. // old twitter bird logo
  80. label: "Twitter",
  81. brand,
  82. html: `<svg viewBox="0 0 24 24" aria-hidden="true" class="twitter-bird"><g><path d=" ${BIRD_PATH}"></path></g></svg>`,
  83. favicon: "https://abs.twimg.com/favicons/twitter.2.ico",
  84. faviconDot: "https://abs.twimg.com/favicons/twitter-pip.2.ico",
  85. },
  86. { // even older twitter bird logo
  87. label: "Old Twitter",
  88. brand,
  89. 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>`,
  90. favicon: fav`old_twitter_favicon`,
  91. faviconDot: fav`old_twitter_favicon_dot`
  92. },
  93. { // antediluvian twitter bird logo
  94. label: "Older Twitter",
  95. brand,
  96. html: `<img class="twitter-classic" src="${res`older_twitter_logo`}">`,
  97. logo: res`older_twitter_logo`,
  98. favicon: fav`older_twitter_favicon`,
  99. faviconDot: fav`older_twitter_favicon_dot`
  100. },
  101. // From the shallow end of nostalgia to the deep end.
  102. // Those logos are only shown in the dropdown if you press the `Shift` key while opening it.
  103. // Great care was taken in researching proper branding for each one.
  104. {
  105. label: "Pigeon",
  106. brand: { site: 'Pigeon', action: 'Coo', actions: 'Coos', reaction: 'Grunt', reactions: 'Grunts' },
  107. html: `<img class="twitter-classic" src="${res`pigeon_logo`}">`,
  108. logo: res`pigeon_logo`,
  109. favicon: fav`pigeon_logo`
  110. },
  111. {
  112. label: "Bluesky",
  113. brand: { site: 'Bluesky', action: 'Skeet', actions: 'Skeets', reaction: 'Reskeet', reactions: 'Reskeets' },
  114. html: `<img class="twitter-classic" src="${res`bluesky_logo`}">`,
  115. logo: res`bluesky_logo`,
  116. favicon: fav`bluesky_favicon`
  117. },
  118. {
  119. label: "Threads",
  120. brand: { site: 'Threads', action: 'Post', actions: 'Posts', reaction: 'Repost', reactions: 'Reposts' },
  121. 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>`,
  122. favicon: fav`threads_favicon`
  123. },
  124. {
  125. label: "Mastodon",
  126. brand: { site: 'Mastodon', action: 'Toot', actions: 'Toots', reaction: 'Retoot', reactions: 'Retoots' },
  127. 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>`,
  128. favicon: fav`mastodon_favicon`
  129. },
  130. {
  131. label: "Parler",
  132. brand: { site: 'Parler', action: 'Twat', actions: 'Twats', reaction: 'Echo', reactions: 'Echoes' },
  133. 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>`,
  134. favicon: fav`parler_favicon`,
  135. dot: "#77f"
  136. },
  137. {
  138. label: "Truth Social",
  139. brand: { site: 'Truth Social', action: 'Truth', actions: 'Truths', reaction: 'ReTruth', reactions: 'ReTruths' },
  140. html: `<img class="twitter-classic" src="${res`truthsocial_logo`}">`,
  141. logo: res`truthsocial_logo`,
  142. favicon: fav`truthsocial_logo`
  143. },
  144. {
  145. label: "Reddit",
  146. brand: { site: 'Reddit', action: 'Spez', actions: 'Spezz', reaction: 'Respez', reactions: 'Respezz' },
  147. 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>`,
  148. favicon: fav`reddit_favicon`,
  149. dot: "#77f"
  150. }
  151. ];
  152.  
  153. // state management and backward compatibility sanity
  154. let logo = {};
  155. let branding = true;
  156. function applyState() {
  157. const logoLabel = GM_getValue("logo", { label: "Twitter"}).label ?? "Twitter";
  158. const l = LOGOS.find(logo => logo.label === logoLabel) ?? LOGOS[1];
  159. branding = GM_getValue("branding", true);
  160. applyBrand(logo.brand ?? brand, l.brand ?? brand);
  161. logo = l;
  162. }
  163. function stateChangeListener() {
  164. applyState();
  165. // emit a DOM mutation to trigger our observers and update everything.
  166. document.body.classList.toggle('logoChanged');
  167. }
  168. GM_addValueChangeListener("logo", stateChangeListener);
  169. GM_addValueChangeListener("branding", stateChangeListener);
  170. applyState();
  171.  
  172. // styles.
  173. untilDOM("head").then(head=>head.prepend(crel('style', { textContent: `
  174. header[role="banner"] h1[role="heading"] {
  175. flex-direction: row;
  176. }
  177. header[role="banner"] h1[role="heading"]:hover .logo-dropdown-arrow,
  178. header[role="banner"] h1[role="heading"] a:active + .logo-dropdown-arrow,
  179. body.logo-dropdown-open .logo-dropdown-arrow {
  180. opacity: 1;
  181. }
  182. .logo-dropdown-anchor {
  183. height: initial !important;
  184. }
  185. .logo-dropdown-arrow {
  186. opacity: 0;
  187. transition: all 250ms;
  188. width: 20px;
  189. height: 20px;
  190. line-height: 22px;
  191. margin-right: -20px;
  192. text-align: center;
  193. color: var(--twitter-icon-color);
  194. border-radius: 9px;
  195. background: var(--twitter-bg-color);
  196. }
  197. .logo-dropdown-arrow:hover {
  198. background: var(--icon-hover-bg);
  199. }
  200. .logo-dropdown-backdrop {
  201. position: fixed;
  202. inset: 0;
  203. background: rgba(0,0,0,0);
  204. }
  205. .logo-dropdown {
  206. position: fixed;
  207. width: 3rem;
  208. background: var(--twitter-bg-color);
  209. padding: 0.5em;
  210. border-radius: 5px;
  211. box-shadow: var(--dropdown-box-1) 0px 0px 15px, var(--dropdown-box-2) 0px 0px 3px 1px;
  212. }
  213. .logo-dropdown-item {
  214. cursor: pointer;
  215. height: 2rem;
  216. margin-top: 0.5em;
  217. margin-bottom: 0.5em;
  218. padding: 8px;
  219. transition: all 250ms;
  220. border-radius: 999px;
  221. }
  222. .logo-dropdown-item:hover, .logo-dropdown-item:focus {
  223. background: var(--icon-hover-bg);
  224. }
  225.  
  226. /* custom CSS for each logo */
  227. .twitter-x {
  228. height: 2rem;
  229. -ms-flex-positive: 1;
  230. -webkit-box-flex: 1;
  231. -webkit-flex-grow: 1;
  232. flex-grow: 1;
  233. color: var(--twitter-icon-color);
  234. -moz-user-select: none;
  235. -ms-user-select: none;
  236. -webkit-user-select: none;
  237. user-select: none;
  238. vertical-align: text-bottom;
  239. position: relative;
  240. max-width: 100%;
  241. fill: currentcolor;
  242. display: inline-block;
  243. }
  244.  
  245. /* can probably be used with any SVG logo */
  246. .twitter-bird {
  247. height: 2rem;
  248. color: rgba(29,155,240,1.00) !important;
  249. vertical-align: text-bottom;
  250. position: relative;
  251. max-width: 100%;
  252. fill: currentcolor;
  253. -moz-user-select: none;
  254. -ms-user-select: none;
  255. -webkit-user-select: none;
  256. user-select: none;
  257. display: inline-block;
  258. }
  259.  
  260. /* can probably be used with any bitmap logo */
  261. .twitter-classic {
  262. max-width: 2rem;
  263. vertical-align: text-bottom;
  264. position: relative;
  265. -moz-user-select: none;
  266. -ms-user-select: none;
  267. -webkit-user-select: none;
  268. user-select: none;
  269. display: inline-block;
  270. }
  271.  
  272. .threads-squiggly {
  273. height: 2rem;
  274. fill: var(--twitter-icon-color);
  275. }
  276.  
  277. .hidden {
  278. display: none !important;
  279. }
  280. `})));
  281.  
  282. // 0. avoid a flash of X favicon
  283. const dottedFavicons = {};
  284. async function overrideFavicon () {
  285. const hasNotification = document.title[0] == "(";
  286. let icon = logo.favicon;
  287. if (hasNotification) {
  288. if (logo.faviconDot) {
  289. icon = logo.faviconDot;
  290. } else {
  291. if (!dottedFavicons[icon]) {
  292. // slap a dot on the favicon
  293. const img = await new Promise(r => crel('img', { src: icon, onload: e=>r(e.target) }));
  294. const { width, height } = img;
  295. const canvas = crel('canvas', { width, height });
  296. const ctx = canvas.getContext("2d");
  297. ctx.drawImage(img, 0, 0);
  298. ctx.fillStyle = logo.dot ?? "red";
  299. ctx.arc(width*3/4, height/4, width/5, 0, Math.PI*2);
  300. ctx.fill();
  301. dottedFavicons[icon] = canvas.toDataURL();
  302. }
  303. icon = dottedFavicons[icon];
  304. }
  305. }
  306. $$`link[rel="shortcut icon"],link[rel="icon"]`.forEach(link => {
  307. if (link.href !== icon) link.href = icon;
  308. });
  309. }
  310. overrideFavicon();
  311.  
  312. // 1. early run to replace placeholder logo on app start.
  313. untilDOM("#placeholder").then(e=> {
  314. // tweak the loading logo right quick.
  315. if (logo.html) {
  316. const classes = e.firstChild.getAttribute("class");
  317. e.innerHTML = logo.html;
  318. e.firstChild.setAttribute('class', e.firstChild.getAttribute('class') + ' ' + classes);
  319. e.firstChild.setAttribute('style', "max-width: initial; height: initial");
  320. }
  321. });
  322.  
  323. // 2. watch for lightmode/darkmode changes and adjust (cheaply.)
  324. (async()=> {
  325. const bodyStyles = getComputedStyle(await until('body'));
  326. while (true) {
  327. var bgColor = await until((bg = bodyStyles.backgroundColor) => bg !== bgColor && bg);
  328. const isDarkMode = bgColor.replace(/[rgba( )]+/g,'').split(',').reduce((v,a)=>+a+v, 0) < 255;
  329.  
  330. document.body.style.setProperty("--twitter-bg-color", bgColor);
  331. document.body.style.setProperty("--twitter-icon-color", isDarkMode ? "rgba(214,217,219,1.00)" : "rgba(36,46,54,1.00)");
  332. document.body.style.setProperty("--icon-hover-bg", isDarkMode ? "rgba(239, 243, 244, 0.1)" : "rgba(15, 20, 25, 0.1)");
  333. document.body.style.setProperty("--dropdown-bg-color", isDarkMode ? "#111" : "#fff");
  334. document.body.style.setProperty("--dropdown-box-1", isDarkMode ? "rgba(255, 255, 255, 0.2)" : "rgba(101, 119, 134, 0.2)")
  335. document.body.style.setProperty("--dropdown-box-2", isDarkMode ? "rgba(255, 255, 255, 0.15)" : "rgba(101, 119, 134, 0.15)")
  336. }
  337. })();
  338.  
  339. // 3. DESKTOP: inject our logo picker dropdown, potentially several times.
  340. (async()=> {
  341. while (true) {
  342. const heading = await untilDOM(`header[role="banner"] h1[role="heading"]`);
  343. heading.append(crel('a', {
  344. className: "logo-dropdown-arrow logo-dropdown-anchor",
  345. textContent: '▾',
  346. onclick(e) { openLogoDropDown(e.shiftKey); }
  347. }));
  348. const logo = heading.firstChild;
  349. logo.addEventListener('keypress', e=> {
  350. if (e.code == 'Space' || e.code == 'Enter') {
  351. openLogoDropDown(e.shiftKey, true);
  352. e.preventDefault();
  353. }
  354. });
  355.  
  356. logo.tabIndex = "0";
  357. // wait until our dropdown gets wiped by React, and reapply our tweaks
  358. await untilDOM(()=>!$`.logo-dropdown-anchor`);
  359. }
  360. })();
  361.  
  362. // 𝜋. MOBILE: listen for tap or long tap on logo to bring up logo picker dropdown
  363. (async() => {
  364. while (true) {
  365. const logo = await untilDOM(() => $`[data-testid="TopNavBar"] :not([role="button"]) > div > svg`?.parentElement);
  366. logo.classList.add("logo-dropdown-anchor");
  367. let longPressTimer;
  368. const cleanupEventListeners = events({
  369. touchstart() {
  370. longPressTimer = setTimeout(() => openLogoDropDown(true), 500);
  371. },
  372. touchend(e) {
  373. clearTimeout(longPressTimer);
  374. if ($`.logo-dropdown`) {
  375. console.warn("FOO ASDFASD", e.target);
  376. e.preventDefault();
  377. e.stopPropagation();
  378. }
  379. },
  380. click() { openLogoDropDown() },
  381. contextmenu(e) { e.preventDefault() }
  382. }, logo);
  383. // wait until React wipes us out to reapply our tweaks
  384. await untilDOM(()=>!$`.logo-dropdown-anchor`);
  385. // `logo` isn't our node, clean up.
  386. cleanupEventListeners();
  387. }
  388. })();;
  389.  
  390. // 3½. dropdown and logo selection logic
  391. function openLogoDropDown(full, focus) {
  392. if (!$`.logo-dropdown-anchor`) return;
  393. let index = LOGOS.findIndex(l => logo.label === l.label);
  394. if (index==-1) index = 0;
  395. if (index >= LOGOS_CUTOFF) full = true;
  396. const disconnect = observeDOM(() => {
  397. const { bottom, left } = $`.logo-dropdown-anchor`.getBoundingClientRect();
  398. const dropdown = $`.logo-dropdown`;
  399. if (dropdown.style.top !== `${bottom}px`) dropdown.style.top = `${bottom}px`;
  400. if (dropdown.style.left !== `${left}px`) dropdown.style.left = `${left}px`;
  401. });
  402. const backdrop = crel('div', {
  403. className: "logo-dropdown-backdrop",
  404. ariaHaspopup: "true",
  405. ariaControls: "menu",
  406. onclick() {
  407. disconnect();
  408. backdrop.remove();
  409. dropdown.remove();
  410. document.body.classList.remove('logo-dropdown-open');
  411. removeEventListener('keydown', dropdownKeyHandler, true);
  412. }
  413. });
  414. const dropdown = crel('div', {
  415. className: "logo-dropdown",
  416. role: "menu",
  417. ariaLabel: 'Logo Picker',
  418. tabIndex: "-1",
  419. }, ...LOGOS.slice(0,full?LOGOS.length:LOGOS_CUTOFF).map(l => crel('div', {
  420. className: 'logo-dropdown-item',
  421. role: "menuitem",
  422. ariaLabel: l.label,
  423. title: l.label,
  424. tabIndex: "0",
  425. ...(l.logo ? {} : { innerHTML: l.html }),
  426. onclick() {
  427. backdrop.click();
  428. },
  429. onfocus() {
  430. applyBrand(logo.brand ?? brand, l.brand ?? brand);
  431. logo = l;
  432. GM_setValue("logo", {label: logo.label}); // don't store more than needed.
  433. },
  434. onkeypress(e) {
  435. if (e.code == "Enter" || e.code =="Space") {
  436. e.target.click();
  437. e.preventDefault();
  438. }
  439. }
  440. }, l.logo ? GM_addElement('img', {
  441. class: "twitter-classic",
  442. src: l.logo
  443. }): '')));
  444. document.body.append(backdrop, dropdown);
  445. document.body.classList.add('logo-dropdown-open');
  446. if (focus) dropdown.childNodes[index].focus();
  447. addEventListener('keydown', dropdownKeyHandler, true);
  448. function dropdownKeyHandler(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.  
  458. // 4. wait until the placeholder logo is out of the way, then replace the favicon and all logos aggressively.
  459. (async function applyLogo() {
  460. function replaceLegacyLogo(l, classes) {
  461. const logoElt = logo.logo ? GM_addElement('img', { class: 'twitter-classic', src: logo.logo }) : crel('div', { innerHTML: logo.html}).firstChild;
  462. if (l.classList.contains("legacy-logo")) {
  463. // it's one of ours, safe to blow up
  464. l.replaceWith(logoElt);
  465. } else {
  466. // this may be a React node. hide but don't destroy.
  467. l.classList.add('hidden');
  468. l.after(logoElt);
  469. }
  470. logoElt.dataset.class = classes;
  471. logoElt.setAttribute('class', logoElt.getAttribute('class') + ' ' + classes + ' legacy-logo');
  472. logoElt.setAttribute('style', "max-height: initial;max-width:999px;padding: 0 10px");
  473. }
  474. await untilDOM(()=>!$`#placeholder`);
  475. observeDOM(async() => {
  476. overrideFavicon();
  477. if (logo.html) {
  478. // initial sweep of legacy logos
  479. $$(legacyLogosSelector).forEach(path=> {
  480. const svg = path.closest`svg`;
  481. replaceLegacyLogo(svg, svg.getAttribute("class") ?? '');
  482. });
  483. // further updates of legacy logos when user picks another logo
  484. $$(".legacy-logo").forEach(l => {
  485. if (l.outerHTML.replace(/ (data-class|class|style|id)=".*?"/g,'') !== logo.html.replace(/ (class|style|id)=".*?"/g,'')) {
  486. replaceLegacyLogo(l, l.dataset.class);
  487. }
  488. });
  489. // special case the primary logo
  490. const l = ($`header[role="banner"] h1[role="heading"] a[href="/home"] > div` ?? $`header[role="banner"] h1[role="heading"] a[href="/"] > div` ?? $`.twtr-grid [aria-label$=" home"]` ?? $`.logo-title .logo` ?? $`[class$="_twitter-logo"]`)?.firstElementChild;
  491. if (l && !l.classList.contains('hidden') && l.outerHTML !== logo.html) {
  492. l.classList.add('hidden');
  493. if (logo.logo) {
  494. l.after(GM_addElement('img', { class: 'twitter-classic legacy-logo', src: logo.logo }))
  495. } else {
  496. const logoElt = crel('div', { innerHTML: logo.html}).firstChild;
  497. logoElt.classList.add("legacy-logo");
  498. l.after(logoElt);
  499. }
  500. }
  501. // on Mobile, the logo can disappear, and we need to mimic that.
  502. $$(".legacy-logo").forEach(l => {
  503. const previous = l.previousElementSibling;
  504. if (!previous || !previous.classList.contains("hidden")) {
  505. l.remove();
  506. }
  507. })
  508. }
  509. });
  510. })();
  511.  
  512. // 5. brand consistentcy enforcement
  513. function applyBrand(from, to) {
  514. // the silly branding variants only make sense in English, don't butcher other languages.
  515. const isEnglish = /^en([-_].*)?$/i.test(document.documentElement.lang);
  516. if (!branding) {
  517. // force default brand instead of our silly variants
  518. to = brand;
  519. }
  520. // nothing more confusing than a logo that doesn't match its copy. let's help!
  521. if (!to) return;
  522.  
  523. // avoid querying the DOM separately for each word. tweak things to find and replace all words in one shot.
  524. const obj = to.site == LOGOS[0].brand.site ? {} : { "\\bX\\b" : true, X: to.site }; // X shenanigans to keep up with Elon's evolving non-sense.
  525. (isEnglish?["site","reactions","reaction","actions","action"]:["site"]).forEach(key => {
  526. const word = from[key], betterWord = to[key];
  527. if (!word || !betterWord || word == betterWord) return;
  528. obj[word] = betterWord;
  529. });
  530. const keys = Object.keys(obj);
  531. if (keys.length==0) return;
  532. const regexp = new RegExp(keys.join('|'),'g');
  533. function replaceBrandWord(elt) {
  534. // update text without damaging the DOM tree.
  535. if (elt.childNodes.length>0) {
  536. elt.childNodes.forEach(replaceBrandWord);
  537. } else {
  538. elt.textContent = elt.textContent.replace(regexp, w => obj[w]);
  539. }
  540. }
  541. // non-trivial Xpath evaluations are slow. matching CSS selectors, even with additional filters are often much faster.
  542. [...$$`div,span,title,a,b,button,h1,h2,p`]
  543. .filter(e=>!e.childElementCount && !e.closest`article[data-testid="tweet"],div[data-testid^="User"]`)
  544. .filter(e => e.textContent.match(regexp))
  545. .forEach(replaceBrandWord);
  546. $$$(`//span[text()="${keys.join('" or text()="')}"]`)
  547. .filter(e => !e.closest`[data-testid="tweetText"`)
  548. .forEach(replaceBrandWord);
  549. $$(`[placeholder*="${keys.join('"],[placeholder*="')}"]`)
  550. .forEach(elt => elt.placeholder = elt.placeholder.replace(regexp, w => obj[w]));
  551. }
  552. observeDOM(()=>applyBrand(brand, logo.brand));
  553.  
  554. // 6. keyboard shortcut: 'Q' (add ourselves in the '?' dialog, and do the thing.)
  555. (async function keyboardShortcut() {
  556. while (true) {
  557. // wait until something we see that has the shape of a keyboard shortcut modal, and grab the last "Actions" shortcut from it.
  558. const lastActionsRow = await untilDOM('#layers [role="dialog"][aria-labelledby] [data-viewportview]>div:last-child>div:nth-child(2) [role="row"]:last-child');
  559. const label = lastActionsRow.innerText.split('\n')[0];
  560. if (label == t`logo_menu_label`) { // we already have our shortcut label shown. chill.
  561. await sleep(500);
  562. continue;
  563. }
  564. console.log(i18n);
  565. // clone, customize and insert a new action shortcut.
  566. const newRow = lastActionsRow.cloneNode(true);
  567. $('span', newRow).textContent = t`logo_menu_label`;
  568. $('[role="cell"]>div', newRow).textContent = 'q';
  569. lastActionsRow.after(newRow);
  570. }
  571. })();
  572. addEventListener('keypress', e => {
  573. const a = document.activeElement;
  574. if (a.contentEditable == 'true' || a.tagName == 'INPUT' || a.tagName == 'TEXTAREA') return;
  575. if (e.code == 'KeyQ') {
  576. if ($`.logo-dropdown`) {
  577. $`.logo-dropdown-backdrop`?.click();
  578. } else {
  579. openLogoDropDown(e.shiftKey, true);
  580. }
  581. }
  582. }, true);