Control Panel for Twitter

Gives you more control over Twitter and adds missing features and UI improvements

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

  1. // ==UserScript==
  2. // @name Control Panel for Twitter
  3. // @description Gives you more control over Twitter and adds missing features and UI improvements
  4. // @icon https://raw.githubusercontent.com/insin/control-panel-for-twitter/master/icons/icon32.png
  5. // @namespace https://github.com/insin/control-panel-for-twitter/
  6. // @match https://twitter.com/*
  7. // @match https://mobile.twitter.com/*
  8. // @run-at document-start
  9. // @version 125
  10. // ==/UserScript==
  11. void function() {
  12.  
  13. let debug = false
  14.  
  15. /** @type {boolean} */
  16. let desktop
  17. /** @type {boolean} */
  18. let mobile
  19. let isSafari = navigator.userAgent.includes('Safari/') && !/Chrom(e|ium)\//.test(navigator.userAgent)
  20.  
  21. /** @type {HTMLHtmlElement} */
  22. let $html
  23. /** @type {HTMLBodyElement} */
  24. let $body
  25. /** @type {HTMLElement} */
  26. let $reactRoot
  27. /** @type {string} */
  28. let lang
  29. /** @type {string} */
  30. let dir
  31. /** @type {boolean} */
  32. let ltr
  33.  
  34. //#region Default config
  35. /**
  36. * @type {import("./types").Config}
  37. */
  38. const config = {
  39. debug: false,
  40. // Shared
  41. addAddMutedWordMenuItem: true,
  42. alwaysUseLatestTweets: true,
  43. defaultToLatestSearch: false,
  44. disableHomeTimeline: false,
  45. disabledHomeTimelineRedirect: 'notifications',
  46. disableTweetTextFormatting: false,
  47. dontUseChirpFont: false,
  48. dropdownMenuFontWeight: true,
  49. fastBlock: true,
  50. followButtonStyle: 'monochrome',
  51. hideAnalyticsNav: true,
  52. hideBlueReplyFollowedBy: false,
  53. hideBlueReplyFollowing: false,
  54. hideBookmarkButton: false,
  55. hideBookmarkMetrics: true,
  56. hideBookmarksNav: false,
  57. hideCommunitiesNav: false,
  58. hideConnectNav: true,
  59. hideExplorePageContents: true,
  60. hideFollowingMetrics: true,
  61. hideForYouTimeline: true,
  62. hideHelpCenterNav: true,
  63. hideHomeHeading: true,
  64. hideKeyboardShortcutsNav: false,
  65. hideLikeMetrics: true,
  66. hideListsNav: false,
  67. hideMetrics: false,
  68. hideMonetizationNav: true,
  69. hideMoreTweets: true,
  70. hideProfileRetweets: false,
  71. hideQuoteTweetMetrics: true,
  72. hideReplyMetrics: true,
  73. hideRetweetMetrics: true,
  74. hideSeeNewTweets: false,
  75. hideShareTweetButton: false,
  76. hideSubscriptions: true,
  77. hideTotalTweetsMetrics: true,
  78. hideTweetAnalyticsLinks: false,
  79. hideTwitterAdsNav: true,
  80. hideTwitterBlueReplies: false,
  81. hideTwitterBlueUpsells: true,
  82. hideUnavailableQuoteTweets: true,
  83. hideVerifiedNotificationsTab: true,
  84. hideViews: true,
  85. hideWhoToFollowEtc: true,
  86. listRetweets: 'ignore',
  87. mutableQuoteTweets: true,
  88. mutedQuotes: [],
  89. quoteTweets: 'ignore',
  90. reducedInteractionMode: false,
  91. replaceLogo: true,
  92. retweets: 'separate',
  93. showBlueReplyFollowersCount: true,
  94. tweakQuoteTweetsPage: true,
  95. twitterBlueChecks: 'replace',
  96. uninvertFollowButtons: true,
  97. // Experiments
  98. // none currently
  99. // Desktop only
  100. fullWidthContent: false,
  101. fullWidthMedia: true,
  102. hideAccountSwitcher: false,
  103. hideExploreNav: true,
  104. hideExploreNavWithSidebar: true,
  105. hideMessagesDrawer: true,
  106. hideSidebarContent: true,
  107. navBaseFontSize: true,
  108. navDensity: 'default',
  109. showRelevantPeople: false,
  110. // Mobile only
  111. hideAppNags: true,
  112. hideMessagesBottomNavItem: false,
  113. }
  114. //#endregion
  115.  
  116. //#region Locales
  117. /**
  118. * @type {{[key: string]: import("./types").Locale}}
  119. */
  120. const locales = {
  121. 'ar-x-fm': {
  122. ADD_MUTED_WORD: 'اضافة كلمة مكتومة',
  123. HOME: 'الرئيسيّة',
  124. MUTE_THIS_CONVERSATION: 'كتم هذه المحادثه',
  125. QUOTE_TWEET: 'اقتباس التغريدة',
  126. QUOTE_TWEETS: 'تغريدات اقتباس',
  127. RETWEETS: 'إعادات التغريد',
  128. SHARED_TWEETS: 'التغريدات المشتركة',
  129. SHOW: 'إظهار',
  130. SHOW_MORE_REPLIES: 'عرض المزيد من الردود',
  131. TURN_OFF_RETWEETS: 'تعطيل إعادة التغريد',
  132. TURN_ON_RETWEETS: 'تفعيل إعادة التغريد',
  133. TWITTER: 'تويتر',
  134. },
  135. ar: {
  136. ADD_MUTED_WORD: 'اضافة كلمة مكتومة',
  137. HOME: 'الرئيسيّة',
  138. MUTE_THIS_CONVERSATION: 'كتم هذه المحادثه',
  139. QUOTE_TWEET: 'اقتباس التغريدة',
  140. QUOTE_TWEETS: 'تغريدات اقتباس',
  141. RETWEETS: 'إعادات التغريد',
  142. SHARED_TWEETS: 'التغريدات المشتركة',
  143. SHOW: 'إظهار',
  144. SHOW_MORE_REPLIES: 'عرض المزيد من الردود',
  145. TURN_OFF_RETWEETS: 'تعطيل إعادة التغريد',
  146. TURN_ON_RETWEETS: 'تفعيل إعادة التغريد',
  147. },
  148. bg: {
  149. ADD_MUTED_WORD: 'Добавяне на заглушена дума',
  150. HOME: 'Начало',
  151. MUTE_THIS_CONVERSATION: 'Заглушаване на разговора',
  152. QUOTE_TWEET: 'Цитиране на туита',
  153. QUOTE_TWEETS: 'Туитове с цитат',
  154. RETWEETS: 'Ретуитове',
  155. SHARED_TWEETS: 'Споделени туитове',
  156. SHOW: 'Показване',
  157. SHOW_MORE_REPLIES: 'Показване на още отговори',
  158. TURN_OFF_RETWEETS: 'Изключване на ретуитовете',
  159. TURN_ON_RETWEETS: 'Включване на ретуитовете',
  160. },
  161. bn: {
  162. ADD_MUTED_WORD: 'নীরব করা শব্দ যোগ করুন',
  163. HOME: 'হোম',
  164. MUTE_THIS_CONVERSATION: 'এই কথা-বার্তা নীরব করুন',
  165. QUOTE_TWEET: 'টুইট উদ্ধৃত করুন',
  166. QUOTE_TWEETS: 'টুইট উদ্ধৃতিগুলো',
  167. RETWEETS: 'পুনঃটুইটগুলো',
  168. SHARED_TWEETS: 'ভাগ করা টুইটগুলি',
  169. SHOW: 'দেখান',
  170. SHOW_MORE_REPLIES: 'আরও উত্তর দেখান',
  171. TURN_OFF_RETWEETS: 'পুনঃ টুইটগুলি বন্ধ করুন',
  172. TURN_ON_RETWEETS: 'পুনঃ টুইটগুলি চালু করুন',
  173. TWITTER: 'টুইটার',
  174. },
  175. ca: {
  176. ADD_MUTED_WORD: 'Afegeix una paraula silenciada',
  177. HOME: 'Inici',
  178. MUTE_THIS_CONVERSATION: 'Silencia la conversa',
  179. QUOTE_TWEET: 'Cita el tuit',
  180. QUOTE_TWEETS: 'Tuits amb cita',
  181. RETWEETS: 'Retuits',
  182. SHARED_TWEETS: 'Tuits compartits',
  183. SHOW: 'Mostra',
  184. SHOW_MORE_REPLIES: 'Mostra més respostes',
  185. TURN_OFF_RETWEETS: 'Desactiva els retuits',
  186. TURN_ON_RETWEETS: 'Activa els retuits',
  187. },
  188. cs: {
  189. ADD_MUTED_WORD: 'Přidat slovo na seznam skrytých slov',
  190. HOME: 'Hlavní stránka',
  191. MUTE_THIS_CONVERSATION: 'Skrýt tuto konverzaci',
  192. QUOTE_TWEET: 'Citovat Tweet',
  193. QUOTE_TWEETS: 'Tweety s citací',
  194. RETWEETS: 'Retweety',
  195. SHARED_TWEETS: 'Sdílené tweety',
  196. SHOW: 'Zobrazit',
  197. SHOW_MORE_REPLIES: 'Zobrazit další odpovědi',
  198. TURN_OFF_RETWEETS: 'Vypnout retweety',
  199. TURN_ON_RETWEETS: 'Zapnout retweety',
  200. },
  201. da: {
  202. ADD_MUTED_WORD: 'Tilføj skjult ord',
  203. HOME: 'Forside',
  204. MUTE_THIS_CONVERSATION: 'Skjul denne samtale',
  205. QUOTE_TWEET: 'Citér Tweet',
  206. QUOTE_TWEETS: 'Citat-Tweets',
  207. SHARED_TWEETS: 'Delte tweets',
  208. SHOW: 'Vis',
  209. SHOW_MORE_REPLIES: 'Vis flere svar',
  210. TURN_OFF_RETWEETS: 'Slå Retweets fra',
  211. TURN_ON_RETWEETS: 'Slå Retweets til',
  212. },
  213. de: {
  214. ADD_MUTED_WORD: 'Stummgeschaltetes Wort hinzufügen',
  215. HOME: 'Startseite',
  216. MUTE_THIS_CONVERSATION: 'Diese Konversation stummschalten',
  217. QUOTE_TWEET: 'Tweet zitieren',
  218. QUOTE_TWEETS: 'Zitierte Tweets',
  219. SHARED_TWEETS: 'Geteilte Tweets',
  220. SHOW: 'Anzeigen',
  221. SHOW_MORE_REPLIES: 'Mehr Antworten anzeigen',
  222. TURN_OFF_RETWEETS: 'Retweets ausschalten',
  223. TURN_ON_RETWEETS: 'Retweets einschalten',
  224. },
  225. el: {
  226. ADD_MUTED_WORD: 'Προσθήκη λέξης σε σίγαση',
  227. HOME: 'Αρχική σελίδα',
  228. MUTE_THIS_CONVERSATION: 'Σίγαση αυτής της συζήτησης',
  229. QUOTE_TWEET: 'Παράθεση Tweet',
  230. QUOTE_TWEETS: 'Tweet με παράθεση',
  231. RETWEETS: 'Retweet',
  232. SHARED_TWEETS: 'Κοινόχρηστα Tweets',
  233. SHOW: 'Εμφάνιση',
  234. SHOW_MORE_REPLIES: 'Εμφάνιση περισσότερων απαντήσεων',
  235. TURN_OFF_RETWEETS: 'Απενεργοποίηση των Retweet',
  236. TURN_ON_RETWEETS: 'Ενεργοποίηση των Retweet',
  237. },
  238. en: {
  239. ADD_MUTED_WORD: 'Add muted word',
  240. HOME: 'Home',
  241. MUTE_THIS_CONVERSATION: 'Mute this conversation',
  242. QUOTE_TWEET: 'Quote Tweet',
  243. QUOTE_TWEETS: 'Quote Tweets',
  244. RETWEETS: 'Retweets',
  245. SHARED_TWEETS: 'Shared Tweets',
  246. SHOW: 'Show',
  247. SHOW_MORE_REPLIES: 'Show more replies',
  248. TURN_OFF_RETWEETS: 'Turn off Retweets',
  249. TURN_ON_RETWEETS: 'Turn on Retweets',
  250. TWITTER: 'Twitter',
  251. },
  252. es: {
  253. ADD_MUTED_WORD: 'Añadir palabra silenciada',
  254. HOME: 'Inicio',
  255. MUTE_THIS_CONVERSATION: 'Silenciar esta conversación',
  256. QUOTE_TWEET: 'Citar Tweet',
  257. QUOTE_TWEETS: 'Tweets citados',
  258. SHARED_TWEETS: 'Tweets compartidos',
  259. SHOW: 'Mostrar',
  260. SHOW_MORE_REPLIES: 'Mostrar más respuestas',
  261. TURN_OFF_RETWEETS: 'Desactivar Retweets',
  262. TURN_ON_RETWEETS: 'Activar Retweets',
  263. },
  264. eu: {
  265. ADD_MUTED_WORD: 'Gehitu isilarazitako hitza',
  266. HOME: 'Hasiera',
  267. MUTE_THIS_CONVERSATION: 'Isilarazi elkarrizketa hau',
  268. QUOTE_TWEET: 'Txioa apaitu',
  269. QUOTE_TWEETS: 'Aipatu txioak',
  270. RETWEETS: 'Bertxioak',
  271. SHARED_TWEETS: 'Partekatutako',
  272. SHOW: 'Erakutsi',
  273. SHOW_MORE_REPLIES: 'Erakutsi erantzun gehiago',
  274. TURN_OFF_RETWEETS: 'Desaktibatu birtxioak',
  275. TURN_ON_RETWEETS: 'Aktibatu birtxioak',
  276. },
  277. fa: {
  278. ADD_MUTED_WORD: 'افزودن واژه خموش‌سازی شده',
  279. HOME: 'خانه',
  280. MUTE_THIS_CONVERSATION: 'خموش‌سازی این گفتگو',
  281. QUOTE_TWEET: 'نقل‌توییت',
  282. QUOTE_TWEETS: 'نقل‌توییت‌ها',
  283. RETWEETS: 'بازتوییت‌ها',
  284. SHARED_TWEETS: 'توییتهای مشترک',
  285. SHOW: 'نمایش',
  286. SHOW_MORE_REPLIES: 'نمایش پاسخ‌های بیشتر',
  287. TURN_OFF_RETWEETS: 'غیرفعال‌سازی بازتوییت‌ها',
  288. TURN_ON_RETWEETS: 'فعال سازی بازتوییت‌ها',
  289. TWITTER: 'توییتر',
  290. },
  291. fi: {
  292. ADD_MUTED_WORD: 'Lisää hiljennetty sana',
  293. HOME: 'Etusivu',
  294. MUTE_THIS_CONVERSATION: 'Hiljennä tämä keskustelu',
  295. QUOTE_TWEET: 'Twiitin lainaus',
  296. QUOTE_TWEETS: 'Twiitin lainaukset',
  297. RETWEETS: 'Uudelleentwiittaukset',
  298. SHARED_TWEETS: 'Jaetut twiitit',
  299. SHOW: 'Näytä',
  300. SHOW_MORE_REPLIES: 'Näytä lisää vastauksia',
  301. TURN_OFF_RETWEETS: 'Poista uudelleentwiittaukset käytöstä',
  302. TURN_ON_RETWEETS: 'Ota uudelleentwiittaukset käyttöön',
  303. },
  304. fil: {
  305. ADD_MUTED_WORD: 'Idagdag ang naka-mute na salita',
  306. HOME: 'Home',
  307. MUTE_THIS_CONVERSATION: 'I-mute ang usapang ito',
  308. QUOTE_TWEET: 'Quote na Tweet',
  309. QUOTE_TWEETS: 'Mga Quote na Tweet',
  310. RETWEETS: 'Mga Retweet',
  311. SHARED_TWEETS: 'Mga Ibinahaging Tweet',
  312. SHOW: 'Ipakita',
  313. SHOW_MORE_REPLIES: 'Magpakita pa ng mga sagot',
  314. TURN_OFF_RETWEETS: 'I-off ang Retweets',
  315. TURN_ON_RETWEETS: 'I-on ang Retweets',
  316. },
  317. fr: {
  318. ADD_MUTED_WORD: 'Ajouter un mot masqué',
  319. HOME: 'Accueil',
  320. MUTE_THIS_CONVERSATION: 'Masquer cette conversation',
  321. QUOTE_TWEET: 'Citer le Tweet',
  322. QUOTE_TWEETS: 'Tweets cités',
  323. SHARED_TWEETS: 'Tweets partagés',
  324. SHOW: 'Afficher',
  325. SHOW_MORE_REPLIES: 'Voir plus de réponses',
  326. TURN_OFF_RETWEETS: 'Désactiver les Retweets',
  327. TURN_ON_RETWEETS: 'Activer les Retweets',
  328. },
  329. ga: {
  330. ADD_MUTED_WORD: 'Cuir focal balbhaithe leis',
  331. HOME: 'Baile',
  332. MUTE_THIS_CONVERSATION: 'Balbhaigh an comhrá seo',
  333. QUOTE_TWEET: 'Cuir Ráiteas Leis',
  334. QUOTE_TWEETS: 'Luaigh Tvuíteanna',
  335. RETWEETS: 'Atweetanna',
  336. SHARED_TWEETS: 'Tweetanna Roinnte',
  337. SHOW: 'Taispeáin',
  338. SHOW_MORE_REPLIES: 'Taispeáin tuilleadh freagraí',
  339. TURN_OFF_RETWEETS: 'Cas as Atweetanna',
  340. TURN_ON_RETWEETS: 'Cas Atweetanna air',
  341. },
  342. gl: {
  343. ADD_MUTED_WORD: 'Engadir palabra silenciada',
  344. HOME: 'Inicio',
  345. MUTE_THIS_CONVERSATION: 'Silenciar esta conversa',
  346. QUOTE_TWEET: 'Citar chío',
  347. QUOTE_TWEETS: 'Chíos citados',
  348. RETWEETS: 'Rechouchíos',
  349. SHARED_TWEETS: 'Chíos compartidos',
  350. SHOW: 'Amosar',
  351. SHOW_MORE_REPLIES: 'Amosar máis respostas',
  352. TURN_OFF_RETWEETS: 'Desactivar os rechouchíos',
  353. TURN_ON_RETWEETS: 'Activar os rechouchíos',
  354. },
  355. gu: {
  356. ADD_MUTED_WORD: 'જોડાણ અટકાવેલો શબ્દ ઉમેરો',
  357. HOME: 'હોમ',
  358. MUTE_THIS_CONVERSATION: 'આ વાર્તાલાપનું જોડાણ અટકાવો',
  359. QUOTE_TWEET: 'અવતરણની સાથે ટ્વીટ કરો',
  360. QUOTE_TWEETS: 'અવતરણની સાથે ટ્વીટ્સ',
  361. RETWEETS: 'પુનટ્વીટ્સ',
  362. SHARED_TWEETS: 'શેર કરેલી ટ્વીટ્સ',
  363. SHOW: 'બતાવો',
  364. SHOW_MORE_REPLIES: 'વધુ પ્રત્યુતરો દર્શાવો',
  365. TURN_OFF_RETWEETS: 'પુનટ્વીટ્સ બંધ કરો',
  366. TURN_ON_RETWEETS: 'પુનટ્વીટ્સ ચાલુ કરો',
  367. },
  368. he: {
  369. ADD_MUTED_WORD: 'הוסף מילה מושתקת',
  370. HOME: 'דף הבית',
  371. MUTE_THIS_CONVERSATION: 'להשתיק את השיחה הזאת',
  372. QUOTE_TWEET: 'ציטוט ציוץ',
  373. QUOTE_TWEETS: 'ציוצי ציטוט',
  374. RETWEETS: 'ציוצים מחדש',
  375. SHARED_TWEETS: 'ציוצים משותפים',
  376. SHOW: 'הצג',
  377. SHOW_MORE_REPLIES: 'הצג תשובות נוספות',
  378. TURN_OFF_RETWEETS: 'כבה ציוצים מחדש',
  379. TURN_ON_RETWEETS: 'הפעל ציוצים מחדש',
  380. TWITTER: 'טוויטר',
  381. },
  382. hi: {
  383. ADD_MUTED_WORD: 'म्यूट किया गया शब्द जोड़ें',
  384. HOME: 'होम',
  385. MUTE_THIS_CONVERSATION: 'इस बातचीत को म्यूट करें',
  386. QUOTE_TWEET: 'ट्वीट क्वोट करें',
  387. QUOTE_TWEETS: 'कोट ट्वीट्स',
  388. RETWEETS: 'रीट्वीट्स',
  389. SHARED_TWEETS: 'साझा किए गए ट्वीट',
  390. SHOW: 'दिखाएं',
  391. SHOW_MORE_REPLIES: 'और अधिक जवाब दिखाएँ',
  392. TURN_OFF_RETWEETS: 'रीट्वीट बंद करें',
  393. TURN_ON_RETWEETS: 'रीट्वीट चालू करें',
  394. },
  395. hr: {
  396. ADD_MUTED_WORD: 'Dodaj onemogućenu riječ',
  397. HOME: 'Naslovnica',
  398. MUTE_THIS_CONVERSATION: 'Isključi zvuk ovog razgovora',
  399. QUOTE_TWEET: 'Citiraj Tweet',
  400. QUOTE_TWEETS: 'Citirani tweetovi',
  401. RETWEETS: 'Proslijeđeni tweetovi',
  402. SHARED_TWEETS: 'Dijeljeni tweetovi',
  403. SHOW: 'Prikaži',
  404. SHOW_MORE_REPLIES: 'Prikaži još odgovora',
  405. TURN_OFF_RETWEETS: 'Isključi proslijeđene tweetove',
  406. TURN_ON_RETWEETS: 'Uključi proslijeđene tweetove',
  407. },
  408. hu: {
  409. ADD_MUTED_WORD: 'Elnémított szó hozzáadása',
  410. HOME: 'Kezdőlap',
  411. MUTE_THIS_CONVERSATION: 'Beszélgetés némítása',
  412. QUOTE_TWEET: 'Tweet idézése',
  413. QUOTE_TWEETS: 'Tweet-idézések',
  414. RETWEETS: 'Retweetek',
  415. SHARED_TWEETS: 'Megosztott tweetek',
  416. SHOW: 'Megjelenítés',
  417. SHOW_MORE_REPLIES: 'Több válasz megjelenítése',
  418. TURN_OFF_RETWEETS: 'Retweetek kikapcsolása',
  419. TURN_ON_RETWEETS: 'Retweetek bekapcsolása',
  420. },
  421. id: {
  422. ADD_MUTED_WORD: 'Tambahkan kata kunci yang dibisukan',
  423. HOME: 'Beranda',
  424. MUTE_THIS_CONVERSATION: 'Bisukan percakapan ini',
  425. QUOTE_TWEET: 'Kutip Tweet',
  426. QUOTE_TWEETS: 'Tweet Kutipan',
  427. RETWEETS: 'Retweet',
  428. SHARED_TWEETS: 'Tweet yang Dibagikan',
  429. SHOW: 'Tampilkan',
  430. SHOW_MORE_REPLIES: 'Tampilkan balasan lainnya',
  431. TURN_OFF_RETWEETS: 'Matikan Retweet',
  432. TURN_ON_RETWEETS: 'Nyalakan Retweet',
  433. },
  434. it: {
  435. ADD_MUTED_WORD: 'Aggiungi parola o frase silenziata',
  436. HOME: 'Home',
  437. MUTE_THIS_CONVERSATION: 'Silenzia questa conversazione',
  438. QUOTE_TWEET: 'Cita Tweet',
  439. QUOTE_TWEETS: 'Tweet di citazione',
  440. RETWEETS: 'Retweet',
  441. SHARED_TWEETS: 'Tweet condivisi',
  442. SHOW: 'Mostra',
  443. SHOW_MORE_REPLIES: 'Mostra altre risposte',
  444. TURN_OFF_RETWEETS: 'Disattiva Retweet',
  445. TURN_ON_RETWEETS: 'Attiva Retweet',
  446. },
  447. ja: {
  448. ADD_MUTED_WORD: 'ミュートするキーワードを追加',
  449. HOME: 'ホーム',
  450. MUTE_THIS_CONVERSATION: 'この会話をミュート',
  451. QUOTE_TWEET: '引用ツイート',
  452. QUOTE_TWEETS: '引用ツイート',
  453. RETWEETS: 'リツイート',
  454. SHARED_TWEETS: '共有ツイート',
  455. SHOW: '表示',
  456. SHOW_MORE_REPLIES: '返信をさらに表示',
  457. TURN_OFF_RETWEETS: 'リツイートをオフにする',
  458. TURN_ON_RETWEETS: 'リツイートをオンにする',
  459. },
  460. kn: {
  461. ADD_MUTED_WORD: 'ಸದ್ದಡಗಿಸಿದ ಪದವನ್ನು ಸೇರಿಸಿ',
  462. HOME: 'ಹೋಮ್',
  463. MUTE_THIS_CONVERSATION: 'ಈ ಸಂವಾದವನ್ನು ಸದ್ದಡಗಿಸಿ',
  464. QUOTE_TWEET: 'ಟ್ವೀಟ್ ಕೋಟ್ ಮಾಡಿ',
  465. QUOTE_TWEETS: 'ಕೋಟ್ ಟ್ವೀಟ್‌ಗಳು',
  466. RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳು',
  467. SHARED_TWEETS: 'ಹಂಚಿದ ಟ್ವೀಟ್‌ಗಳು',
  468. SHOW: 'ತೋರಿಸಿ',
  469. SHOW_MORE_REPLIES: 'ಇನ್ನಷ್ಟು ಪ್ರತಿಕ್ರಿಯೆಗಳನ್ನು ತೋರಿಸಿ',
  470. TURN_OFF_RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳನ್ನು ಆಫ್ ಮಾಡಿ',
  471. TURN_ON_RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳನ್ನು ಆನ್ ಮಾಡಿ',
  472. },
  473. ko: {
  474. ADD_MUTED_WORD: '뮤트할 단어 추가하기',
  475. HOME: '홈',
  476. MUTE_THIS_CONVERSATION: '이 대화 뮤트하기',
  477. QUOTE_TWEET: '트윗 인용하기',
  478. QUOTE_TWEETS: '트윗 인용하기',
  479. RETWEETS: '리트윗',
  480. SHARED_TWEETS: '공유 트윗',
  481. SHOW: '표시',
  482. SHOW_MORE_REPLIES: '더 많은 답글 보기',
  483. TURN_OFF_RETWEETS: '리트윗 끄기',
  484. TURN_ON_RETWEETS: '리트윗 켜기',
  485. TWITTER: '트위터',
  486. },
  487. mr: {
  488. ADD_MUTED_WORD: 'म्यूट केलेले शब्द सामील करा',
  489. HOME: 'होम',
  490. MUTE_THIS_CONVERSATION: 'ही चर्चा म्यूट करा',
  491. QUOTE_TWEET: 'ट्विट वर भाष्य करा',
  492. QUOTE_TWEETS: 'भाष्य ट्विट्स',
  493. RETWEETS: 'पुनर्ट्विट्स',
  494. SHARED_TWEETS: 'सामायिक ट्विट',
  495. SHOW: 'दाखवा',
  496. SHOW_MORE_REPLIES: 'अधिक प्रत्युत्तरे दाखवा',
  497. TURN_OFF_RETWEETS: 'पुनर्ट्विट्स बंद करा',
  498. TURN_ON_RETWEETS: 'पुनर्ट्विट्स चालू करा',
  499. },
  500. ms: {
  501. ADD_MUTED_WORD: 'Tambahkan perkataan yang disenyapkan',
  502. HOME: 'Laman Utama',
  503. MUTE_THIS_CONVERSATION: 'Senyapkan perbualan ini',
  504. QUOTE_TWEET: 'Petik Tweet',
  505. QUOTE_TWEETS: 'Tweet Petikan',
  506. RETWEETS: 'Tweet semula',
  507. SHARED_TWEETS: 'Tweet Berkongsi',
  508. SHOW: 'Tunjukkan',
  509. SHOW_MORE_REPLIES: 'Tunjukkan lagi balasan',
  510. TURN_OFF_RETWEETS: 'Matikan Tweet semula',
  511. TURN_ON_RETWEETS: 'Hidupkan Tweet semula',
  512. },
  513. nb: {
  514. ADD_MUTED_WORD: 'Skjul nytt ord',
  515. HOME: 'Hjem',
  516. MUTE_THIS_CONVERSATION: 'Skjul denne samtalen',
  517. QUOTE_TWEET: 'Sitat-Tweet',
  518. QUOTE_TWEETS: 'Sitat-Tweets',
  519. SHARED_TWEETS: 'Delte tweets',
  520. SHOW: 'Vis',
  521. SHOW_MORE_REPLIES: 'Vis flere svar',
  522. TURN_OFF_RETWEETS: 'Slå av Retweets',
  523. TURN_ON_RETWEETS: 'Slå på Retweets',
  524. },
  525. nl: {
  526. ADD_MUTED_WORD: 'Genegeerd woord toevoegen',
  527. HOME: 'Startpagina',
  528. MUTE_THIS_CONVERSATION: 'Dit gesprek negeren',
  529. QUOTE_TWEET: 'Citeer Tweet',
  530. QUOTE_TWEETS: 'Geciteerde Tweets',
  531. SHARED_TWEETS: 'Gedeelde Tweets',
  532. SHOW: 'Weergeven',
  533. SHOW_MORE_REPLIES: 'Meer antwoorden tonen',
  534. TURN_OFF_RETWEETS: 'Retweets uitschakelen',
  535. TURN_ON_RETWEETS: 'Retweets inschakelen',
  536. },
  537. pl: {
  538. ADD_MUTED_WORD: 'Dodaj wyciszone słowo',
  539. HOME: 'Główna',
  540. MUTE_THIS_CONVERSATION: 'Wycisz tę rozmowę',
  541. QUOTE_TWEET: 'Cytuj Tweeta',
  542. QUOTE_TWEETS: 'Cytaty z Tweeta',
  543. RETWEETS: 'Tweety podane dalej',
  544. SHARED_TWEETS: 'Udostępnione Tweety',
  545. SHOW: 'Pokaż',
  546. SHOW_MORE_REPLIES: 'Pokaż więcej odpowiedzi',
  547. TURN_OFF_RETWEETS: 'Wyłącz Tweety podane dalej',
  548. TURN_ON_RETWEETS: 'Włącz Tweety podane dalej',
  549. },
  550. pt: {
  551. ADD_MUTED_WORD: 'Adicionar palavra silenciada',
  552. HOME: 'Página Inicial',
  553. MUTE_THIS_CONVERSATION: 'Silenciar esta conversa',
  554. QUOTE_TWEET: 'Comentar o Tweet',
  555. QUOTE_TWEETS: 'Tweets com comentário',
  556. SHARED_TWEETS: 'Tweets Compartilhados',
  557. SHOW: 'Mostrar',
  558. SHOW_MORE_REPLIES: 'Mostrar mais respostas',
  559. TURN_OFF_RETWEETS: 'Desativar Retweets',
  560. TURN_ON_RETWEETS: 'Ativar Retweets',
  561. },
  562. ro: {
  563. ADD_MUTED_WORD: 'Adaugă cuvântul ignorat',
  564. HOME: 'Pagina principală',
  565. MUTE_THIS_CONVERSATION: 'Ignoră această conversație',
  566. QUOTE_TWEET: 'Citează Tweetul',
  567. QUOTE_TWEETS: 'Tweeturi cu citat',
  568. RETWEETS: 'Retweeturi',
  569. SHARED_TWEETS: 'Tweeturi partajate',
  570. SHOW: 'Afișează',
  571. SHOW_MORE_REPLIES: 'Afișează mai multe răspunsuri',
  572. TURN_OFF_RETWEETS: 'Dezactivează Retweeturile',
  573. TURN_ON_RETWEETS: 'Activează Retweeturile',
  574. },
  575. ru: {
  576. ADD_MUTED_WORD: 'Добавить игнорируемое слово',
  577. HOME: 'Главная',
  578. MUTE_THIS_CONVERSATION: 'Игнорировать эту переписку',
  579. QUOTE_TWEET: 'Цитировать',
  580. QUOTE_TWEETS: 'Твиты с цитатами',
  581. RETWEETS: 'Ретвиты',
  582. SHARED_TWEETS: 'Общие твиты',
  583. SHOW: 'Показать',
  584. SHOW_MORE_REPLIES: 'Показать еще ответы',
  585. TURN_OFF_RETWEETS: 'Отключить ретвиты',
  586. TURN_ON_RETWEETS: 'Включить ретвиты',
  587. TWITTER: 'Твиттер',
  588. },
  589. sk: {
  590. ADD_MUTED_WORD: 'Pridať stíšené slovo',
  591. HOME: 'Domov',
  592. MUTE_THIS_CONVERSATION: 'Stíšiť túto konverzáciu',
  593. QUOTE_TWEET: 'Tweet s citátom',
  594. QUOTE_TWEETS: 'Tweety s citátom',
  595. RETWEETS: 'Retweety',
  596. SHARED_TWEETS: 'Zdieľané Tweety',
  597. SHOW: 'Zobraziť',
  598. SHOW_MORE_REPLIES: 'Zobraziť viac odpovedí',
  599. TURN_OFF_RETWEETS: 'Vypnúť retweety',
  600. TURN_ON_RETWEETS: 'Zapnúť retweety',
  601. },
  602. sr: {
  603. ADD_MUTED_WORD: 'Додај игнорисану реч',
  604. HOME: 'Почетна',
  605. MUTE_THIS_CONVERSATION: 'Игнориши овај разговор',
  606. QUOTE_TWEET: 'твит са цитатом',
  607. QUOTE_TWEETS: 'твит(ов)а са цитатом',
  608. RETWEETS: 'Ретвитови',
  609. SHARED_TWEETS: 'Дељени твитови',
  610. SHOW: 'Прикажи',
  611. SHOW_MORE_REPLIES: 'Прикажи још одговора',
  612. TURN_OFF_RETWEETS: 'Искључи ретвитове',
  613. TURN_ON_RETWEETS: 'Укључи ретвитове',
  614. TWITTER: 'Твитер',
  615. },
  616. sv: {
  617. ADD_MUTED_WORD: 'Lägg till ignorerat ord',
  618. HOME: 'Hem',
  619. MUTE_THIS_CONVERSATION: 'Ignorera den här konversationen',
  620. QUOTE_TWEET: 'Citera Tweet',
  621. QUOTE_TWEETS: 'Citat-tweets',
  622. SHARED_TWEETS: 'Delade tweetsen',
  623. SHOW: 'Visa',
  624. SHOW_MORE_REPLIES: 'Visa fler svar',
  625. TURN_OFF_RETWEETS: 'Stäng av Retweets',
  626. TURN_ON_RETWEETS: 'Slå på Retweets',
  627. },
  628. ta: {
  629. ADD_MUTED_WORD: 'செயல்மறைத்த வார்த்தையைச் சேர்',
  630. HOME: 'முகப்பு',
  631. MUTE_THIS_CONVERSATION: 'இந்த உரையாடலை செயல்மறை',
  632. QUOTE_TWEET: 'ட்விட்டை மேற்கோள் காட்டு',
  633. QUOTE_TWEETS: 'மேற்கோள் கீச்சுகள்',
  634. RETWEETS: 'மறுகீச்சுகள்',
  635. SHARED_TWEETS: 'பகிரப்பட்ட ட்வீட்டுகள்',
  636. SHOW: 'காண்பி',
  637. SHOW_MORE_REPLIES: 'மேலும் பதில்களைக் காண்பி',
  638. TURN_OFF_RETWEETS: 'மறுகீச்சுகளை அணை',
  639. TURN_ON_RETWEETS: 'மறுகீச்சுகளை இயக்கு',
  640. },
  641. th: {
  642. ADD_MUTED_WORD: 'เพิ่มคำที่ซ่อน',
  643. HOME: 'หน้าแรก',
  644. MUTE_THIS_CONVERSATION: 'ซ่อนบทสนทนานี้',
  645. QUOTE_TWEET: 'อ้างอิงทวีต',
  646. QUOTE_TWEETS: 'ทวีตและคำพูด',
  647. RETWEETS: 'รีทวีต',
  648. SHARED_TWEETS: 'ทวีตที่แชร์',
  649. SHOW: 'แสดง',
  650. SHOW_MORE_REPLIES: 'แสดงการตอบกลับเพิ่มเติม',
  651. TURN_OFF_RETWEETS: 'ปิดรีทวีต',
  652. TURN_ON_RETWEETS: 'เปิดรีทวีต',
  653. TWITTER: 'ทวิตเตอร์',
  654. },
  655. tr: {
  656. ADD_MUTED_WORD: 'Sessize alınacak kelime ekle',
  657. HOME: 'Anasayfa',
  658. MUTE_THIS_CONVERSATION: 'Bu sohbeti sessize al',
  659. QUOTE_TWEET: 'Tweeti Alıntıla',
  660. QUOTE_TWEETS: 'Alıntı Tweetler',
  661. RETWEETS: 'Retweetler',
  662. SHARED_TWEETS: 'Paylaşılan Tweetler',
  663. SHOW: 'Göster',
  664. SHOW_MORE_REPLIES: 'Daha fazla yanıt göster',
  665. TURN_OFF_RETWEETS: 'Retweetleri kapat',
  666. TURN_ON_RETWEETS: 'Retweetleri aç',
  667. },
  668. uk: {
  669. ADD_MUTED_WORD: 'Додати слово до списку ігнорування',
  670. HOME: 'Головна',
  671. MUTE_THIS_CONVERSATION: 'Ігнорувати цю розмову',
  672. QUOTE_TWEET: 'Цитувати твіт',
  673. QUOTE_TWEETS: 'Цитовані твіти',
  674. RETWEETS: 'Ретвіти',
  675. SHARED_TWEETS: 'Спільні твіти',
  676. SHOW: 'Показати',
  677. SHOW_MORE_REPLIES: 'Показати більше відповідей',
  678. TURN_OFF_RETWEETS: 'Вимкнути ретвіти',
  679. TURN_ON_RETWEETS: 'Увімкнути ретвіти',
  680. TWITTER: 'Твіттер',
  681. },
  682. ur: {
  683. ADD_MUTED_WORD: 'میوٹ شدہ لفظ شامل کریں',
  684. HOME: 'ہوم',
  685. MUTE_THIS_CONVERSATION: 'اس گفتگو کو میوٹ کریں',
  686. QUOTE_TWEET: 'ٹویٹ کا حوالہ دیں',
  687. QUOTE_TWEETS: 'ٹویٹ کو نقل کرو',
  688. RETWEETS: 'ریٹویٹس',
  689. SHARED_TWEETS: 'مشترکہ ٹویٹس',
  690. SHOW: 'دکھائیں',
  691. SHOW_MORE_REPLIES: 'مزید جوابات دکھائیں',
  692. TURN_OFF_RETWEETS: 'ری ٹویٹس غیر فعال کریں',
  693. TURN_ON_RETWEETS: 'ری ٹویٹس غیر فعال کریں',
  694. TWITTER: 'ٹوئٹر',
  695. },
  696. vi: {
  697. ADD_MUTED_WORD: 'Thêm từ tắt tiếng',
  698. HOME: 'Trang chủ',
  699. MUTE_THIS_CONVERSATION: 'Tắt tiếng cuộc trò chuyện này',
  700. QUOTE_TWEET: 'Trích dẫn Tweet',
  701. QUOTE_TWEETS: 'Tweet trích dẫn',
  702. RETWEETS: 'Các Tweet lại',
  703. SHARED_TWEETS: 'Tweet được chia sẻ',
  704. SHOW: 'Hiện',
  705. SHOW_MORE_REPLIES: 'Hiển thị thêm trả lời',
  706. TURN_OFF_RETWEETS: 'Tắt Tweet lại',
  707. TURN_ON_RETWEETS: 'Bật Tweet lại',
  708. },
  709. 'zh-Hant': {
  710. ADD_MUTED_WORD: '加入靜音文字',
  711. HOME: '首頁',
  712. MUTE_THIS_CONVERSATION: '將此對話靜音',
  713. QUOTE_TWEET: '引用推文',
  714. QUOTE_TWEETS: '引用的推文',
  715. RETWEETS: '轉推',
  716. SHARED_TWEETS: '分享的推文',
  717. SHOW: '顯示',
  718. SHOW_MORE_REPLIES: '顯示更多回覆',
  719. TURN_OFF_RETWEETS: '關閉轉推',
  720. TURN_ON_RETWEETS: '開啟轉推',
  721. },
  722. zh: {
  723. ADD_MUTED_WORD: '添加要隐藏的字词',
  724. HOME: '主页',
  725. MUTE_THIS_CONVERSATION: '隐藏此对话',
  726. QUOTE_TWEET: '引用推文',
  727. QUOTE_TWEETS: '引用推文',
  728. RETWEETS: '转推',
  729. SHARED_TWEETS: '分享的推文',
  730. SHOW: '显示',
  731. SHOW_MORE_REPLIES: '显示更多回复',
  732. TURN_OFF_RETWEETS: '关闭转推',
  733. TURN_ON_RETWEETS: '开启转推',
  734. },
  735. }
  736.  
  737. /**
  738. * @param {import("./types").LocaleKey} code
  739. * @returns {string}
  740. */
  741. function getString(code) {
  742. return (locales[lang] || locales['en'])[code] || locales['en'][code];
  743. }
  744. //#endregion
  745.  
  746. //#region Constants
  747. /** @enum {string} */
  748. const PagePaths = {
  749. ADD_MUTED_WORD: '/settings/add_muted_keyword',
  750. BOOKMARKS: '/i/bookmarks',
  751. COMPOSE_MESSAGE: '/messages/compose',
  752. COMPOSE_TWEET: '/compose/tweet',
  753. CONNECT: '/i/connect',
  754. CUSTOMIZE_YOUR_VIEW: '/i/display',
  755. HOME: '/home',
  756. NOTIFICATION_TIMELINE: '/i/timeline',
  757. PROFILE_SETTINGS: '/settings/profile',
  758. SEARCH: '/search',
  759. }
  760.  
  761. /** @enum {string} */
  762. const Selectors = {
  763. BLOCK_MENU_ITEM: '[data-testid="block"]',
  764. DESKTOP_TIMELINE_HEADER: 'div[data-testid="primaryColumn"] > div > div:first-of-type',
  765. DISPLAY_DONE_BUTTON_DESKTOP: '#layers div[role="button"]:not([aria-label])',
  766. DISPLAY_DONE_BUTTON_MOBILE: 'main div[role="button"]:not([aria-label])',
  767. MESSAGES_DRAWER: 'div[data-testid="DMDrawer"]',
  768. MODAL_TIMELINE: '#layers section > h1 + div[aria-label] > div > div > div',
  769. MOBILE_TIMELINE_HEADER_OLD: 'header > div:nth-of-type(2) > div:first-of-type',
  770. MOBILE_TIMELINE_HEADER_NEW: 'div[data-testid="TopNavBar"]',
  771. NAV_HOME_LINK: 'a[data-testid="AppTabBar_Home_Link"]',
  772. PRIMARY_COLUMN: 'div[data-testid="primaryColumn"]',
  773. PRIMARY_NAV_DESKTOP: 'header nav',
  774. PRIMARY_NAV_MOBILE: '#layers nav',
  775. PROMOTED_TWEET_CONTAINER: '[data-testid="placementTracking"]',
  776. SIDEBAR: 'div[data-testid="sidebarColumn"]',
  777. SIDEBAR_WRAPPERS: 'div[data-testid="sidebarColumn"] > div > div > div > div > div',
  778. TIMELINE: 'div[data-testid="primaryColumn"] section > h1 + div[aria-label] > div > div > div',
  779. TIMELINE_HEADING: 'h2[role="heading"]',
  780. TWEET: '[data-testid="tweet"]',
  781. VERIFIED_TICK: 'svg[data-testid="icon-verified"]',
  782. X_LOGO_PATH: 'svg path[d="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"]',
  783. }
  784.  
  785. /** @enum {string} */
  786. const Svgs = {
  787. BLUE_LOGO_PATH: 'M16.5 3H2v18h15c3.038 0 5.5-2.46 5.5-5.5 0-1.4-.524-2.68-1.385-3.65-.08-.09-.089-.22-.023-.32.574-.87.908-1.91.908-3.03C22 5.46 19.538 3 16.5 3zm-.796 5.99c.457-.05.892-.17 1.296-.35-.302.45-.684.84-1.125 1.15.004.1.006.19.006.29 0 2.94-2.269 6.32-6.421 6.32-1.274 0-2.46-.37-3.459-1 .177.02.357.03.539.03 1.057 0 2.03-.35 2.803-.95-.988-.02-1.821-.66-2.109-1.54.138.03.28.04.425.04.206 0 .405-.03.595-.08-1.033-.2-1.811-1.1-1.811-2.18v-.03c.305.17.652.27 1.023.28-.606-.4-1.004-1.08-1.004-1.85 0-.4.111-.78.305-1.11 1.113 1.34 2.775 2.22 4.652 2.32-.038-.17-.058-.33-.058-.51 0-1.23 1.01-2.22 2.256-2.22.649 0 1.235.27 1.647.7.514-.1.997-.28 1.433-.54-.168.52-.526.96-.992 1.23z',
  788. HOME: '<g><path d="M12 9c-2.209 0-4 1.791-4 4s1.791 4 4 4 4-1.791 4-4-1.791-4-4-4zm0 6c-1.105 0-2-.895-2-2s.895-2 2-2 2 .895 2 2-.895 2-2 2zm0-13.304L.622 8.807l1.06 1.696L3 9.679V19.5C3 20.881 4.119 22 5.5 22h13c1.381 0 2.5-1.119 2.5-2.5V9.679l1.318.824 1.06-1.696L12 1.696zM19 19.5c0 .276-.224.5-.5.5h-13c-.276 0-.5-.224-.5-.5V8.429l7-4.375 7 4.375V19.5z"></path></g>',
  789. MUTE: '<g><path d="M18 6.59V1.2L8.71 7H5.5C4.12 7 3 8.12 3 9.5v5C3 15.88 4.12 17 5.5 17h2.09l-2.3 2.29 1.42 1.42 15.5-15.5-1.42-1.42L18 6.59zm-8 8V8.55l6-3.75v3.79l-6 6zM5 9.5c0-.28.22-.5.5-.5H8v6H5.5c-.28 0-.5-.22-.5-.5v-5zm6.5 9.24l1.45-1.45L16 19.2V14l2 .02v8.78l-6.5-4.06z"></path></g>',
  790. RETWEET: '<g><path d="M4.5 3.88l4.432 4.14-1.364 1.46L5.5 7.55V16c0 1.1.896 2 2 2H13v2H7.5c-2.209 0-4-1.79-4-4V7.55L1.432 9.48.068 8.02 4.5 3.88zM16.5 6H11V4h5.5c2.209 0 4 1.79 4 4v8.45l2.068-1.93 1.364 1.46-4.432 4.14-4.432-4.14 1.364-1.46 2.068 1.93V8c0-1.1-.896-2-2-2z"></path></g>',
  791. RETWEETS_OFF: '<g><path d="M3.707 21.707l18-18-1.414-1.414-2.088 2.088C17.688 4.137 17.11 4 16.5 4H11v2h5.5c.028 0 .056 0 .084.002l-10.88 10.88c-.131-.266-.204-.565-.204-.882V7.551l2.068 1.93 1.365-1.462L4.5 3.882.068 8.019l1.365 1.462 2.068-1.93V16c0 .871.278 1.677.751 2.334l-1.959 1.959 1.414 1.414zM18.5 9h2v7.449l2.068-1.93 1.365 1.462-4.433 4.137-4.432-4.137 1.365-1.462 2.067 1.93V9zm-8.964 9l-2 2H13v-2H9.536z"></path></g>',
  792. TWITTER_LOGO_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',
  793. }
  794.  
  795. /** @enum {string} */
  796. const Images = {
  797. TWITTER_FAVICON: 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAA0pJREFUWAntVk1oE1EQnnlJbFK3KUq9VJPYWgQVD/5QD0qpfweL1YJQoZAULBRPggp6kB78PQn14kHx0jRB0UO9REVFb1YqVBEsbZW2SbVS0B6apEnbbMbZ6qbZdTempqCHPAjvzcw3P5mdmfcAiquYgX+cAVwu/+5AdDMQnSPCHUhQA0hf+Rxy2OjicIvzm+qnKhito0qpb2wvJhWeJgCPP7oPELeHvdJ1VSGf3eOPnSWga0S0Qo9HxEkEusDBuNjbEca8G291nlBxmgDc/ukuIvAJxI6wr+yKCsq1ewLxQ2lZfpQLo8oQ4ZXdCkfnACrGWpyDCl+oQmVn5xuVPU102e2P3qoJkFOhzVb9S7KSnL5jJs/mI+As01PJFPSlZeFSZZoAGBRXBZyq9lk5NrC+e7pJ5en30c+JWk59pZ5vRDOuhAD381c/H/FKz1SMNgCE16rg505r5TT0uLqme93d0fbq+1SeLSeU83Ke0RHYFPGVPcjQfNDUwIa7M665+dQAEEjZoMwZMcEF9RxIDAgBQ2mCcqJ0Z0b+h4MNbZ4RnyOSDbNmE2iRk5jCNgIIckFoZAs4IgfLGrlKGjkzS16iwj6pV9I4mUvCPf73JVytH9nRJj24QHrqU8NCIWrMaGqAC+Ut/3ZzAS63cx4v2K/x/IvQBOCwWzu5KmJGwEJ5PIgeG9nQBDDcXPpFoDjJ7ThvBC6EZxXWkJG+JgAFwGM4KBAOcibeGCn8FQ/hyajXPmSk+1sACogn4hYk7OdiHDFSWipPkPWSmY6mCzIghEEuxJvcEYUvxIdhX2mvmSHDDPBF9AJRnDZTyp+P40671JYLbxiAohDxSTfQIg4oNxgPzCWPHaWQBViOf2jGqVwBaEaxGbAqOFMrp+SefC8eNhoFIY5lXzpmtnMGUB2IbU3JdIqVW9m5zcxINn/hAYKiIexdaTh4srHKORMAP0b28PNgJyGt5gvHzQVYx91QpVcwpRFl/p63HSR1DLbid1OcTpAJQOG7u+KH+aI5Qwj13IsamU5vkUSIc8uGLDa8OtoivV8U5HcydFLtT7hlSDVy2nfxI2Ibg9awuVU8IeJAOMF5m2B6jFs1tM5R9rS3GRP5uSuiihn4DzPwA7z7GDH+43gqAAAAAElFTkSuQmCC',
  798. TWITTER_PIP_FAVICON: 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAALASURBVHgB7VZNchJBFP5eM9FoRWV2WiZmbmBuIJ4g5ASBRWJlRXIC4ASQVUqxCo4QTwDegJzAiYlFXM1YZWmVQD9fQ6YyAwMMGBZW8i2G6e7He1+/3wHuOih4+fWieJhiKsirA0ZbE44fXZUaWDIGBH4/L+UUUB897DMfPf5ermKJUOaRIhTiDlNEBSwZlnkwY2vCuYOEWD/xMrCoKC41utISRlcc3Or2dfnqwHbDcj9X0fbztn9DAHxOoM0xrZILSIBXtR9F0VGKbJIhz7kVi3Lr770yAz4p2iYm188/awVi6lo4Ns4mETEDLz94uTHjIxDDRaWoohhOSjwi/9mKEFjtlKsayAuRM7M2HmFJwCRVIIqLSAAJjS822v0Vaip1E1oKC6XrXtrExjnxnJ6ldoVKFj0+ujywW3FKTTzJoibmAXP+Yt9uBEsrfLbWRelJzS/0B8z4WoKa6zW/1dd83Hlnn0Z0peAQkqNHvNPZi+qIELBWUNU97LLJ4hDESMZSlNmo+b5UTEvC85m0JCipTQREE+BhdzypIwSkLvyn4LKYrEzQkSZCloiyw+xJbnygfxX+VAJrPWnBoC9ixBXdDm4XflD7YajIinFq3L0E45J7fBa3HyEg7mhgeWjPJODu223J/iMsATzhcmp04+ueXTW1OsiD2zIuVfNNLockBAyIkdaaPxHGs3YR0JTQWnGbWkFCQZX5imwCmBoX++nGpONYD1zu2S0a9IN/g3jSNcNnqsy0ww2ZdPJzCKLXWAAy1N6ay2BRAgEcGZ+aqDnaoqdbjw6dhQgYwz1S2xKOQyQ0Phy7vDPr5iH5ITY+elmtpddLFyQzZBTP3xGl3FJ95NzQJ1hiAgMSw5jnJOZvMA/EMBNKSW89kUAAp+45+g+yojRjljL9NoP4GxdLYzk334vy3lYP0HBjhsw97vHf4C/b8RLHAOr+CQAAAABJRU5ErkJggg==',
  799. }
  800.  
  801. const THEME_COLORS = new Set([
  802. 'rgb(29, 155, 240)', // blue
  803. 'rgb(255, 212, 0)', // yellow
  804. 'rgb(244, 33, 46)', // pink
  805. 'rgb(120, 86, 255)', // purple
  806. 'rgb(255, 122, 0)', // orange
  807. 'rgb(0, 186, 124)', // green
  808. ])
  809. // <body> pseudo-selector for pages the full-width content feature works on
  810. const FULL_WIDTH_BODY_PSEUDO = ':is(.Community, .List, .MainTimeline)'
  811. // Matches any notification count at the start of the title
  812. const TITLE_NOTIFICATION_RE = /^\(\d+\+?\) /
  813. // The Communities nav item takes you to /yourusername/communities
  814. const URL_COMMUNITIES_RE = /^\/[a-zA-Z\d_]{1,20}\/communities\/?$/
  815. const URL_COMMUNITY_RE = /^\/i\/communities\/\d+(?:\/about)?\/?$/
  816. const URL_COMMUNITY_MEMBERS_RE = /^\/i\/communities\/\d+\/(?:members|moderators)\/?$/
  817. const URL_DISCOVER_COMMUNITIES_RE = /^\/i\/communities\/suggested\/?/
  818. const URL_LIST_RE = /\/i\/lists\/\d+\/?$/
  819. const URL_MEDIA_RE = /\/(?:photo|video)\/\d\/?$/
  820. const URL_MEDIAVIEWER_RE = /^\/[a-zA-Z\d_]{1,20}\/status\/\d+\/mediaviewer$/i
  821. // Matches URLs which show one of the tabs on a user profile page
  822. const URL_PROFILE_RE = /^\/([a-zA-Z\d_]{1,20})(?:\/(?:with_replies|superfollows|highlights|media|likes))?\/?$/
  823. // Matches URLs which show a user's Followers you know / Followers / Following tab
  824. const URL_PROFILE_FOLLOWS_RE = /^\/[a-zA-Z\d_]{1,20}\/follow(?:ing|ers|ers_you_follow)\/?$/
  825. const URL_TWEET_RE = /^\/([a-zA-Z\d_]{1,20})\/status\/(\d+)\/?$/
  826. const URL_TWEET_LIKES_RETWEETS_RE = /^\/[a-zA-Z\d_]{1,20}\/status\/\d+\/(likes|retweets)\/?$/
  827.  
  828. // The Twitter Media Assist exension adds a new button at the end of the action
  829. // bar (#346)
  830. const TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR = '.tva-download-icon, .tva-modal-download-icon'
  831. //#endregion
  832.  
  833. //#region Variables
  834. /**
  835. * The quoted Tweet associated with a caret menu that's just been opened.
  836. * @type {import("./types").QuotedTweet}
  837. */
  838. let quotedTweet = null
  839.  
  840. /** `true` when a 'Block @${user}' menu item was seen in the last popup. */
  841. let blockMenuItemSeen = false
  842.  
  843. /** Notification count in the title (including trailing space), e.g. `'(1) '`. */
  844. let currentNotificationCount = ''
  845.  
  846. /** Title of the current page, without the `' / Twitter'` suffix. */
  847. let currentPage = ''
  848.  
  849. /** Current `location.pathname`. */
  850. let currentPath = ''
  851.  
  852. /**
  853. * CSS rule in the React Native stylesheet which defines the Chirp font-family
  854. * and fallbacks for the whole app.
  855. * @type {CSSStyleRule}
  856. */
  857. let fontFamilyRule = null
  858.  
  859. /** @type {string} */
  860. let fontSize = null
  861.  
  862. /** Set to `true` when a Home/Following heading or Home nav link is used. */
  863. let homeNavigationIsBeingUsed = false
  864.  
  865. /** Set to `true` when the media modal is open on desktop. */
  866. let isDesktopMediaModalOpen = false
  867.  
  868. /** Set to `true` when a user list modal is open on desktop. */
  869. let isDesktopUserListModalOpen = false
  870.  
  871. /**
  872. * Cache for the last page title which was used for the main timeline.
  873. * @type {string}
  874. */
  875. let lastMainTimelineTitle = null
  876.  
  877. /**
  878. * MutationObservers active on the current modal.
  879. * @type {import("./types").Disconnectable[]}
  880. */
  881. let modalObservers = []
  882.  
  883. /**
  884. * `true` after the app has initialised.
  885. * @type {boolean}
  886. */
  887. let observingPageChanges = false
  888.  
  889. /**
  890. * MutationObservers active on the current page, or anything else we want to
  891. * clean up when the user moves off the current page.
  892. * @type {import("./types").Disconnectable[]}
  893. */
  894. let pageObservers = []
  895.  
  896. /** `true` when a 'Pin to your profile' menu item was seen in the last popup. */
  897. let pinMenuItemSeen = false
  898.  
  899. /** @type {number} */
  900. let selectedHomeTabIndex = -1
  901.  
  902. /**
  903. * Title for the fake timeline used to separate out retweets and quote tweets.
  904. * @type {string}
  905. */
  906. let separatedTweetsTimelineTitle = null
  907.  
  908. /**
  909. * The current "Color" setting, which can be changed in "Customize your view".
  910. * @type {string}
  911. */
  912. let themeColor = localStorage.lastThemeColor
  913.  
  914. /**
  915. * `true` when "For you" was the last tab selected on the main timeline.
  916. */
  917. let wasForYouTabSelected = false
  918.  
  919. function isOnBookmarksPage() {
  920. return currentPath == PagePaths.BOOKMARKS
  921. }
  922.  
  923. function isOnCommunitiesPage() {
  924. return URL_COMMUNITIES_RE.test(currentPath)
  925. }
  926.  
  927. function isOnCommunityPage() {
  928. return URL_COMMUNITY_RE.test(currentPath)
  929. }
  930.  
  931. function isOnCommunityMembersPage() {
  932. return URL_COMMUNITY_MEMBERS_RE.test(currentPath)
  933. }
  934.  
  935. function isOnDiscoverCommunitiesPage() {
  936. return URL_DISCOVER_COMMUNITIES_RE.test(currentPath)
  937. }
  938.  
  939. function isOnExplorePage() {
  940. return currentPath.startsWith('/explore')
  941. }
  942.  
  943. function isOnFollowListPage() {
  944. return URL_PROFILE_FOLLOWS_RE.test(currentPath)
  945. }
  946.  
  947. function isOnHomeTimeline() {
  948. return currentPage == getString('HOME')
  949. }
  950.  
  951. function isOnIndividualTweetPage() {
  952. return URL_TWEET_RE.test(currentPath)
  953. }
  954.  
  955. function isOnListPage() {
  956. return URL_LIST_RE.test(currentPath)
  957. }
  958.  
  959. function isOnMainTimelinePage() {
  960. return currentPath == PagePaths.HOME || (
  961. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW &&
  962. isOnHomeTimeline() ||
  963. isOnSeparatedTweetsTimeline()
  964. )
  965. }
  966.  
  967. function isOnNotificationsPage() {
  968. return currentPath.startsWith('/notifications')
  969. }
  970.  
  971. function isOnProfilePage() {
  972. let profilePathUsername = currentPath.match(URL_PROFILE_RE)?.[1]
  973. if (!profilePathUsername) return false
  974. // twitter.com/user and its sub-URLs put @user in the title
  975. return currentPage.toLowerCase().includes(`${ltr ? '@' : ''}${profilePathUsername.toLowerCase()}${!ltr ? '@' : ''}`)
  976. }
  977.  
  978. function isOnQuoteTweetsPage() {
  979. return currentPath.endsWith('/retweets/with_comments')
  980. }
  981.  
  982. function isOnSearchPage() {
  983. return currentPath.startsWith('/search') || currentPath.startsWith('/hashtag/')
  984. }
  985.  
  986. function isOnSeparatedTweetsTimeline() {
  987. return currentPage == separatedTweetsTimelineTitle
  988. }
  989.  
  990. function isOnSettingsPage() {
  991. return currentPath.startsWith('/settings')
  992. }
  993.  
  994. function shouldHideSidebar() {
  995. return isOnExplorePage() || isOnDiscoverCommunitiesPage()
  996. }
  997.  
  998. function shouldShowSeparatedTweetsTab() {
  999. return config.retweets == 'separate' || config.quoteTweets == 'separate'
  1000. }
  1001. //#endregion
  1002.  
  1003. //#region Utility functions
  1004. /**
  1005. * @param {string} role
  1006. * @return {HTMLStyleElement}
  1007. */
  1008. function addStyle(role) {
  1009. let $style = document.createElement('style')
  1010. $style.dataset.insertedBy = 'control-panel-for-twitter'
  1011. $style.dataset.role = role
  1012. document.head.appendChild($style)
  1013. return $style
  1014. }
  1015.  
  1016. /**
  1017. * @param {Element} $svg
  1018. */
  1019. function blueCheck($svg) {
  1020. if (!$svg) {
  1021. warn('blueCheck was given', $svg)
  1022. return
  1023. }
  1024. $svg.classList.add('tnt_blue_check')
  1025. // Safari doesn't support using `d: path(…)` to replace paths in an SVG, so
  1026. // we have to manually patch the path in it.
  1027. if (isSafari && config.twitterBlueChecks == 'replace') {
  1028. $svg.firstElementChild.firstElementChild.setAttribute('d', Svgs.BLUE_LOGO_PATH)
  1029. }
  1030. }
  1031.  
  1032. /**
  1033. * @param {Element} $svgPath
  1034. */
  1035. function twitterLogo($svgPath) {
  1036. // Safari doesn't support using `d: path(…)` to replace paths in an SVG, so
  1037. // we have to manually patch the path in it.
  1038. $svgPath.setAttribute('d', Svgs.TWITTER_LOGO_PATH)
  1039. $svgPath.parentElement.classList.add('tnt_logo')
  1040. }
  1041.  
  1042. /**
  1043. * @param {string} str
  1044. * @return {string}
  1045. */
  1046. function dedent(str) {
  1047. str = str.replace(/^[ \t]*\r?\n/, '')
  1048. let indent = /^[ \t]+/m.exec(str)
  1049. if (indent) str = str.replace(new RegExp('^' + indent[0], 'gm'), '')
  1050. return str.replace(/(\r?\n)[ \t]+$/, '$1')
  1051. }
  1052.  
  1053. /**
  1054. * @param {string} name
  1055. * @param {import("./types").Disconnectable[]} observers
  1056. * @param {string?} type
  1057. */
  1058. function disconnectObserver(name, observers, type = 'observer') {
  1059. for (let i = observers.length -1; i >= 0; i--) {
  1060. let observer = observers[i]
  1061. if ('name' in observer && observer.name == name) {
  1062. observer.disconnect()
  1063. observers.splice(i, 1)
  1064. log(`disconnected ${name} ${type}`)
  1065. }
  1066. }
  1067. }
  1068.  
  1069. function disconnectModalObserver(name) {
  1070. disconnectObserver(name, modalObservers)
  1071. }
  1072.  
  1073. function disconnectAllModalObservers() {
  1074. if (modalObservers.length > 0) {
  1075. log(
  1076. `disconnecting ${modalObservers.length} modal observer${s(modalObservers.length)}`,
  1077. modalObservers.map(observer => observer['name'])
  1078. )
  1079. modalObservers.forEach(observer => observer.disconnect())
  1080. modalObservers = []
  1081. }
  1082. }
  1083.  
  1084. function disconnectPageObserver(name) {
  1085. disconnectObserver(name, pageObservers, 'page observer')
  1086. }
  1087.  
  1088. /**
  1089. * @param {string} selector
  1090. * @param {{
  1091. * name?: string
  1092. * stopIf?: () => boolean
  1093. * timeout?: number
  1094. * context?: Document | HTMLElement
  1095. * }?} options
  1096. * @returns {Promise<HTMLElement | null>}
  1097. */
  1098. function getElement(selector, {
  1099. name = null,
  1100. stopIf = null,
  1101. timeout = Infinity,
  1102. context = document,
  1103. } = {}) {
  1104. return new Promise((resolve) => {
  1105. let startTime = Date.now()
  1106. let rafId
  1107. let timeoutId
  1108.  
  1109. function stop($element, reason) {
  1110. if ($element == null) {
  1111. warn(`stopped waiting for ${name || selector} after ${reason}`)
  1112. }
  1113. else if (Date.now() > startTime) {
  1114. log(`${name || selector} appeared after ${Date.now() - startTime}ms`)
  1115. }
  1116. if (rafId) {
  1117. cancelAnimationFrame(rafId)
  1118. }
  1119. if (timeoutId) {
  1120. clearTimeout(timeoutId)
  1121. }
  1122. resolve($element)
  1123. }
  1124.  
  1125. if (timeout !== Infinity) {
  1126. timeoutId = setTimeout(stop, timeout, null, `${timeout}ms timeout`)
  1127. }
  1128.  
  1129. function queryElement() {
  1130. let $element = context.querySelector(selector)
  1131. if ($element) {
  1132. stop($element)
  1133. }
  1134. else if (stopIf?.() === true) {
  1135. stop(null, 'stopIf condition met')
  1136. }
  1137. else {
  1138. rafId = requestAnimationFrame(queryElement)
  1139. }
  1140. }
  1141.  
  1142. queryElement()
  1143. })
  1144. }
  1145.  
  1146. /**
  1147. * Gets cached user info from React state.
  1148. * @returns {import("./types").UserInfoObject}
  1149. */
  1150. function getUserInfo() {
  1151. /** @type {import("./types").UserInfoObject} */
  1152. let userInfo = {}
  1153. let reactRootContainer = ($reactRoot?.wrappedJSObject ? $reactRoot.wrappedJSObject : $reactRoot)?._reactRootContainer
  1154. if (reactRootContainer) {
  1155. let userEntities = reactRootContainer?._internalRoot?.current?.memoizedState?.element?.props?.children?.props?.store?.getState()?.entities?.users?.entities
  1156. if (userEntities) {
  1157. for (let user of Object.values(userEntities)) {
  1158. userInfo[user.screen_name] = {following: user.following, followedBy: user.followed_by, followersCount: user.followers_count}
  1159. }
  1160. } else {
  1161. warn('user entities not found')
  1162. }
  1163. } else {
  1164. warn('React root container not found')
  1165. }
  1166. return userInfo
  1167. }
  1168.  
  1169. function log(...args) {
  1170. if (debug) {
  1171. console.log(`${currentPage ? `(${
  1172. currentPage.length < 70 ? currentPage : currentPage.slice(0, 70) + '…'
  1173. })` : ''}`, ...args)
  1174. }
  1175. }
  1176.  
  1177. function warn(...args) {
  1178. if (debug) {
  1179. console.log(`❗ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1180. }
  1181. }
  1182.  
  1183. function error(...args) {
  1184. console.log(`❌ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1185. }
  1186.  
  1187. /**
  1188. * @param {() => boolean} condition
  1189. * @returns {() => boolean}
  1190. */
  1191. function not(condition) {
  1192. return () => !condition()
  1193. }
  1194.  
  1195. /**
  1196. * Convenience wrapper for the MutationObserver API - the callback is called
  1197. * immediately to support using an observer and its options as a trigger for any
  1198. * change, without looking at MutationRecords.
  1199. * @param {Node} $element
  1200. * @param {MutationCallback} callback
  1201. * @param {string} name
  1202. * @param {MutationObserverInit} options
  1203. * @return {import("./types").NamedMutationObserver}
  1204. */
  1205. function observeElement($element, callback, name = '', options = {childList: true}) {
  1206. if (name) {
  1207. if (options.childList && callback.length > 0) {
  1208. log(`observing ${name}`, $element)
  1209. } else {
  1210. log (`observing ${name}`)
  1211. }
  1212. }
  1213.  
  1214. let observer = new MutationObserver(callback)
  1215. callback([], observer)
  1216. observer.observe($element, options)
  1217. observer['name'] = name
  1218. return observer
  1219. }
  1220.  
  1221. /**
  1222. * @param {string} page
  1223. * @returns {() => boolean}
  1224. */
  1225. function pageIsNot(page) {
  1226. return () => page != currentPage
  1227. }
  1228.  
  1229. /**
  1230. * @param {string} path
  1231. * @returns {() => boolean}
  1232. */
  1233. function pathIsNot(path) {
  1234. return () => path != currentPath
  1235. }
  1236.  
  1237. /**
  1238. * @param {number} n
  1239. * @returns {string}
  1240. */
  1241. function s(n) {
  1242. return n == 1 ? '' : 's'
  1243. }
  1244.  
  1245. function storeConfigChanges(changes) {
  1246. window.postMessage({type: 'tntConfigChange', changes})
  1247. }
  1248. //#endregion
  1249.  
  1250. //#region Global observers
  1251. const checkReactNativeStylesheet = (() => {
  1252. /** @type {number} */
  1253. let startTime
  1254.  
  1255. return function checkReactNativeStylesheet() {
  1256. if (startTime == null) {
  1257. startTime = Date.now()
  1258. }
  1259.  
  1260. let $style = /** @type {HTMLStyleElement} */ (document.querySelector('style#react-native-stylesheet'))
  1261. if (!$style) {
  1262. warn('React Native stylesheet not found')
  1263. return
  1264. }
  1265.  
  1266. for (let rule of $style.sheet.cssRules) {
  1267. if (!(rule instanceof CSSStyleRule)) continue
  1268.  
  1269. if (fontFamilyRule == null &&
  1270. rule.style.fontFamily &&
  1271. rule.style.fontFamily.includes('TwitterChirp')) {
  1272. fontFamilyRule = rule
  1273. log('found Chirp fontFamily CSS rule in React Native stylesheet')
  1274. configureFont()
  1275. }
  1276.  
  1277. if (themeColor == null &&
  1278. rule.style.backgroundColor &&
  1279. THEME_COLORS.has(rule.style.backgroundColor)) {
  1280. themeColor = rule.style.backgroundColor
  1281. localStorage.lastThemeColor = themeColor
  1282. log(`found initial theme color in React Native stylesheet: ${themeColor}`)
  1283. configureThemeCss()
  1284. }
  1285. }
  1286.  
  1287. let elapsedTime = Date.now() - startTime
  1288. if (fontFamilyRule == null || themeColor == null) {
  1289. if (elapsedTime < 3000) {
  1290. setTimeout(checkReactNativeStylesheet, 100)
  1291. } else {
  1292. warn(`stopped checking React Native stylesheet after ${elapsedTime}ms`)
  1293. }
  1294. } else {
  1295. log(`finished checking React Native stylesheet in ${elapsedTime}ms`)
  1296. }
  1297. }
  1298. })()
  1299.  
  1300. /**
  1301. * When the "Background" setting is changed in "Customize your view", <body>'s
  1302. * backgroundColor is changed and the app is re-rendered, so we need to
  1303. * re-process the current page.
  1304. */
  1305. function observeBodyBackgroundColor() {
  1306. let lastBackgroundColor = null
  1307.  
  1308. observeElement($body, () => {
  1309. let backgroundColor = $body.style.backgroundColor
  1310. if (backgroundColor == lastBackgroundColor) return
  1311.  
  1312. $body.classList.toggle('Default', backgroundColor == 'rgb(255, 255, 255)')
  1313. $body.classList.toggle('Dim', backgroundColor == 'rgb(21, 32, 43)')
  1314. $body.classList.toggle('LightsOut', backgroundColor == 'rgb(0, 0, 0)')
  1315.  
  1316. if (lastBackgroundColor != null) {
  1317. log('Background setting changed - re-processing current page')
  1318. observePopups()
  1319. processCurrentPage()
  1320. }
  1321. lastBackgroundColor = backgroundColor
  1322. }, '<body> style attribute for background colour changes', {
  1323. attributes: true,
  1324. attributeFilter: ['style']
  1325. })
  1326. }
  1327.  
  1328. /**
  1329. * When the "Color" setting is changed in "Customize your view", the app
  1330. * re-renders from a certain point, so we need to re-process the current page.
  1331. */
  1332. async function observeColor() {
  1333. let $colorRerenderBoundary = await getElement('#react-root > div > div')
  1334.  
  1335. observeElement($colorRerenderBoundary, async () => {
  1336. if (location.pathname != PagePaths.CUSTOMIZE_YOUR_VIEW) return
  1337.  
  1338. let $doneButton = await getElement(desktop ? Selectors.DISPLAY_DONE_BUTTON_DESKTOP : Selectors.DISPLAY_DONE_BUTTON_MOBILE, {
  1339. name: 'Done button',
  1340. stopIf: not(() => location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW),
  1341. })
  1342. if (!$doneButton) return
  1343.  
  1344. let color = getComputedStyle($doneButton).backgroundColor
  1345. if (color == themeColor) return
  1346.  
  1347. log('Color setting changed - re-processing current page')
  1348. themeColor = color
  1349. localStorage.lastThemeColor = color
  1350. configureThemeCss()
  1351. observePopups()
  1352. processCurrentPage()
  1353. }, 'Color change re-render boundary')
  1354. }
  1355.  
  1356. /**
  1357. * When the "Font size" setting is changed in "Customize your view" on desktop,
  1358. * `<html>`'s fontSize is changed and the app is re-rendered.
  1359. */
  1360. const observeHtmlFontSize = (() => {
  1361. /** @type {MutationObserver} */
  1362. let fontSizeObserver
  1363.  
  1364. return function observeHtmlFontSize() {
  1365. if (fontSizeObserver) {
  1366. fontSizeObserver.disconnect()
  1367. fontSizeObserver = null
  1368. }
  1369.  
  1370. if (mobile) return
  1371.  
  1372. let lastOverflow = ''
  1373.  
  1374. fontSizeObserver = observeElement($html, () => {
  1375. if (!$html.style.fontSize) return
  1376.  
  1377. let hasFontSizeChanged = fontSize != null && $html.style.fontSize != fontSize
  1378.  
  1379. if ($html.style.fontSize != fontSize) {
  1380. fontSize = $html.style.fontSize
  1381. log(`<html> fontSize has changed to ${fontSize}`)
  1382. configureNavFontSizeCss()
  1383. }
  1384.  
  1385. // Ignore overflow changes, which happen when a dialog is shown or hidden
  1386. let hasOverflowChanged = $html.style.overflow != lastOverflow
  1387. lastOverflow = $html.style.overflow
  1388. if (!hasFontSizeChanged && hasOverflowChanged) {
  1389. log('ignoring <html> style overflow change')
  1390. return
  1391. }
  1392.  
  1393. // When you switch between the smallest "Font size" options, <html>'s
  1394. // style is updated but the font size is kept the same - re-process just
  1395. // in case.
  1396. if (hasFontSizeChanged ||
  1397. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW && fontSize == '14px') {
  1398. log('<html> style attribute changed, re-processing current page')
  1399. observePopups()
  1400. processCurrentPage()
  1401. }
  1402. }, '<html> style attribute for font size changes', {
  1403. attributes: true,
  1404. attributeFilter: ['style']
  1405. })
  1406. }
  1407. })()
  1408.  
  1409. async function observeDesktopModalTimeline() {
  1410. // Media modals remember if they were previously collapsed, so we could be
  1411. // waiting for the initial timeline to be either rendered or expanded.
  1412. let $initialTimeline = await getElement(Selectors.MODAL_TIMELINE, {
  1413. name: 'initial modal timeline',
  1414. stopIf: () => !isDesktopMediaModalOpen,
  1415. })
  1416.  
  1417. if ($initialTimeline == null) return
  1418.  
  1419. /**
  1420. * @param {HTMLElement} $timeline
  1421. */
  1422. function observeModalTimelineItems($timeline) {
  1423. disconnectModalObserver('modal timeline')
  1424. modalObservers.push(
  1425. observeElement($timeline, () => onIndividualTweetTimelineChange($timeline), 'modal timeline')
  1426. )
  1427.  
  1428. // If other media in the modal is clicked, the timeline is replaced.
  1429. disconnectModalObserver('modal timeline parent')
  1430. modalObservers.push(
  1431. observeElement($timeline.parentElement, (mutations) => {
  1432. mutations.forEach((mutation) => {
  1433. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1434. log('modal timeline replaced')
  1435. disconnectModalObserver('modal timeline')
  1436. modalObservers.push(
  1437. observeElement($newTimeline, () => onIndividualTweetTimelineChange($newTimeline), 'modal timeline')
  1438. )
  1439. })
  1440. })
  1441. }, 'modal timeline parent')
  1442. )
  1443. }
  1444.  
  1445. /**
  1446. * @param {HTMLElement} $timeline
  1447. */
  1448. function observeModalTimeline($timeline) {
  1449. // If the inital timeline doesn't have a style attribute it's a placeholder
  1450. if ($timeline.hasAttribute('style')) {
  1451. observeModalTimelineItems($timeline)
  1452. }
  1453. else {
  1454. log('waiting for modal timeline')
  1455. let startTime = Date.now()
  1456. modalObservers.push(
  1457. observeElement($timeline.parentElement, (mutations) => {
  1458. mutations.forEach((mutation) => {
  1459. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  1460. disconnectModalObserver('modal timeline parent')
  1461. if (Date.now() > startTime) {
  1462. log(`modal timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  1463. }
  1464. observeModalTimelineItems($timeline)
  1465. })
  1466. })
  1467. }, 'modal timeline parent')
  1468. )
  1469. }
  1470. }
  1471.  
  1472. // The modal timeline can be expanded and collapsed
  1473. let $expandedContainer = $initialTimeline.closest('[aria-expanded="true"]')
  1474. modalObservers.push(
  1475. observeElement($expandedContainer.parentElement, async (mutations) => {
  1476. if (mutations.some(mutation => mutation.removedNodes.length > 0)) {
  1477. log('modal timeline collapsed')
  1478. disconnectModalObserver('modal timeline parent')
  1479. disconnectModalObserver('modal timeline')
  1480. }
  1481. else if (mutations.some(mutation => mutation.addedNodes.length > 0)) {
  1482. log('modal timeline expanded')
  1483. let $timeline = await getElement(Selectors.MODAL_TIMELINE, {
  1484. name: 'expanded modal timeline',
  1485. stopIf: () => !isDesktopMediaModalOpen,
  1486. })
  1487. if ($timeline == null) return
  1488. observeModalTimeline($timeline)
  1489. }
  1490. }, 'collapsible modal timeline container')
  1491. )
  1492.  
  1493. observeModalTimeline($initialTimeline)
  1494. }
  1495.  
  1496. const observeFavicon = (() => {
  1497. /** @type {HTMLElement} */
  1498. let $shortcutIcon
  1499. /** @type {MutationObserver} */
  1500. let shortcutIconObserver
  1501.  
  1502. async function observeFavicon() {
  1503. if ($shortcutIcon == null) {
  1504. $shortcutIcon = await getElement('link[rel="shortcut icon"]', {name: 'shortcut icon'})
  1505. }
  1506.  
  1507. if (!config.replaceLogo) {
  1508. if (shortcutIconObserver != null) {
  1509. shortcutIconObserver.disconnect()
  1510. shortcutIconObserver = null
  1511. if ($shortcutIcon.getAttribute('href').startsWith('data:')) {
  1512. $shortcutIcon.setAttribute('href', `//abs.twimg.com/favicons/twitter${currentNotificationCount ? '-pip' : ''}.3.ico`)
  1513. }
  1514. }
  1515. return
  1516. }
  1517.  
  1518. shortcutIconObserver = observeElement($shortcutIcon, () => {
  1519. let href = $shortcutIcon.getAttribute('href')
  1520. if (href.startsWith('data:')) return
  1521. $shortcutIcon.setAttribute('href', href.includes('pip') ? Images.TWITTER_PIP_FAVICON : Images.TWITTER_FAVICON)
  1522. }, 'shortcut icon href', {
  1523. attributes: true,
  1524. attributeFilter: ['href']
  1525. })
  1526. }
  1527.  
  1528. observeFavicon.updatePip = function(showPip) {
  1529. if (!$shortcutIcon) return
  1530. let icon = showPip ? Images.TWITTER_PIP_FAVICON : Images.TWITTER_FAVICON
  1531. if ($shortcutIcon.getAttribute('href') != icon) {
  1532. $shortcutIcon.setAttribute('href', icon)
  1533. }
  1534. }
  1535.  
  1536. return observeFavicon
  1537. })()
  1538.  
  1539. /**
  1540. * Twitter displays popups in the #layers element. It also reuses open popups
  1541. * in certain cases rather than creating one from scratch, so we also need to
  1542. * deal with nested popups, e.g. if you hover over the caret menu in a Tweet, a
  1543. * popup will be created to display a "More" tootip and clicking to open the
  1544. * menu will create a nested element in the existing popup, whereas clicking the
  1545. * caret quickly without hovering over it will display the menu in new popup.
  1546. * Use of nested popups can also differ between desktop and mobile, so features
  1547. * need to be mindful of that.
  1548. */
  1549. const observePopups = (() => {
  1550. /** @type {MutationObserver} */
  1551. let popupObserver
  1552. /** @type {WeakMap<HTMLElement, {disconnect()}>} */
  1553. let nestedObservers = new WeakMap()
  1554.  
  1555. return async function observePopups() {
  1556. if (popupObserver) {
  1557. popupObserver.disconnect()
  1558. popupObserver = null
  1559. }
  1560.  
  1561. let $layers = await getElement('#layers', {
  1562. name: 'layers',
  1563. })
  1564.  
  1565. // There can be only one
  1566. if (popupObserver) {
  1567. popupObserver.disconnect()
  1568. }
  1569.  
  1570. popupObserver = observeElement($layers, (mutations) => {
  1571. mutations.forEach((mutation) => {
  1572. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1573. let nestedObserver = onPopup($el)
  1574. if (nestedObserver) {
  1575. nestedObservers.set($el, nestedObserver)
  1576. }
  1577. })
  1578. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1579. if (nestedObservers.has($el)) {
  1580. nestedObservers.get($el).disconnect()
  1581. nestedObservers.delete($el)
  1582. }
  1583. })
  1584. })
  1585. }, 'popup container')
  1586. }
  1587. })()
  1588.  
  1589. async function observeTitle() {
  1590. let $title = await getElement('title', {name: '<title>'})
  1591. observeElement($title, () => {
  1592. let title = $title.textContent
  1593. if (config.replaceLogo && (ltr ? /X$/ : /^(?:\(\d+\+?\) )?X/).test(title)) {
  1594. document.title = title.replace(ltr ? /X$/ : 'X', getString('TWITTER'))
  1595. return
  1596. }
  1597. if (observingPageChanges) {
  1598. onTitleChange(title)
  1599. }
  1600. }, '<title>')
  1601. }
  1602. //#endregion
  1603.  
  1604. //#region Page observers
  1605. /**
  1606. * If a profile is blocked its media box won't appear, add a `Blocked` class to
  1607. * `<body>` to hide sidebar content.
  1608. * @param {string} currentPage
  1609. */
  1610. async function observeProfileBlockedStatus(currentPage) {
  1611. let $buttonContainer = await getElement(`[data-testid="userActions"] ~ [data-testid="placementTracking"], a[href="${PagePaths.PROFILE_SETTINGS}"]`, {
  1612. name: 'Follow / Unblock button container or Edit profile button',
  1613. stopIf: pageIsNot(currentPage),
  1614. })
  1615. if ($buttonContainer == null) return
  1616.  
  1617. if ($buttonContainer.hasAttribute('href')) {
  1618. log('on own profile page')
  1619. $body.classList.remove('Blocked')
  1620. return
  1621. }
  1622.  
  1623. pageObservers.push(
  1624. observeElement($buttonContainer, () => {
  1625. let isBlocked = (/** @type {HTMLElement} */ ($buttonContainer.querySelector('[role="button"]'))?.dataset.testid ?? '').endsWith('unblock')
  1626. $body.classList.toggle('Blocked', isBlocked)
  1627. }, 'Follow / Unblock button container')
  1628. )
  1629. }
  1630.  
  1631. /**
  1632. * If an account has never tweeted any media, add a `NoMedia` class to `<body>`
  1633. * to hide the "You might like" section which will appear where the media box
  1634. * would have been.
  1635. * @param {string} currentPage
  1636. */
  1637. async function observeProfileSidebar(currentPage) {
  1638. let $sidebarContent = await getElement(Selectors.SIDEBAR_WRAPPERS, {
  1639. name: 'profile sidebar content container',
  1640. stopIf: pageIsNot(currentPage),
  1641. })
  1642. if ($sidebarContent == null) return
  1643.  
  1644. let sidebarContentObserver = observeElement($sidebarContent, () => {
  1645. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1646. }, 'profile sidebar content container')
  1647. pageObservers.push(sidebarContentObserver)
  1648.  
  1649. // On initial appearance, the sidebar is injected with static HTML with
  1650. // spinner placeholders, which gets replaced. When this happens we need to
  1651. // observe the new content container instead.
  1652. let $sidebarContentParent = $sidebarContent.parentElement
  1653. pageObservers.push(
  1654. observeElement($sidebarContentParent, (mutations) => {
  1655. let sidebarContentReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($sidebarContent))
  1656. if (sidebarContentReplaced) {
  1657. log('profile sidebar content container replaced, observing new container')
  1658. sidebarContentObserver.disconnect()
  1659. pageObservers.splice(pageObservers.indexOf(sidebarContentObserver), 1)
  1660. $sidebarContent = /** @type {HTMLElement} */ ($sidebarContentParent.firstElementChild)
  1661. pageObservers.push(
  1662. observeElement($sidebarContent, () => {
  1663. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1664. }, 'sidebar content container')
  1665. )
  1666. }
  1667. }, 'sidebar content container parent')
  1668. )
  1669. }
  1670.  
  1671. async function observeSidebar() {
  1672. let $primaryColumn = await getElement(Selectors.PRIMARY_COLUMN, {
  1673. name: 'primary column'
  1674. })
  1675. let $sidebarContainer = $primaryColumn.parentElement
  1676. pageObservers.push(
  1677. observeElement($sidebarContainer, () => {
  1678. let $sidebar = $sidebarContainer.querySelector(Selectors.SIDEBAR)
  1679. log(`sidebar ${$sidebar ? 'appeared' : 'disappeared'}`)
  1680. $body.classList.toggle('Sidebar', Boolean($sidebar))
  1681. if ($sidebar && config.twitterBlueChecks != 'ignore' && !isOnSearchPage() && !isOnExplorePage()) {
  1682. observeSearchForm()
  1683. }
  1684. }, 'sidebar container')
  1685. )
  1686. }
  1687.  
  1688. async function observeSearchForm() {
  1689. let $searchForm = await getElement('form[role="search"]', {
  1690. name: 'search form',
  1691. stopIf: pageIsNot(currentPage),
  1692. // The sidebar on Profile pages can be really slow
  1693. timeout: 2000,
  1694. })
  1695. if (!$searchForm) return
  1696. let $results = /** @type {HTMLElement} */ ($searchForm.lastElementChild)
  1697. pageObservers.push(
  1698. observeElement($results, () => {
  1699. processBlueChecks($results)
  1700. }, 'search results', {childList: true, subtree: true})
  1701. )
  1702. }
  1703.  
  1704. /**
  1705. * @param {string} page
  1706. * @param {import("./types").TimelineOptions?} options
  1707. */
  1708. async function observeTimeline(page, options = {}) {
  1709. let {
  1710. isTabbed = false,
  1711. onTabChanged = null,
  1712. onTimelineAppeared = null,
  1713. onTimelineItemsChanged = onTimelineChange,
  1714. tabbedTimelineContainerSelector = null,
  1715. timelineSelector = Selectors.TIMELINE,
  1716. } = options
  1717.  
  1718. let $timeline = await getElement(timelineSelector, {
  1719. name: 'initial timeline',
  1720. stopIf: pageIsNot(page),
  1721. })
  1722.  
  1723. if ($timeline == null) return
  1724.  
  1725. /**
  1726. * @param {HTMLElement} $timeline
  1727. */
  1728. function observeTimelineItems($timeline) {
  1729. disconnectPageObserver('timeline')
  1730. pageObservers.push(
  1731. observeElement($timeline, () => onTimelineItemsChanged($timeline, page, options), 'timeline')
  1732. )
  1733. onTimelineAppeared?.()
  1734. if (isTabbed) {
  1735. // When a tab which has been viewed before is revisited, the timeline is
  1736. // replaced.
  1737. disconnectPageObserver('timeline parent')
  1738. pageObservers.push(
  1739. observeElement($timeline.parentElement, (mutations) => {
  1740. mutations.forEach((mutation) => {
  1741. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1742. disconnectPageObserver('timeline')
  1743. log('tab changed')
  1744. onTabChanged?.()
  1745. pageObservers.push(
  1746. observeElement($newTimeline, () => onTimelineItemsChanged($newTimeline, page, options), 'timeline')
  1747. )
  1748. })
  1749. })
  1750. }, 'timeline parent')
  1751. )
  1752. }
  1753. }
  1754.  
  1755. // If the inital timeline doesn't have a style attribute it's a placeholder
  1756. if ($timeline.hasAttribute('style')) {
  1757. observeTimelineItems($timeline)
  1758. }
  1759. else {
  1760. log('waiting for timeline')
  1761. let startTime = Date.now()
  1762. pageObservers.push(
  1763. observeElement($timeline.parentElement, (mutations) => {
  1764. mutations.forEach((mutation) => {
  1765. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  1766. disconnectPageObserver('timeline parent')
  1767. if (Date.now() > startTime) {
  1768. log(`timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  1769. }
  1770. observeTimelineItems($timeline)
  1771. })
  1772. })
  1773. }, 'timeline parent')
  1774. )
  1775. }
  1776.  
  1777. // On some tabbed timeline pages, the first time a new tab is navigated to,
  1778. // the element containing the timeline is replaced with a loading spinner.
  1779. if (isTabbed && tabbedTimelineContainerSelector) {
  1780. let $tabbedTimelineContainer = document.querySelector(tabbedTimelineContainerSelector)
  1781. if ($tabbedTimelineContainer) {
  1782. let waitingForNewTimeline = false
  1783. pageObservers.push(
  1784. observeElement($tabbedTimelineContainer, async (mutations) => {
  1785. // This is going to fire twice on a new tab, as the spinner is added
  1786. // then replaced with the new timeline element.
  1787. if (!mutations.some(mutation => mutation.addedNodes.length > 0) || waitingForNewTimeline) return
  1788.  
  1789. waitingForNewTimeline = true
  1790. let $newTimeline = await getElement(timelineSelector, {
  1791. name: 'new timeline',
  1792. stopIf: pageIsNot(page),
  1793. })
  1794. waitingForNewTimeline = false
  1795. if (!$newTimeline) return
  1796.  
  1797. log('tab changed')
  1798. onTabChanged?.()
  1799. observeTimelineItems($newTimeline)
  1800. }, 'tabbed timeline container')
  1801. )
  1802. } else {
  1803. warn('tabbed timeline container not found')
  1804. }
  1805. }
  1806. }
  1807.  
  1808. /**
  1809. * @param {HTMLElement} $context
  1810. * @param {string} initialPath
  1811. */
  1812. async function observeUserListTimeline($context, initialPath) {
  1813. let $timeline = await getElement('h1[id^="accessible-list"] + div > div > div > div', {
  1814. context: $context,
  1815. name: 'user list timeline',
  1816. stopIf: not(() => initialPath == location.pathname),
  1817. })
  1818. if (!$timeline) return
  1819.  
  1820. modalObservers.push(
  1821. observeElement($timeline, () => {
  1822. processBlueChecks($timeline)
  1823. }, 'user list timeline')
  1824. )
  1825. }
  1826. //#endregion
  1827.  
  1828. //#region Tweak functions
  1829. /**
  1830. * Add an "Add muted word" menu item after the given link which takes you
  1831. * straight to entering a new muted word (by clicking its way through all the
  1832. * individual screens!).
  1833. * @param {HTMLElement} $link
  1834. * @param {string} linkSelector
  1835. */
  1836. async function addAddMutedWordMenuItem($link, linkSelector) {
  1837. log('adding "Add muted word" menu item')
  1838.  
  1839. // Wait for the dropdown to appear on desktop
  1840. if (desktop) {
  1841. $link = await getElement(`#layers div[data-testid="Dropdown"] ${linkSelector}`, {
  1842. name: 'rendered menu item',
  1843. timeout: 100,
  1844. })
  1845. if (!$link) return
  1846. }
  1847.  
  1848. let $addMutedWord = /** @type {HTMLElement} */ ($link.parentElement.cloneNode(true))
  1849. $addMutedWord.classList.add('tnt_menu_item')
  1850. $addMutedWord.querySelector('a').href = PagePaths.ADD_MUTED_WORD
  1851. $addMutedWord.querySelector('span').textContent = getString('ADD_MUTED_WORD')
  1852. $addMutedWord.querySelector('svg').innerHTML = Svgs.MUTE
  1853. $addMutedWord.addEventListener('click', (e) => {
  1854. e.preventDefault()
  1855. addMutedWord()
  1856. })
  1857. $link.parentElement.insertAdjacentElement('afterend', $addMutedWord)
  1858. }
  1859.  
  1860. function addCaretMenuListenerForQuoteTweet($tweet) {
  1861. let $caret = /** @type {HTMLElement} */ ($tweet.querySelector('[data-testid="caret"]'))
  1862. if ($caret && !$caret.dataset.tweakNewTwitterListener) {
  1863. $caret.addEventListener('click', () => {
  1864. quotedTweet = getQuotedTweetDetails($tweet, {getText: true})
  1865. })
  1866. $caret.dataset.tweakNewTwitterListener = 'true'
  1867. }
  1868. }
  1869.  
  1870. /**
  1871. * Add a "Mute this conversation" menu item to a Quote Tweet's menu.
  1872. * @param {HTMLElement} $blockMenuItem
  1873. */
  1874. async function addMuteQuotesMenuItem($blockMenuItem) {
  1875. log('adding "Mute this conversation" menu item')
  1876.  
  1877. // Wait for the menu to render properly on desktop
  1878. if (desktop) {
  1879. $blockMenuItem = await getElement(`:scope > div > div > div > ${Selectors.BLOCK_MENU_ITEM}`, {
  1880. context: $blockMenuItem.parentElement,
  1881. name: 'rendered block menu item',
  1882. timeout: 100,
  1883. })
  1884. if (!$blockMenuItem) return
  1885. }
  1886.  
  1887. let $muteQuotes = /** @type {HTMLElement} */ ($blockMenuItem.previousElementSibling.cloneNode(true))
  1888. $muteQuotes.classList.add('tnt_menu_item')
  1889. $muteQuotes.querySelector('span').textContent = getString('MUTE_THIS_CONVERSATION')
  1890. $muteQuotes.addEventListener('click', (e) => {
  1891. e.preventDefault()
  1892. log('muting quotes of a tweet', quotedTweet)
  1893. config.mutedQuotes = config.mutedQuotes.concat(quotedTweet)
  1894. storeConfigChanges({mutedQuotes: config.mutedQuotes})
  1895. processCurrentPage()
  1896. // Dismiss the menu
  1897. let $menuLayer = /** @type {HTMLElement} */ ($blockMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  1898. if (!$menuLayer) {
  1899. log('could not find menu layer to dismiss menu')
  1900. }
  1901. $menuLayer?.click()
  1902. })
  1903.  
  1904. $blockMenuItem.insertAdjacentElement('beforebegin', $muteQuotes)
  1905. }
  1906.  
  1907. async function addMutedWord() {
  1908. if (!document.querySelector('a[href="/settings')) {
  1909. let $settingsAndSupport = /** @type {HTMLElement} */ (document.querySelector('[data-testid="settingsAndSupport"]'))
  1910. $settingsAndSupport?.click()
  1911. }
  1912.  
  1913. for (let path of [
  1914. '/settings',
  1915. '/settings/privacy_and_safety',
  1916. '/settings/mute_and_block',
  1917. '/settings/muted_keywords',
  1918. '/settings/add_muted_keyword',
  1919. ]) {
  1920. let $link = await getElement(`a[href="${path}"]`, {timeout: 500})
  1921. if (!$link) return
  1922. $link.click()
  1923. }
  1924. let $input = await getElement('input[name="keyword"]')
  1925. setTimeout(() => $input.focus(), 100)
  1926. }
  1927.  
  1928. /**
  1929. * Add a "Turn on/off Retweets" menu item to a List's menu.
  1930. * @param {HTMLElement} $switchMenuItem
  1931. */
  1932. async function addToggleListRetweetsMenuItem($switchMenuItem) {
  1933. log('adding "Turn on/off Retweets" menu item')
  1934.  
  1935. // Wait for the menu to render properly on desktop
  1936. if (desktop) {
  1937. $switchMenuItem = await getElement(':scope > div > div > div > [role="menuitem"]', {
  1938. context: $switchMenuItem.parentElement,
  1939. name: 'rendered switch menu item',
  1940. timeout: 100,
  1941. })
  1942. if (!$switchMenuItem) return
  1943. }
  1944.  
  1945. let $toggleRetweets = /** @type {HTMLElement} */ ($switchMenuItem.cloneNode(true))
  1946. $toggleRetweets.classList.add('tnt_menu_item')
  1947. $toggleRetweets.querySelector('span').textContent = getString(`TURN_${config.listRetweets == 'ignore' ? 'OFF' : 'ON'}_RETWEETS`)
  1948. $toggleRetweets.querySelector('svg').innerHTML = config.listRetweets == 'ignore' ? Svgs.RETWEETS_OFF : Svgs.RETWEET
  1949. $toggleRetweets.querySelector(':scope > div:last-child > div:last-child')?.remove()
  1950. $toggleRetweets.addEventListener('click', (e) => {
  1951. e.preventDefault()
  1952. log('toggling list retweets')
  1953. config.listRetweets = config.listRetweets == 'ignore' ? 'hide' : 'ignore'
  1954. storeConfigChanges({listRetweets: config.listRetweets})
  1955. processCurrentPage()
  1956. // Dismiss the menu
  1957. let $menuLayer = /** @type {HTMLElement} */ ($switchMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  1958. if (!$menuLayer) {
  1959. log('could not find menu layer to dismiss menu')
  1960. }
  1961. $menuLayer?.click()
  1962. })
  1963.  
  1964. $switchMenuItem.insertAdjacentElement('beforebegin', $toggleRetweets)
  1965. }
  1966.  
  1967. /**
  1968. * Redirects away from the home timeline if we're on it and it's been disabled.
  1969. * @returns {boolean} `true` if redirected as a result of this call
  1970. */
  1971. function checkforDisabledHomeTimeline() {
  1972. if (config.disableHomeTimeline && location.pathname == '/home') {
  1973. log(`home timeline disabled, redirecting to /${config.disabledHomeTimelineRedirect}`)
  1974. let primaryNavSelector = desktop ? Selectors.PRIMARY_NAV_DESKTOP : Selectors.PRIMARY_NAV_MOBILE
  1975. ;/** @type {HTMLElement} */ (
  1976. document.querySelector(`${primaryNavSelector} a[href="/${config.disabledHomeTimelineRedirect}"]`)
  1977. ).click()
  1978. return true
  1979. }
  1980. }
  1981.  
  1982. const configureCss = (() => {
  1983. let $style
  1984.  
  1985. return function configureCss() {
  1986. if ($style == null) {
  1987. $style = addStyle('features')
  1988. }
  1989. let cssRules = []
  1990. let hideCssSelectors = []
  1991. let menuRole = `[role="${desktop ? 'menu' : 'dialog'}"]`
  1992.  
  1993. // Hover colours for custom menu items
  1994. cssRules.push(`
  1995. body.Default .tnt_menu_item:hover { background-color: rgb(247, 249, 249) !important; }
  1996. body.Dim .tnt_menu_item:hover { background-color: rgb(30, 39, 50) !important; }
  1997. body.LightsOut .tnt_menu_item:hover { background-color: rgb(22, 24, 28) !important; }
  1998. `)
  1999.  
  2000. if (config.alwaysUseLatestTweets && config.hideForYouTimeline) {
  2001. cssRules.push(`
  2002. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child {
  2003. flex: 0;
  2004. }
  2005. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child > a {
  2006. display: none;
  2007. }
  2008. `)
  2009. }
  2010. if (config.disableTweetTextFormatting) {
  2011. cssRules.push(`
  2012. div[data-testid="tweetText"] span {
  2013. font-style: normal;
  2014. font-weight: normal;
  2015. }
  2016. `)
  2017. }
  2018. if (config.dropdownMenuFontWeight) {
  2019. cssRules.push(`
  2020. [data-testid="${desktop ? 'Dropdown' : 'sheetDialog'}"] [role="menuitem"] [dir] {
  2021. font-weight: normal;
  2022. }
  2023. `)
  2024. }
  2025. if (config.hideAnalyticsNav) {
  2026. hideCssSelectors.push(`${menuRole} a[href*="analytics.twitter.com"]`)
  2027. }
  2028. if (config.hideBookmarkButton) {
  2029. hideCssSelectors.push(
  2030. // Under individual tweets
  2031. '[data-testid="tweet"][tabindex="-1"] [role="group"][id^="id__"] > div:nth-child(4)',
  2032. )
  2033. }
  2034. if (config.hideBookmarksNav) {
  2035. hideCssSelectors.push(`${menuRole} a[href$="/bookmarks"]`)
  2036. }
  2037. if (config.hideCommunitiesNav) {
  2038. hideCssSelectors.push(`${menuRole} a[href$="/communities"]`)
  2039. }
  2040. if (config.hideShareTweetButton) {
  2041. hideCssSelectors.push(
  2042. // Under timeline tweets
  2043. `[data-testid="tweet"][tabindex="0"] [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2044. // Under individual tweets
  2045. `[data-testid="tweet"][tabindex="-1"] [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2046. )
  2047. }
  2048. if (config.hideSubscriptions) {
  2049. hideCssSelectors.push(
  2050. // Subscribe buttons in profile (multiple locations)
  2051. 'body.Profile [role="button"][style*="border-color: rgb(201, 54, 204)"]',
  2052. // Subscriptions count in profile
  2053. 'body.Profile a[href$="/creator-subscriptions/subscriptions"]',
  2054. // Subs tab in profile (3rd of 5, or 6 if they have Highlights)
  2055. 'body.Profile [data-testid="ScrollSnap-List"] > [role="presentation"]:nth-child(3):is(:nth-last-child(3), :nth-last-child(4))',
  2056. // Subscribe button in focused tweet
  2057. '[data-testid="tweet"][tabindex="-1"] [data-testid$="-subscribe"]',
  2058. // "Subscribe to" dropdown item (desktop)
  2059. '[data-testid="Dropdown"] > [data-testid="subscribe"]',
  2060. // "Subscribe to" menu item (mobile)
  2061. '[data-testid="sheetDialog"] > [data-testid="subscribe"]',
  2062. // "Subscriber" indicator in replies from subscribers
  2063. 'body.Default [data-testid="tweet"] [data-testid="userFollowIndicator"][style*="color: rgb(141, 32, 144)"]',
  2064. 'body:is(.Dim, .LightsOut) [data-testid="tweet"] [data-testid="userFollowIndicator"][style*="color: rgb(223, 130, 224)"]',
  2065. // Monetization and Subscriptions items in Settings
  2066. 'body.Settings a[href="/settings/monetization"]',
  2067. 'body.Settings a[href="/settings/manage_subscriptions"]',
  2068. )
  2069. }
  2070. if (config.hideHelpCenterNav) {
  2071. hideCssSelectors.push(`${menuRole} a[href*="support.twitter.com"]`)
  2072. }
  2073. if (config.hideMetrics) {
  2074. configureHideMetricsCss(cssRules, hideCssSelectors)
  2075. }
  2076. if (config.hideMonetizationNav) {
  2077. hideCssSelectors.push(`${menuRole} a[href$="/settings/monetization"]`)
  2078. }
  2079. if (config.hideTweetAnalyticsLinks) {
  2080. hideCssSelectors.push('[data-testid="analyticsButton"]')
  2081. }
  2082. if (config.hideTwitterAdsNav) {
  2083. hideCssSelectors.push(`${menuRole} a[href*="ads.twitter.com"]`)
  2084. }
  2085. if (config.hideTwitterBlueUpsells) {
  2086. hideCssSelectors.push(
  2087. // Twitter Blue menu item
  2088. `${menuRole} a[href$="/i/blue_sign_up"]`,
  2089. // "Highlight on your profile" on your tweets
  2090. '[role="menuitem"][data-testid="highlightUpsell"]',
  2091. // "Edit with Twitter Blue" on recent tweets
  2092. '[role="menuitem"][data-testid="editWithTwitterBlue"]',
  2093. // Twitter Blue item in Settings
  2094. 'body.Settings a[href="/i/blue_sign_up"]',
  2095. // "Highlight your best content instead" on the pin modal
  2096. '.PinModal [data-testid="sheetDialog"] > div > div:last-child > div > div > div:first-child',
  2097. // Highlight button on the pin modal
  2098. '.PinModal [data-testid="sheetDialog"] [role="button"]:first-child:nth-last-child(3)',
  2099. )
  2100. // Allow Pin and Cancel buttons go to max-width on the pin modal
  2101. cssRules.push(`
  2102. .PinModal [data-testid="sheetDialog"] > div > div:last-child > div > div {
  2103. width: 100%;
  2104. margin-top: 0;
  2105. padding-left: 32px;
  2106. padding-right: 32px;
  2107. }
  2108. `)
  2109. }
  2110. if (config.hideVerifiedNotificationsTab) {
  2111. hideCssSelectors.push(
  2112. `body.Notifications ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:nth-child(2)`
  2113. )
  2114. }
  2115. if (config.hideViews) {
  2116. hideCssSelectors.push(
  2117. // "Views" under individual tweets
  2118. '[data-testid="tweet"][tabindex="-1"] div[dir] + div[aria-hidden="true"]:nth-child(2):nth-last-child(2)',
  2119. '[data-testid="tweet"][tabindex="-1"] div[dir] + div[aria-hidden="true"]:nth-child(2):nth-last-child(2) + div[dir]:last-child'
  2120. )
  2121. }
  2122. if (config.hideWhoToFollowEtc) {
  2123. hideCssSelectors.push(`body.Profile ${Selectors.PRIMARY_COLUMN} aside[role="complementary"]`)
  2124. }
  2125. if (config.reducedInteractionMode) {
  2126. hideCssSelectors.push(
  2127. '[data-testid="tweet"] [role="group"]',
  2128. 'body.Tweet a:is([href$="/retweets"], [href$="/likes"])',
  2129. 'body.Tweet [data-testid="tweet"] + div > div [role="group"]',
  2130. )
  2131. }
  2132. if (config.tweakQuoteTweetsPage) {
  2133. // Hide the quoted tweet, which is repeated in every quote tweet
  2134. hideCssSelectors.push('body.QuoteTweets [data-testid="tweet"] [aria-labelledby] > div:last-child')
  2135. }
  2136. if (config.twitterBlueChecks == 'hide') {
  2137. hideCssSelectors.push('.tnt_blue_check')
  2138. }
  2139. if (config.twitterBlueChecks == 'replace') {
  2140. cssRules.push(`
  2141. :is(${Selectors.VERIFIED_TICK}, svg[data-testid="verificationBadge"]).tnt_blue_check path {
  2142. d: path("${Svgs.BLUE_LOGO_PATH}");
  2143. }
  2144. `)
  2145. }
  2146.  
  2147. // Hide "Creator Studio" if all its contents are hidden
  2148. if (config.hideAnalyticsNav) {
  2149. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(1)`)
  2150. }
  2151. // Hide "Professional Tools" if all its contents are hidden
  2152. if (config.hideTwitterAdsNav) {
  2153. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(2)`)
  2154. }
  2155.  
  2156. if (shouldShowSeparatedTweetsTab()) {
  2157. cssRules.push(`
  2158. body.Default {
  2159. --active-tab-text: rgb(15, 20, 25);
  2160. --inactive-tab-text: rgb(83, 100, 113);
  2161. --tab-border: rgb(239, 243, 244);
  2162. --tab-hover: rgba(15, 20, 25, 0.1);
  2163. }
  2164. body.Dim {
  2165. --active-tab-text: rgb(247, 249, 249);
  2166. --inactive-tab-text: rgb(139, 152, 165);
  2167. --tab-border: rgb(56, 68, 77);
  2168. --tab-hover: rgba(247, 249, 249, 0.1);
  2169. }
  2170. body.LightsOut {
  2171. --active-tab-text: rgb(247, 249, 249);
  2172. --inactive-tab-text: rgb(113, 118, 123);
  2173. --tab-border: rgb(47, 51, 54);
  2174. --tab-hover: rgba(231, 233, 234, 0.1);
  2175. }
  2176.  
  2177. /* Tabbed timeline */
  2178. body.Desktop #tnt_separated_tweets_tab:hover,
  2179. body.Mobile:not(.SeparatedTweets) #tnt_separated_tweets_tab:hover,
  2180. body.Mobile #tnt_separated_tweets_tab:active {
  2181. background-color: var(--tab-hover);
  2182. }
  2183. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div,
  2184. body.TabbedTimeline.SeparatedTweets ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:not(#tnt_separated_tweets_tab) > a > div > div {
  2185. font-weight: normal !important;
  2186. color: var(--inactive-tab-text) !important;
  2187. }
  2188. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div {
  2189. font-weight: bold;
  2190. color: var(--active-tab-text); !important;
  2191. }
  2192. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div > div,
  2193. body.TabbedTimeline.SeparatedTweets ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:not(#tnt_separated_tweets_tab) > a > div > div > div {
  2194. height: 0 !important;
  2195. }
  2196. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2197. height: 4px !important;
  2198. min-width: 56px;
  2199. width: 100%;
  2200. position: absolute;
  2201. bottom: 0;
  2202. border-radius: 9999px;
  2203. }
  2204. `)
  2205. }
  2206.  
  2207. if (desktop) {
  2208. if (config.navDensity == 'comfortable' || config.navDensity == 'compact') {
  2209. cssRules.push(`
  2210. header nav > a,
  2211. header nav > div[data-testid="AppTabBar_More_Menu"] {
  2212. padding-top: 0 !important;
  2213. padding-bottom: 0 !important;
  2214. }
  2215. `)
  2216. }
  2217. if (config.navDensity == 'compact') {
  2218. cssRules.push(`
  2219. header nav > a > div,
  2220. header nav > div[data-testid="AppTabBar_More_Menu"] > div {
  2221. padding-top: 6px !important;
  2222. padding-bottom: 6px !important;
  2223. }
  2224. `)
  2225. }
  2226. if (config.hideHomeHeading) {
  2227. hideCssSelectors.push(`body.TabbedTimeline ${Selectors.DESKTOP_TIMELINE_HEADER} > div:first-child > div:first-child`)
  2228. }
  2229. if (config.hideSeeNewTweets) {
  2230. hideCssSelectors.push(`body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div > div:first-child > div[style^="transform"]`)
  2231. }
  2232. if (config.disableHomeTimeline) {
  2233. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/home"]`)
  2234. }
  2235. if (config.fullWidthContent) {
  2236. cssRules.push(`
  2237. /* Use full width when the sidebar is visible */
  2238. body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN},
  2239. body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2240. max-width: 990px;
  2241. }
  2242. /* Make the "What's happening" input keep its original width */
  2243. body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div:first-child > div:nth-of-type(3) div[role="progressbar"] + div {
  2244. max-width: 598px;
  2245. }
  2246. /* Use full width when the sidebar is not visible */
  2247. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} header[role="banner"] {
  2248. flex-grow: 0;
  2249. }
  2250. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} main[role="main"] > div {
  2251. width: 100%;
  2252. }
  2253. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} {
  2254. max-width: unset;
  2255. width: 100%;
  2256. }
  2257. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:first-child div,
  2258. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2259. max-width: unset;
  2260. }
  2261. `)
  2262. if (!config.fullWidthMedia) {
  2263. // Make media & cards keep their original width
  2264. cssRules.push(`
  2265. body${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} ${Selectors.TWEET} > div > div > div:nth-of-type(2) > div:nth-of-type(2) > div[id][aria-labelledby]:not(:empty) {
  2266. max-width: 504px;
  2267. }
  2268. `)
  2269. }
  2270. // Hide the sidebar when present
  2271. hideCssSelectors.push(`body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.SIDEBAR}`)
  2272. }
  2273. if (config.hideAccountSwitcher) {
  2274. cssRules.push(`
  2275. header[role="banner"] > div > div > div > div:last-child {
  2276. flex-shrink: 1 !important;
  2277. align-items: flex-end !important;
  2278. }
  2279. `)
  2280. hideCssSelectors.push(
  2281. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child:not(:only-child)',
  2282. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child + div',
  2283. )
  2284. }
  2285. if (config.hideExplorePageContents) {
  2286. hideCssSelectors.push(
  2287. // Tabs
  2288. `body.Explore ${Selectors.DESKTOP_TIMELINE_HEADER} nav`,
  2289. // Content
  2290. `body.Explore ${Selectors.TIMELINE}`,
  2291. )
  2292. }
  2293. if (config.hideConnectNav) {
  2294. hideCssSelectors.push(`${menuRole} a[href$="/i/connect_people"]`)
  2295. }
  2296. if (config.hideKeyboardShortcutsNav) {
  2297. hideCssSelectors.push(`${menuRole} a[href$="/i/keyboard_shortcuts"]`)
  2298. }
  2299. if (config.hideListsNav) {
  2300. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/lists"]`)
  2301. }
  2302. if (config.hideTwitterBlueUpsells) {
  2303. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/i/verified-choose"]`)
  2304. }
  2305. if (config.hideSidebarContent) {
  2306. // Only show the first sidebar item by default
  2307. // Re-show subsequent non-algorithmic sections on specific pages
  2308. cssRules.push(`
  2309. ${Selectors.SIDEBAR_WRAPPERS} > div:not(:first-of-type) {
  2310. display: none;
  2311. }
  2312. body.Profile:not(.Blocked, .NoMedia) ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2313. display: block;
  2314. }
  2315. body.Search ${Selectors.SIDEBAR_WRAPPERS} > div:nth-of-type(2) {
  2316. display: block;
  2317. }
  2318. `)
  2319. if (config.showRelevantPeople) {
  2320. cssRules.push(`
  2321. body.Tweet ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2322. display: block;
  2323. }
  2324. `)
  2325. }
  2326. hideCssSelectors.push(`body.HideSidebar ${Selectors.SIDEBAR}`)
  2327. } else if (config.hideTwitterBlueUpsells) {
  2328. hideCssSelectors.push(
  2329. `body.MainTimeline ${Selectors.SIDEBAR_WRAPPERS} > div:nth-of-type(3)`
  2330. )
  2331. }
  2332. if (config.hideShareTweetButton) {
  2333. hideCssSelectors.push(
  2334. // In media modal
  2335. `[aria-modal="true"] [role="group"] > div[style]:not([role]):not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2336. )
  2337. }
  2338. if (config.hideExploreNav) {
  2339. // When configured, hide Explore only when the sidebar is showing, or
  2340. // when on a page full-width content is enabled on.
  2341. let bodySelector = `${config.hideExploreNavWithSidebar ? `body.Sidebar${config.fullWidthContent ? `:not(${FULL_WIDTH_BODY_PSEUDO})` : ''} ` : ''}`
  2342. hideCssSelectors.push(`${bodySelector}${Selectors.PRIMARY_NAV_DESKTOP} a[href="/explore"]`)
  2343. }
  2344. if (config.hideBookmarksNav) {
  2345. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/i/bookmarks"]`)
  2346. }
  2347. if (config.hideCommunitiesNav) {
  2348. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/communities"]`)
  2349. }
  2350. if (config.hideMessagesDrawer) {
  2351. cssRules.push(`${Selectors.MESSAGES_DRAWER} { visibility: hidden; }`)
  2352. }
  2353. if (config.hideViews) {
  2354. hideCssSelectors.push(
  2355. // Under timeline tweets
  2356. // The Buffer extension adds a new button in position 2 - use their added class to avoid
  2357. // hiding the wrong button (#209)
  2358. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-of-type(4)',
  2359. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-of-type(5)',
  2360. )
  2361. }
  2362. if (config.retweets != 'separate' && config.quoteTweets != 'separate') {
  2363. hideCssSelectors.push('#tnt_separated_tweets_tab')
  2364. }
  2365. }
  2366.  
  2367. if (mobile) {
  2368. if (config.disableHomeTimeline) {
  2369. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/home"]`)
  2370. }
  2371. if (config.hideSeeNewTweets) {
  2372. hideCssSelectors.push(`body.MainTimeline ${Selectors.MOBILE_TIMELINE_HEADER_NEW} ~ div[style^="transform"]:last-child`)
  2373. }
  2374. if (config.hideAppNags) {
  2375. cssRules.push(`
  2376. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_OLD} div:nth-of-type(3) > div > [role="button"],
  2377. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_NEW} div:nth-of-type(3) > div > [role="button"] {
  2378. visibility: hidden;
  2379. }
  2380. `)
  2381. }
  2382. if (config.hideExplorePageContents) {
  2383. // Hide explore page contents so we don't get a brief flash of them
  2384. // before automatically switching the page to search mode.
  2385. hideCssSelectors.push(
  2386. // Tabs
  2387. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div:nth-of-type(2)`,
  2388. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:nth-of-type(2)`,
  2389. // Content
  2390. `body.Explore ${Selectors.TIMELINE}`,
  2391. )
  2392. }
  2393. if (config.hideListsNav) {
  2394. hideCssSelectors.push(`${menuRole} a[href$="/lists"]`)
  2395. }
  2396. if (config.hideMessagesBottomNavItem) {
  2397. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/messages"]`)
  2398. }
  2399. if (config.hideShareTweetButton) {
  2400. hideCssSelectors.push(
  2401. // In media modal
  2402. `body.MobileMedia [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2403. )
  2404. }
  2405. if (config.hideViews) {
  2406. hideCssSelectors.push(
  2407. // Under timeline tweets
  2408. // Views only display on mobile at larger widths - only hide the 4th button if there are 5
  2409. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-child(4):nth-last-child(2)',
  2410. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-child(4):nth-last-child(2)',
  2411. )
  2412. }
  2413. }
  2414.  
  2415. if (hideCssSelectors.length > 0) {
  2416. cssRules.push(`
  2417. ${hideCssSelectors.join(',\n')} {
  2418. display: none !important;
  2419. }
  2420. `)
  2421. }
  2422.  
  2423. $style.textContent = cssRules.map(dedent).join('\n')
  2424. }
  2425. })()
  2426.  
  2427. function configureFont() {
  2428. if (!fontFamilyRule) {
  2429. warn('no fontFamilyRule found for configureFont to use')
  2430. return
  2431. }
  2432.  
  2433. if (config.dontUseChirpFont) {
  2434. if (fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2435. fontFamilyRule.style.fontFamily = fontFamilyRule.style.fontFamily.replace(/"?TwitterChirp"?, ?/, '')
  2436. log('disabled Chirp font')
  2437. }
  2438. } else if (!fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2439. fontFamilyRule.style.fontFamily = `"TwitterChirp", ${fontFamilyRule.style.fontFamily}`
  2440. log(`enabled Chirp font`)
  2441. }
  2442. }
  2443.  
  2444. /**
  2445. * @param {string[]} cssRules
  2446. * @param {string[]} hideCssSelectors
  2447. */
  2448. function configureHideMetricsCss(cssRules, hideCssSelectors) {
  2449. if (config.hideFollowingMetrics) {
  2450. // User profile hover card and page metrics
  2451. hideCssSelectors.push(
  2452. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) > :first-child'
  2453. )
  2454. // Fix display of whitespace after hidden metrics
  2455. cssRules.push(
  2456. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) { white-space: pre-line; }'
  2457. )
  2458. }
  2459.  
  2460. if (config.hideTotalTweetsMetrics) {
  2461. // Tweet count under username header on profile pages
  2462. hideCssSelectors.push(
  2463. mobile ? `
  2464. body.Profile header > div > div:first-of-type h2 + div[dir],
  2465. body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:first-of-type h2 + div[dir]
  2466. ` : `body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 + div[dir]`
  2467. )
  2468. }
  2469.  
  2470. let individualTweetMetricSelectors = [
  2471. config.hideRetweetMetrics && '[href$="/retweets"]',
  2472. config.hideLikeMetrics && '[href$="/likes"]',
  2473. config.hideQuoteTweetMetrics && '[href$="/retweets/with_comments"]',
  2474. ].filter(Boolean).join(', ')
  2475.  
  2476. if (individualTweetMetricSelectors) {
  2477. // Individual tweet metrics
  2478. hideCssSelectors.push(
  2479. `body.Tweet a:is(${individualTweetMetricSelectors}) > :first-child`,
  2480. `[aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) > :first-child`
  2481. )
  2482. // Fix display of whitespace after hidden metrics
  2483. cssRules.push(
  2484. `body.Tweet a:is(${individualTweetMetricSelectors}), [aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) { white-space: pre-line; }`
  2485. )
  2486. }
  2487.  
  2488. if (config.hideBookmarkMetrics) {
  2489. // Bookmark metrics are the only one without a link
  2490. hideCssSelectors.push('[data-testid="tweet"][tabindex="-1"] [role="group"]:not([id]) > div > div')
  2491. }
  2492.  
  2493. let timelineMetricSelectors = [
  2494. config.hideReplyMetrics && '[data-testid="reply"]',
  2495. config.hideRetweetMetrics && '[data-testid$="retweet"]',
  2496. config.hideLikeMetrics && '[data-testid$="like"]',
  2497. ].filter(Boolean).join(', ')
  2498.  
  2499. if (timelineMetricSelectors) {
  2500. cssRules.push(
  2501. `[role="group"] div:is(${timelineMetricSelectors}) span { visibility: hidden; }`
  2502. )
  2503. }
  2504. }
  2505.  
  2506. const configureNavFontSizeCss = (() => {
  2507. let $style
  2508.  
  2509. return function configureNavFontSizeCss() {
  2510. if ($style == null) {
  2511. $style = addStyle('nav-font-size')
  2512. }
  2513. let cssRules = []
  2514.  
  2515. if (fontSize != null && config.navBaseFontSize) {
  2516. cssRules.push(`
  2517. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] span { font-size: ${fontSize}; font-weight: normal; }
  2518. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] { margin-top: -4px; }
  2519. `)
  2520. }
  2521.  
  2522. $style.textContent = cssRules.map(dedent).join('\n')
  2523. }
  2524. })()
  2525.  
  2526. /**
  2527. * Configures – or re-configures – the separated tweets timeline title.
  2528. *
  2529. * If we're currently on the separated tweets timeline and…
  2530. * - …its title has changed, the page title will be changed to "navigate" to it.
  2531. * - …the separated tweets timeline is no longer needed, we'll change the page
  2532. * title to "navigate" back to the main timeline.
  2533. *
  2534. * @returns {boolean} `true` if "navigation" was triggered by this call
  2535. */
  2536. function configureSeparatedTweetsTimelineTitle() {
  2537. let wasOnSeparatedTweetsTimeline = isOnSeparatedTweetsTimeline()
  2538. let previousTitle = separatedTweetsTimelineTitle
  2539.  
  2540. if (config.retweets == 'separate' && config.quoteTweets == 'separate') {
  2541. separatedTweetsTimelineTitle = getString('SHARED_TWEETS')
  2542. } else if (config.retweets == 'separate') {
  2543. separatedTweetsTimelineTitle = getString('RETWEETS')
  2544. } else if (config.quoteTweets == 'separate') {
  2545. separatedTweetsTimelineTitle = getString('QUOTE_TWEETS')
  2546. } else {
  2547. separatedTweetsTimelineTitle = null
  2548. }
  2549.  
  2550. let titleChanged = previousTitle != separatedTweetsTimelineTitle
  2551. if (wasOnSeparatedTweetsTimeline) {
  2552. if (separatedTweetsTimelineTitle == null) {
  2553. log('moving from separated tweets timeline to main timeline after config change')
  2554. setTitle(getString('HOME'))
  2555. return true
  2556. }
  2557. if (titleChanged) {
  2558. log('applying new separated tweets timeline title after config change')
  2559. setTitle(separatedTweetsTimelineTitle)
  2560. return true
  2561. }
  2562. } else {
  2563. if (titleChanged && previousTitle != null && lastMainTimelineTitle == previousTitle) {
  2564. log('updating lastMainTimelineTitle with new separated tweets timeline title')
  2565. lastMainTimelineTitle = separatedTweetsTimelineTitle
  2566. }
  2567. }
  2568. }
  2569.  
  2570. const configureThemeCss = (() => {
  2571. let $style
  2572.  
  2573. return function configureThemeCss() {
  2574. if ($style == null) {
  2575. $style = addStyle('theme')
  2576. }
  2577. let cssRules = []
  2578.  
  2579. if (debug) {
  2580. cssRules.push(`
  2581. [data-item-type]::after {
  2582. position: absolute;
  2583. top: 0;
  2584. ${ltr ? 'right': 'left'}: 50px;
  2585. content: attr(data-item-type);
  2586. font-family: ${fontFamilyRule?.style.fontFamily || '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial'};
  2587. background-color: rgb(242, 29, 29);
  2588. color: white;
  2589. font-size: 11px;
  2590. font-weight: bold;
  2591. padding: 4px 6px;
  2592. border-bottom-left-radius: 1em;
  2593. border-bottom-right-radius: 1em;
  2594. }
  2595. `)
  2596. }
  2597.  
  2598. // Active tab colour for custom tabs
  2599. if (themeColor != null && shouldShowSeparatedTweetsTab()) {
  2600. cssRules.push(`
  2601. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2602. background-color: ${themeColor} !important;
  2603. }
  2604. `)
  2605. }
  2606.  
  2607. if (config.replaceLogo) {
  2608. cssRules.push(`
  2609. ${Selectors.X_LOGO_PATH} {
  2610. ${themeColor ? `fill: ${themeColor};` : ''}
  2611. d: path("${Svgs.TWITTER_LOGO_PATH}");
  2612. }
  2613. .tnt_logo {
  2614. ${themeColor ? `fill: ${themeColor};` : ''}
  2615. }
  2616. `)
  2617. }
  2618.  
  2619. if (config.uninvertFollowButtons) {
  2620. // Shared styles for Following and Follow buttons
  2621. cssRules.push(`
  2622. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2623. border-color: rgba(0, 0, 0, 0) !important;
  2624. }
  2625. [role="button"][data-testid$="-follow"] {
  2626. background-color: rgba(0, 0, 0, 0) !important;
  2627. }
  2628. `)
  2629. if (config.followButtonStyle == 'monochrome' || themeColor == null) {
  2630. cssRules.push(`
  2631. /* Following button */
  2632. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2633. background-color: rgb(15, 20, 25) !important;
  2634. }
  2635. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2636. color: rgb(255, 255, 255) !important;
  2637. }
  2638. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2639. background-color: rgb(255, 255, 255) !important;
  2640. }
  2641. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2642. color: rgb(15, 20, 25) !important;
  2643. }
  2644. /* Follow button */
  2645. body.Default [role="button"][data-testid$="-follow"] {
  2646. border-color: rgb(207, 217, 222) !important;
  2647. }
  2648. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] {
  2649. border-color: rgb(83, 100, 113) !important;
  2650. }
  2651. body.Default [role="button"][data-testid$="-follow"] > :is(div, span) {
  2652. color: rgb(15, 20, 25) !important;
  2653. }
  2654. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] > :is(div, span) {
  2655. color: rgb(255, 255, 255) !important;
  2656. }
  2657. body.Default [role="button"][data-testid$="-follow"]:hover {
  2658. background-color: rgba(15, 20, 25, 0.1) !important;
  2659. }
  2660. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"]:hover {
  2661. background-color: rgba(255, 255, 255, 0.1) !important;
  2662. }
  2663. `)
  2664. }
  2665. if (config.followButtonStyle == 'themed' && themeColor != null) {
  2666. cssRules.push(`
  2667. /* Following button */
  2668. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2669. background-color: ${themeColor} !important;
  2670. }
  2671. [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2672. color: rgb(255, 255, 255) !important;
  2673. }
  2674. /* Follow button */
  2675. [role="button"][data-testid$="-follow"] {
  2676. border-color: ${themeColor} !important;
  2677. }
  2678. [role="button"][data-testid$="-follow"] > :is(div, span) {
  2679. color: ${themeColor} !important;
  2680. }
  2681. [role="button"][data-testid$="-follow"]:hover {
  2682. background-color: ${themeColor} !important;
  2683. }
  2684. [role="button"][data-testid$="-follow"]:hover > :is(div, span) {
  2685. color: rgb(255, 255, 255) !important;
  2686. }
  2687. `)
  2688. }
  2689. if (mobile) {
  2690. cssRules.push(`
  2691. body.MediaViewer [role="button"][data-testid$="follow"]:not(:hover) {
  2692. border: revert !important;
  2693. background-color: transparent !important;
  2694. }
  2695. body.MediaViewer [role="button"][data-testid$="follow"]:not(:hover) > div {
  2696. color: ${themeColor} !important;
  2697. }
  2698. `)
  2699. }
  2700. }
  2701.  
  2702. $style.textContent = cssRules.map(dedent).join('\n')
  2703. }
  2704. })()
  2705.  
  2706. /**
  2707. * @param {HTMLElement} $tweet
  2708. * @param {?{getText?: boolean}} options
  2709. * @returns {import("./types").QuotedTweet}
  2710. */
  2711. function getQuotedTweetDetails($tweet, options = {}) {
  2712. let {getText = false} = options
  2713. let $quotedTweet = $tweet.querySelector('div[id^="id__"] > div[dir] > span').parentElement.nextElementSibling
  2714. let $userName = $quotedTweet?.querySelector('[data-testid="User-Name"]')
  2715. let user = $userName?.querySelector('[tabindex="-1"]')?.textContent
  2716. let time = $userName?.querySelector('time')?.dateTime
  2717. if (!getText) return {user, time}
  2718.  
  2719. let $heading = $quotedTweet?.querySelector(':scope > div > div:first-child')
  2720. let $qtText = $heading?.nextElementSibling?.querySelector('[lang]')
  2721. let text = $qtText && Array.from($qtText.childNodes, node => {
  2722. if (node.nodeType == 1) {
  2723. if (node.nodeName == 'IMG') return node.alt
  2724. return node.textContent
  2725. }
  2726. return node.nodeValue
  2727. }).join('')
  2728. return {user, time, text}
  2729. }
  2730.  
  2731. /**
  2732. * Attempts to determine the type of a timeline Tweet given the element with
  2733. * data-testid="tweet" on it, falling back to TWEET if it doesn't appear to be
  2734. * one of the particular types we care about.
  2735. * @param {HTMLElement} $tweet
  2736. * @param {?boolean} checkSocialContext
  2737. * @returns {import("./types").TweetType}
  2738. */
  2739. function getTweetType($tweet, checkSocialContext = false) {
  2740. if ($tweet.closest(Selectors.PROMOTED_TWEET_CONTAINER)) {
  2741. return 'PROMOTED_TWEET'
  2742. }
  2743. // Assume social context tweets are Retweets
  2744. if ($tweet.querySelector('[data-testid="socialContext"]')) {
  2745. if (checkSocialContext) {
  2746. let svgPath = $tweet.querySelector('svg path')?.getAttribute('d') ?? ''
  2747. if (svgPath.startsWith('M7 4.5C7 3.12 8.12 2 9.5 2h5C1')) return 'PINNED_TWEET'
  2748. }
  2749. // Quoted tweets from accounts you blocked or muted are displayed as an
  2750. // <article> with "This Tweet is unavailable."
  2751. if ($tweet.querySelector('article')) {
  2752. return 'UNAVAILABLE_RETWEET'
  2753. }
  2754. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2755. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2756. return 'RETWEETED_QUOTE_TWEET'
  2757. }
  2758. return 'RETWEET'
  2759. }
  2760. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2761. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2762. return 'QUOTE_TWEET'
  2763. }
  2764. // Quoted tweets from accounts you blocked or muted are displayed as an
  2765. // <article> with "This Tweet is unavailable."
  2766. if ($tweet.querySelector('article')) {
  2767. return 'UNAVAILABLE_QUOTE_TWEET'
  2768. }
  2769. return 'TWEET'
  2770. }
  2771.  
  2772. // Add 1 every time this gets broken: 6
  2773. function getVerifiedProps($svg) {
  2774. let propsGetter = (props) => props?.children?.props?.children?.[0]?.[0]?.props
  2775. let $parent = $svg.parentElement.parentElement
  2776. // Verified badge button on the profile screen
  2777. if (isOnProfilePage() && $svg.parentElement.getAttribute('role') == 'button') {
  2778. $parent = $svg.closest('span').parentElement
  2779. }
  2780. // Link variant in "user followed/liked/retweeted" notifications
  2781. else if (isOnNotificationsPage() && $parent.getAttribute('role') == 'link') {
  2782. propsGetter = (props) => {
  2783. let linkChildren = props?.children?.props?.children?.[0]
  2784. return linkChildren?.[linkChildren.length - 1]?.props
  2785. }
  2786. }
  2787. if ($parent.wrappedJSObject) {
  2788. $parent = $parent.wrappedJSObject
  2789. }
  2790. let reactPropsKey = Object.keys($parent).find(key => key.startsWith('__reactProps$'))
  2791. let props = propsGetter($parent[reactPropsKey])
  2792. if (!props) {
  2793. warn('React props not found for', $svg)
  2794. }
  2795. else if (!('isVerified' in props)) {
  2796. warn('isVerified not in React props for', $svg, {props})
  2797. }
  2798. return props
  2799. }
  2800.  
  2801. /**
  2802. * @param {HTMLElement} $popup
  2803. * @returns {{tookAction: boolean, onPopupClosed?: () => void}}
  2804. */
  2805. function handlePopup($popup) {
  2806. let result = {tookAction: false, onPopupClosed: null}
  2807.  
  2808. if (desktop && !isDesktopMediaModalOpen && URL_MEDIA_RE.test(location.pathname) && currentPath != location.pathname) {
  2809. log('media modal opened')
  2810. isDesktopMediaModalOpen = true
  2811. observeDesktopModalTimeline()
  2812. return {
  2813. tookAction: true,
  2814. onPopupClosed() {
  2815. log('media modal closed')
  2816. isDesktopMediaModalOpen = false
  2817. disconnectAllModalObservers()
  2818. }
  2819. }
  2820. }
  2821.  
  2822. if (config.twitterBlueChecks != 'ignore' && desktop && !isDesktopUserListModalOpen && URL_TWEET_LIKES_RETWEETS_RE.test(location.pathname)) {
  2823. let modalType = URL_TWEET_LIKES_RETWEETS_RE.exec(location.pathname)[1]
  2824. log(`${modalType} modal opened`)
  2825. isDesktopUserListModalOpen = true
  2826. observeUserListTimeline($popup, location.pathname)
  2827. return {
  2828. tookAction: true,
  2829. onPopupClosed() {
  2830. log(`${modalType} modal closed`)
  2831. isDesktopUserListModalOpen = false
  2832. disconnectAllModalObservers()
  2833. }
  2834. }
  2835. }
  2836.  
  2837. if (isOnListPage()) {
  2838. let $switchSvg = $popup.querySelector(`svg path[d^="M12 3.75c-4.56 0-8.25 3.69-8.25 8.25s"]`)
  2839. if ($switchSvg) {
  2840. addToggleListRetweetsMenuItem($popup.querySelector(`[role="menuitem"]`))
  2841. return {tookAction: true}
  2842. }
  2843. }
  2844.  
  2845. if (config.mutableQuoteTweets) {
  2846. if (quotedTweet) {
  2847. let $blockMenuItem = /** @type {HTMLElement} */ ($popup.querySelector(Selectors.BLOCK_MENU_ITEM))
  2848. if ($blockMenuItem) {
  2849. addMuteQuotesMenuItem($blockMenuItem)
  2850. result.tookAction = true
  2851. // Clear the quoted tweet when the popup closes
  2852. result.onPopupClosed = () => {
  2853. quotedTweet = null
  2854. }
  2855. } else {
  2856. quotedTweet = null
  2857. }
  2858. }
  2859. }
  2860.  
  2861. if (config.fastBlock) {
  2862. if (blockMenuItemSeen && $popup.querySelector('[data-testid="confirmationSheetConfirm"]')) {
  2863. log('fast blocking')
  2864. ;/** @type {HTMLElement} */ ($popup.querySelector('[data-testid="confirmationSheetConfirm"]')).click()
  2865. result.tookAction = true
  2866. }
  2867. else if ($popup.querySelector(Selectors.BLOCK_MENU_ITEM)) {
  2868. log('preparing for fast blocking')
  2869. blockMenuItemSeen = true
  2870. // Create a nested observer for mobile, as it reuses the popup element
  2871. result.tookAction = !mobile
  2872. } else {
  2873. blockMenuItemSeen = false
  2874. }
  2875. }
  2876.  
  2877. if (config.hideTwitterBlueUpsells) {
  2878. // The "Pin to your profile" menu item is currently the only one which opens
  2879. // a sheet dialog.
  2880. if (pinMenuItemSeen && $popup.querySelector('[data-testid="sheetDialog"]')) {
  2881. log('pin to your profile modal opened')
  2882. $popup.classList.add('PinModal')
  2883. result.tookAction = true
  2884. }
  2885. else if ($popup.querySelector('[data-testid="highlighOnPin"]')) {
  2886. log('preparing to hide Twitter Blue upsell when pinning a tweet')
  2887. pinMenuItemSeen = true
  2888. // Create a nested observer for mobile, as it reuses the popup element
  2889. result.tookAction = !mobile
  2890. } else {
  2891. pinMenuItemSeen = false
  2892. }
  2893. }
  2894.  
  2895. if (config.addAddMutedWordMenuItem) {
  2896. let linkSelector = desktop ? 'a[href$="/compose/tweet/unsent/drafts"]' : 'a[href$="/bookmarks"]'
  2897. let $link = /** @type {HTMLElement} */ ($popup.querySelector(linkSelector))
  2898. if ($link) {
  2899. addAddMutedWordMenuItem($link, linkSelector)
  2900. result.tookAction = true
  2901. }
  2902. }
  2903.  
  2904. if (config.twitterBlueChecks != 'ignore') {
  2905. // User typeahead dropdown
  2906. let $typeaheadDropdown = /** @type {HTMLElement} */ ($popup.querySelector('div[id^="typeaheadDropdown"]'))
  2907. if ($typeaheadDropdown) {
  2908. log('typeahead dropdown appeared')
  2909. let observer = observeElement($typeaheadDropdown, () => {
  2910. processBlueChecks($typeaheadDropdown)
  2911. }, 'popup typeahead dropdown')
  2912. return {
  2913. tookAction: true,
  2914. onPopupClosed() {
  2915. log('typeahead dropdown closed')
  2916. observer.disconnect()
  2917. }
  2918. }
  2919. }
  2920.  
  2921. // User hovercard popup
  2922. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  2923. if ($hoverCard) {
  2924. result.tookAction = true
  2925. getElement('div[data-testid^="UserAvatar-Container"]', {
  2926. context: $hoverCard,
  2927. name: 'user hovercard contents',
  2928. timeout: 500,
  2929. }).then(($contents) => {
  2930. if ($contents) processBlueChecks($popup)
  2931. })
  2932. }
  2933. }
  2934.  
  2935. // Verified account popup when you press the check button on a profile page
  2936. if (config.twitterBlueChecks == 'replace' && isOnProfilePage()) {
  2937. if (mobile) {
  2938. let $verificationBadge = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="sheetDialog"] [data-testid="verificationBadge"]'))
  2939. if ($verificationBadge) {
  2940. result.tookAction = true
  2941. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} .tnt_blue_check`)
  2942. if ($headerBlueCheck) {
  2943. blueCheck($verificationBadge)
  2944. }
  2945. }
  2946. } else {
  2947. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  2948. if ($hoverCard) {
  2949. result.tookAction = true
  2950. getElement(':scope > div > div > div > svg[data-testid="verificationBadge"]', {
  2951. context: $hoverCard,
  2952. name: 'verified account hovercard verification badge',
  2953. timeout: 500,
  2954. }).then(($verificationBadge) => {
  2955. if (!$verificationBadge) return
  2956.  
  2957. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 .tnt_blue_check`)
  2958. if (!$headerBlueCheck) return
  2959.  
  2960. // Wait for the hovercard to render its contents
  2961. let popupRenderObserver = observeElement($popup, (mutations) => {
  2962. if (!mutations.length) return
  2963. blueCheck($popup.querySelector('svg[data-testid="verificationBadge"]'))
  2964. popupRenderObserver.disconnect()
  2965. }, 'verified popup render', {childList: true, subtree: true})
  2966. })
  2967. }
  2968. }
  2969. }
  2970.  
  2971. return result
  2972. }
  2973.  
  2974. function isBlueVerified($svg) {
  2975. let props = getVerifiedProps($svg)
  2976. return Boolean(props && props.isBlueVerified && !(props.verifiedType || props.affiliateBadgeInfo?.userLabelType == 'BusinessLabel'))
  2977. }
  2978.  
  2979. /**
  2980. * Checks if a tweet is preceded by an element creating a vertical reply line.
  2981. * @param {HTMLElement} $tweet
  2982. * @returns {boolean}
  2983. */
  2984. function isReplyToPreviousTweet($tweet) {
  2985. let $replyLine = $tweet.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild
  2986. if ($replyLine) {
  2987. return getComputedStyle($replyLine).width == '2px'
  2988. }
  2989. }
  2990.  
  2991. /**
  2992. * @returns {{disconnect()}}
  2993. */
  2994. function onPopup($popup) {
  2995. log('popup appeared', $popup)
  2996.  
  2997. // If handlePopup did something, we don't need to observe nested popups
  2998. let {tookAction, onPopupClosed} = handlePopup($popup)
  2999. if (tookAction) {
  3000. return onPopupClosed ? {disconnect: onPopupClosed} : null
  3001. }
  3002.  
  3003. /** @type {HTMLElement} */
  3004. let $nestedPopup
  3005.  
  3006. let nestedObserver = observeElement($popup, (mutations) => {
  3007. mutations.forEach((mutation) => {
  3008. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3009. log('nested popup appeared', $el)
  3010. $nestedPopup = $el
  3011. ;({onPopupClosed} = handlePopup($el))
  3012. })
  3013. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3014. if ($el !== $nestedPopup) return
  3015. if (onPopupClosed) {
  3016. log('cleaning up after nested popup removed')
  3017. onPopupClosed()
  3018. }
  3019. })
  3020. })
  3021. })
  3022.  
  3023. let disconnect = nestedObserver.disconnect.bind(nestedObserver)
  3024. nestedObserver.disconnect = () => {
  3025. if (onPopupClosed) {
  3026. log('cleaning up after nested popup observer disconnected')
  3027. onPopupClosed()
  3028. }
  3029. disconnect()
  3030. }
  3031.  
  3032. return nestedObserver
  3033. }
  3034.  
  3035. /**
  3036. * @param {HTMLElement} $timeline
  3037. * @param {string} page
  3038. * @param {import("./types").TimelineOptions?} options
  3039. */
  3040. function onTimelineChange($timeline, page, options = {}) {
  3041. let startTime = Date.now()
  3042. let {classifyTweets = true, hideHeadings = true} = options
  3043.  
  3044. let isOnMainTimeline = isOnMainTimelinePage()
  3045. let isOnListTimeline = isOnListPage()
  3046. let isOnProfileTimeline = isOnProfilePage()
  3047. let timelineHasSpecificHandling = isOnMainTimeline || isOnListTimeline || isOnProfileTimeline
  3048.  
  3049. if (config.twitterBlueChecks != 'ignore' && !timelineHasSpecificHandling) {
  3050. processBlueChecks($timeline)
  3051. }
  3052.  
  3053. if (isSafari && config.replaceLogo && isOnNotificationsPage()) {
  3054. processTwitterLogos($timeline)
  3055. }
  3056.  
  3057. if (!classifyTweets) return
  3058.  
  3059. let itemTypes = {}
  3060. let hiddenItemCount = 0
  3061. let hiddenItemTypes = {}
  3062.  
  3063. /** @type {?boolean} */
  3064. let hidPreviousItem = null
  3065. /** @type {{$item: Element, hideItem?: boolean}[]} */
  3066. let changes = []
  3067.  
  3068. for (let $item of $timeline.children) {
  3069. /** @type {?import("./types").TimelineItemType} */
  3070. let itemType = null
  3071. /** @type {?boolean} */
  3072. let hideItem = null
  3073. /** @type {?HTMLElement} */
  3074. let $tweet = $item.querySelector(Selectors.TWEET)
  3075. /** @type {boolean} */
  3076. let isReply = false
  3077. /** @type {boolean} */
  3078. let isBlueTweet = false
  3079.  
  3080. if ($tweet != null) {
  3081. itemType = getTweetType($tweet, isOnProfileTimeline)
  3082. if (timelineHasSpecificHandling) {
  3083. isReply = isReplyToPreviousTweet($tweet)
  3084. if (isReply && hidPreviousItem != null) {
  3085. hideItem = hidPreviousItem
  3086. } else {
  3087. if (isOnMainTimeline) {
  3088. hideItem = shouldHideMainTimelineItem(itemType, page)
  3089. }
  3090. else if (isOnListTimeline) {
  3091. hideItem = shouldHideListTimelineItem(itemType)
  3092. }
  3093. else if (isOnProfileTimeline) {
  3094. hideItem = shouldHideProfileTimelineItem(itemType)
  3095. }
  3096. }
  3097.  
  3098. if (!hideItem && config.mutableQuoteTweets && (itemType == 'QUOTE_TWEET' || itemType == 'RETWEETED_QUOTE_TWEET')) {
  3099. if (config.mutedQuotes.length > 0) {
  3100. let quotedTweet = getQuotedTweetDetails($tweet)
  3101. hideItem = config.mutedQuotes.some(muted => muted.user == quotedTweet.user && muted.time == quotedTweet.time)
  3102. }
  3103. if (!hideItem) {
  3104. addCaretMenuListenerForQuoteTweet($tweet)
  3105. }
  3106. }
  3107.  
  3108. if (config.twitterBlueChecks != 'ignore') {
  3109. for (let $svg of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  3110. let isBlueCheck = isBlueVerified($svg)
  3111. if (!isBlueCheck) continue
  3112.  
  3113. blueCheck($svg)
  3114.  
  3115. let userProfileLink = $svg.closest('a[role="link"]:not([href^="/i/status"])')
  3116. if (!userProfileLink) continue
  3117.  
  3118. isBlueTweet = true
  3119. }
  3120. }
  3121. }
  3122. }
  3123. else if (!timelineHasSpecificHandling) {
  3124. if ($item.querySelector(':scope > div > div > div > article')) {
  3125. itemType = 'UNAVAILABLE'
  3126. }
  3127. }
  3128.  
  3129. if (!timelineHasSpecificHandling) {
  3130. if (itemType != null) {
  3131. hideItem = shouldHideOtherTimelineItem(itemType)
  3132. }
  3133. }
  3134.  
  3135. if (itemType == null) {
  3136. if ($item.querySelector(Selectors.TIMELINE_HEADING)) {
  3137. itemType = 'HEADING'
  3138. hideItem = hideHeadings && config.hideWhoToFollowEtc
  3139. }
  3140. }
  3141.  
  3142. if (debug && itemType != null) {
  3143. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${isBlueTweet ? ' / BLUE' : ''}`
  3144. }
  3145.  
  3146. // Assume a non-identified item following an identified item is related
  3147. if (itemType == null && hidPreviousItem != null) {
  3148. hideItem = hidPreviousItem
  3149. itemType = 'SUBSEQUENT_ITEM'
  3150. }
  3151.  
  3152. if (itemType != null) {
  3153. itemTypes[itemType] ||= 0
  3154. itemTypes[itemType]++
  3155. }
  3156.  
  3157. if (hideItem) {
  3158. hiddenItemCount++
  3159. hiddenItemTypes[itemType] ||= 0
  3160. hiddenItemTypes[itemType]++
  3161. }
  3162.  
  3163. if (hideItem != null && $item.firstElementChild) {
  3164. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  3165. changes.push({$item, hideItem})
  3166. }
  3167. }
  3168.  
  3169. hidPreviousItem = hideItem
  3170. }
  3171.  
  3172. for (let change of changes) {
  3173. /** @type {HTMLElement} */ (change.$item.firstElementChild).style.display = change.hideItem ? 'none' : ''
  3174. }
  3175.  
  3176. log(
  3177. `processed ${$timeline.children.length} timeline item${s($timeline.children.length)} in ${Date.now() - startTime}ms`,
  3178. itemTypes, `hid ${hiddenItemCount}`, hiddenItemTypes
  3179. )
  3180. }
  3181.  
  3182. /**
  3183. * @param {HTMLElement} $timeline
  3184. */
  3185. function onIndividualTweetTimelineChange($timeline) {
  3186. let startTime = Date.now()
  3187.  
  3188. let itemTypes = {}
  3189. let hiddenItemCount = 0
  3190. let hiddenItemTypes = {}
  3191.  
  3192. /** @type {?boolean} */
  3193. let hidPreviousItem = null
  3194. /** @type {boolean} */
  3195. let hideAllSubsequentItems = false
  3196. /** @type {string} */
  3197. let opScreenName = /^\/([a-zA-Z\d_]{1,20})\//.exec(location.pathname)[1].toLowerCase()
  3198. /** @type {{$item: Element, hideItem?: boolean}[]} */
  3199. let changes = []
  3200. /** @type {import("./types").UserInfoObject} */
  3201. let userInfo = getUserInfo()
  3202.  
  3203. for (let $item of $timeline.children) {
  3204. /** @type {?import("./types").TimelineItemType} */
  3205. let itemType = null
  3206. /** @type {?boolean} */
  3207. let hideItem = null
  3208. /** @type {?HTMLElement} */
  3209. let $tweet = $item.querySelector(Selectors.TWEET)
  3210. /** @type {boolean} */
  3211. let isFocusedTweet = false
  3212. /** @type {boolean} */
  3213. let isReply = false
  3214. /** @type {boolean} */
  3215. let isBlueTweet = false
  3216. /** @type {?string} */
  3217. let screenName = null
  3218.  
  3219. if (hideAllSubsequentItems) {
  3220. hideItem = true
  3221. itemType = 'DISCOVER_MORE_TWEET'
  3222. }
  3223. else if ($tweet != null) {
  3224. isFocusedTweet = $tweet.tabIndex == -1
  3225. isReply = isReplyToPreviousTweet($tweet)
  3226. if (isFocusedTweet) {
  3227. itemType = 'FOCUSED_TWEET'
  3228. hideItem = false
  3229. } else {
  3230. itemType = getTweetType($tweet)
  3231. if (isReply && hidPreviousItem != null) {
  3232. hideItem = hidPreviousItem
  3233. } else {
  3234. hideItem = shouldHideIndividualTweetTimelineItem(itemType)
  3235. }
  3236. }
  3237.  
  3238. if (config.twitterBlueChecks != 'ignore' || config.hideTwitterBlueReplies) {
  3239. for (let $svg of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  3240. let isBlueCheck = isBlueVerified($svg)
  3241. if (!isBlueCheck) continue
  3242.  
  3243. if (config.twitterBlueChecks != 'ignore') {
  3244. blueCheck($svg)
  3245. }
  3246.  
  3247. let userProfileLink = /** @type {HTMLAnchorElement} */ ($svg.closest('a[role="link"]:not([href^="/i/status"])'))
  3248. if (!userProfileLink) continue
  3249.  
  3250. isBlueTweet = true
  3251. screenName = userProfileLink.href.split('/').pop()
  3252. }
  3253.  
  3254. // Replies to the focused tweet don't have the reply indicator
  3255. if (isBlueTweet && !isFocusedTweet && !isReply && screenName.toLowerCase() != opScreenName) {
  3256. itemType = 'BLUE_REPLY'
  3257. if (!hideItem) {
  3258. let user = userInfo[screenName]
  3259. hideItem = config.hideTwitterBlueReplies && (user == null || !(
  3260. user.following && !config.hideBlueReplyFollowing ||
  3261. user.followedBy && !config.hideBlueReplyFollowedBy ||
  3262. user.followersCount >= 1000000 && config.showBlueReplyFollowersCount
  3263. ))
  3264. }
  3265. }
  3266. }
  3267. }
  3268. else if ($item.querySelector('article')) {
  3269. if ($item.querySelector('[role="button"]')?.textContent == getString('SHOW')) {
  3270. itemType = 'SHOW_MORE'
  3271. } else {
  3272. itemType = 'UNAVAILABLE'
  3273. hideItem = config.hideUnavailableQuoteTweets
  3274. }
  3275. } else {
  3276. // We need to identify "Show more replies" so it doesn't get hidden if the
  3277. // item immediately before it was hidden.
  3278. let $button = $item.querySelector('div[role="button"]')
  3279. if ($button) {
  3280. if ($button?.textContent == getString('SHOW_MORE_REPLIES')) {
  3281. itemType = 'SHOW_MORE'
  3282. }
  3283. } else {
  3284. let $heading = $item.querySelector(Selectors.TIMELINE_HEADING)
  3285. if ($heading) {
  3286. // Discover More headings have a description next to them
  3287. if ($heading.nextElementSibling &&
  3288. $heading.nextElementSibling.tagName == 'DIV' &&
  3289. $heading.nextElementSibling.getAttribute('dir') != null) {
  3290. itemType = 'DISCOVER_MORE_HEADING'
  3291. hideItem = config.hideMoreTweets
  3292. hideAllSubsequentItems = config.hideMoreTweets
  3293. } else {
  3294. itemType = 'HEADING'
  3295. }
  3296. }
  3297. }
  3298. }
  3299.  
  3300. if (debug && itemType != null) {
  3301. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${isBlueTweet && itemType != 'BLUE_REPLY' ? ' / BLUE' : ''}`
  3302. }
  3303.  
  3304. // Assume a non-identified item following an identified item is related
  3305. if (itemType == null && hidPreviousItem != null) {
  3306. hideItem = hidPreviousItem
  3307. itemType = 'SUBSEQUENT_ITEM'
  3308. }
  3309.  
  3310. if (itemType != null) {
  3311. itemTypes[itemType] ||= 0
  3312. itemTypes[itemType]++
  3313. }
  3314.  
  3315. if (hideItem) {
  3316. hiddenItemCount++
  3317. hiddenItemTypes[itemType] ||= 0
  3318. hiddenItemTypes[itemType]++
  3319. }
  3320.  
  3321. if (isFocusedTweet) {
  3322. // Tweets prior to the focused tweet should never be hidden
  3323. changes = []
  3324. hiddenItemCount = 0
  3325. hiddenItemTypes = {}
  3326. }
  3327. else if (hideItem != null && $item.firstElementChild) {
  3328. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  3329. changes.push({$item, hideItem})
  3330. }
  3331. }
  3332.  
  3333. hidPreviousItem = hideItem
  3334. }
  3335.  
  3336. for (let change of changes) {
  3337. /** @type {HTMLElement} */ (change.$item.firstElementChild).style.display = change.hideItem ? 'none' : ''
  3338. }
  3339.  
  3340. log(
  3341. `processed ${$timeline.children.length} thread item${s($timeline.children.length)} in ${Date.now() - startTime}ms`,
  3342. itemTypes, `hid ${hiddenItemCount}`, hiddenItemTypes
  3343. )
  3344. }
  3345.  
  3346. /**
  3347. * Title format (including notification count):
  3348. * - LTR: (3) ${title} / X
  3349. * - RTL: (3) X \ ${title}
  3350. * @param {string} title
  3351. */
  3352. function onTitleChange(title) {
  3353. log('title changed', {title, path: location.pathname})
  3354.  
  3355. if (checkforDisabledHomeTimeline()) return
  3356.  
  3357. // Ignore leading notification counts in titles
  3358. let notificationCount = ''
  3359. if (TITLE_NOTIFICATION_RE.test(title)) {
  3360. notificationCount = TITLE_NOTIFICATION_RE.exec(title)[0]
  3361. title = title.replace(TITLE_NOTIFICATION_RE, '')
  3362. }
  3363.  
  3364. if (config.replaceLogo && Boolean(notificationCount) != Boolean(currentNotificationCount)) {
  3365. observeFavicon.updatePip(Boolean(notificationCount))
  3366. }
  3367.  
  3368. let homeNavigationWasUsed = homeNavigationIsBeingUsed
  3369. homeNavigationIsBeingUsed = false
  3370.  
  3371. if (title == 'X' || title == getString('TWITTER')) {
  3372. // Mobile uses "Twitter" when viewing media - we need to let these process
  3373. // so the next page will be re-processed when the media is closed.
  3374. if (mobile && (URL_MEDIA_RE.test(location.pathname) || URL_MEDIAVIEWER_RE.test(location.pathname))) {
  3375. log('viewing media on mobile')
  3376. }
  3377. // Ignore Flash of Uninitialised Title when navigating to a page for the
  3378. // first time.
  3379. else {
  3380. log('ignoring Flash of Uninitialised Title')
  3381. return
  3382. }
  3383. }
  3384.  
  3385. // Remove " / Twitter" or "Twitter \ " from the title
  3386. let newPage = title
  3387. if (newPage != 'X' && newPage != getString('TWITTER')) {
  3388. newPage = title.slice(...ltr ? [0, title.lastIndexOf('/') - 1] : [title.indexOf('\\') + 2])
  3389. }
  3390.  
  3391. // Only allow the same page to re-process after a title change on desktop if
  3392. // the "Customize your view" dialog is currently open.
  3393. if (newPage == currentPage && !(desktop && location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW)) {
  3394. log('ignoring duplicate title change')
  3395. currentNotificationCount = notificationCount
  3396. return
  3397. }
  3398.  
  3399. // Search terms are shown in the title
  3400. if (currentPath == PagePaths.SEARCH && location.pathname == PagePaths.SEARCH) {
  3401. log('ignoring title change on Search page')
  3402. currentNotificationCount = notificationCount
  3403. return
  3404. }
  3405.  
  3406. // On desktop, stay on the separated tweets timeline when…
  3407. if (desktop && currentPage == separatedTweetsTimelineTitle &&
  3408. // …the title has changed back to the main timeline…
  3409. (newPage == getString('HOME')) &&
  3410. // …the Home nav link or Following / Home header _wasn't_ clicked and…
  3411. !homeNavigationWasUsed &&
  3412. (
  3413. // …the user viewed media.
  3414. URL_MEDIA_RE.test(location.pathname) ||
  3415. // …the user stopped viewing media.
  3416. URL_MEDIA_RE.test(currentPath) ||
  3417. // …the user opened or used the "Customize your view" dialog.
  3418. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  3419. // …the user closed the "Customize your view" dialog.
  3420. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  3421. // …the user opened the "Send via Direct Message" dialog.
  3422. location.pathname == PagePaths.COMPOSE_MESSAGE ||
  3423. // …the user closed the "Send via Direct Message" dialog.
  3424. currentPath == PagePaths.COMPOSE_MESSAGE ||
  3425. // …the user opened the compose Tweet dialog.
  3426. location.pathname == PagePaths.COMPOSE_TWEET ||
  3427. // …the user closed the compose Tweet dialog.
  3428. currentPath == PagePaths.COMPOSE_TWEET ||
  3429. // …the notification count in the title changed.
  3430. notificationCount != currentNotificationCount
  3431. )) {
  3432. log('ignoring title change on separated tweets timeline')
  3433. currentNotificationCount = notificationCount
  3434. currentPath = location.pathname
  3435. setTitle(separatedTweetsTimelineTitle)
  3436. return
  3437. }
  3438.  
  3439. // Restore display of the separated tweets timelne if it's the last one we
  3440. // saw, and the user navigated back home without using the Home navigation
  3441. // item.
  3442. if (location.pathname == PagePaths.HOME &&
  3443. currentPath != PagePaths.HOME &&
  3444. !homeNavigationWasUsed &&
  3445. lastMainTimelineTitle != null &&
  3446. separatedTweetsTimelineTitle != null &&
  3447. lastMainTimelineTitle == separatedTweetsTimelineTitle) {
  3448. log('restoring display of the separated tweets timeline')
  3449. currentNotificationCount = notificationCount
  3450. currentPath = location.pathname
  3451. setTitle(separatedTweetsTimelineTitle)
  3452. return
  3453. }
  3454.  
  3455. // Assumption: all non-FOUT, non-duplicate title changes are navigation, which
  3456. // need the page to be re-processed.
  3457.  
  3458. currentPage = newPage
  3459. currentNotificationCount = notificationCount
  3460. currentPath = location.pathname
  3461.  
  3462. if (isOnMainTimelinePage()) {
  3463. lastMainTimelineTitle = currentPage
  3464. }
  3465.  
  3466. log('processing new page')
  3467.  
  3468. processCurrentPage()
  3469. }
  3470.  
  3471. /**
  3472. * Processes all Twitter Blue checks inside an element.
  3473. * @param {HTMLElement} $el
  3474. */
  3475. function processBlueChecks($el) {
  3476. for (let $svg of $el.querySelectorAll(`${Selectors.VERIFIED_TICK}:not(.tnt_blue_check)`)) {
  3477. if (isBlueVerified($svg)) {
  3478. blueCheck($svg)
  3479. }
  3480. }
  3481. }
  3482.  
  3483. /**
  3484. * Processes all Twitter logos inside an element.
  3485. */
  3486. function processTwitterLogos($el) {
  3487. for (let $svgPath of $el.querySelectorAll(Selectors.X_LOGO_PATH)) {
  3488. twitterLogo($svgPath)
  3489. }
  3490. }
  3491.  
  3492. function processCurrentPage() {
  3493. if (pageObservers.length > 0) {
  3494. log(
  3495. `disconnecting ${pageObservers.length} page observer${s(pageObservers.length)}`,
  3496. pageObservers.map(observer => observer['name'])
  3497. )
  3498. pageObservers.forEach(observer => observer.disconnect())
  3499. pageObservers = []
  3500. }
  3501.  
  3502. // Hooks for styling pages
  3503. $body.classList.toggle('Community', isOnCommunityPage())
  3504. $body.classList.toggle('Explore', isOnExplorePage())
  3505. $body.classList.toggle('HideSidebar', shouldHideSidebar())
  3506. $body.classList.toggle('List', isOnListPage())
  3507. $body.classList.toggle('MainTimeline', isOnMainTimelinePage())
  3508. $body.classList.toggle('Notifications', isOnNotificationsPage())
  3509. $body.classList.toggle('Profile', isOnProfilePage())
  3510. if (!isOnProfilePage()) {
  3511. $body.classList.remove('Blocked', 'NoMedia')
  3512. }
  3513. $body.classList.toggle('QuoteTweets', isOnQuoteTweetsPage())
  3514. $body.classList.toggle('Tweet', isOnIndividualTweetPage())
  3515. $body.classList.toggle('Search', isOnSearchPage())
  3516. $body.classList.toggle('Settings', isOnSettingsPage())
  3517. $body.classList.toggle('MobileMedia', mobile && URL_MEDIA_RE.test(location.pathname))
  3518. $body.classList.toggle('MediaViewer', mobile && URL_MEDIAVIEWER_RE.test(location.pathname))
  3519. $body.classList.remove('TabbedTimeline')
  3520. $body.classList.remove('SeparatedTweets')
  3521.  
  3522. if (desktop) {
  3523. if (config.twitterBlueChecks != 'ignore' || config.fullWidthContent && (isOnMainTimelinePage() || isOnListPage())) {
  3524. observeSidebar()
  3525. } else {
  3526. $body.classList.remove('Sidebar')
  3527. }
  3528. if (isSafari && config.replaceLogo) {
  3529. tweakDesktopLogo()
  3530. }
  3531. }
  3532.  
  3533. if (config.twitterBlueChecks != 'ignore' && (isOnSearchPage() || isOnExplorePage())) {
  3534. observeSearchForm()
  3535. }
  3536.  
  3537. if (isOnMainTimelinePage()) {
  3538. tweakMainTimelinePage()
  3539. }
  3540. else {
  3541. removeMobileTimelineHeaderElements()
  3542. }
  3543.  
  3544. if (isOnProfilePage()) {
  3545. tweakProfilePage()
  3546. }
  3547. else if (isOnFollowListPage()) {
  3548. tweakFollowListPage()
  3549. }
  3550. else if (isOnIndividualTweetPage()) {
  3551. tweakIndividualTweetPage()
  3552. }
  3553. else if (isOnNotificationsPage()) {
  3554. tweakNotificationsPage()
  3555. }
  3556. else if (isOnSearchPage()) {
  3557. tweakSearchPage()
  3558. }
  3559. else if (isOnQuoteTweetsPage()) {
  3560. tweakQuoteTweetsPage()
  3561. }
  3562. else if (isOnListPage()) {
  3563. tweakListPage()
  3564. }
  3565. else if (isOnExplorePage()) {
  3566. tweakExplorePage()
  3567. }
  3568. else if (isOnBookmarksPage()) {
  3569. tweakBookmarksPage()
  3570. }
  3571. else if (isOnCommunitiesPage()) {
  3572. tweakCommunitiesPage()
  3573. }
  3574. else if (isOnCommunityPage()) {
  3575. tweakCommunityPage()
  3576. }
  3577. else if (isOnCommunityMembersPage()) {
  3578. tweakCommunityMembersPage()
  3579. }
  3580.  
  3581. // On mobile, these are pages instead of modals
  3582. if (mobile) {
  3583. if (currentPath == PagePaths.COMPOSE_TWEET) {
  3584. tweakMobileComposeTweetPage()
  3585. }
  3586. else if (URL_MEDIAVIEWER_RE.test(currentPath)) {
  3587. tweakMobileMediaViewerPage()
  3588. }
  3589. else if (URL_TWEET_LIKES_RETWEETS_RE.test(currentPath)) {
  3590. tweakMobileUserListPage()
  3591. }
  3592. }
  3593. }
  3594.  
  3595. /**
  3596. * The mobile version of Twitter reuses heading elements between screens, so we
  3597. * always remove any elements which could be there from the previous page and
  3598. * re-add them later when needed.
  3599. */
  3600. function removeMobileTimelineHeaderElements() {
  3601. if (mobile) {
  3602. document.querySelector('#tnt_separated_tweets_tab')?.remove()
  3603. }
  3604. }
  3605.  
  3606. /**
  3607. * Sets the page name in <title>, retaining any current notification count.
  3608. * @param {string} page
  3609. */
  3610. function setTitle(page) {
  3611. document.title = ltr ? (
  3612. `${currentNotificationCount}${page} / ${getString('TWITTER')}`
  3613. ) : (
  3614. `${currentNotificationCount}${getString('TWITTER')} \\ ${page}`
  3615. )
  3616. }
  3617.  
  3618. /**
  3619. * @param {import("./types").TimelineItemType} type
  3620. * @returns {boolean}
  3621. */
  3622. function shouldHideIndividualTweetTimelineItem(type) {
  3623. switch (type) {
  3624. case 'QUOTE_TWEET':
  3625. case 'RETWEET':
  3626. case 'RETWEETED_QUOTE_TWEET':
  3627. case 'TWEET':
  3628. return false
  3629. case 'UNAVAILABLE_QUOTE_TWEET':
  3630. case 'UNAVAILABLE_RETWEET':
  3631. return config.hideUnavailableQuoteTweets
  3632. default:
  3633. return true
  3634. }
  3635. }
  3636.  
  3637. /**
  3638. * @param {import("./types").TimelineItemType} type
  3639. * @returns {boolean}
  3640. */
  3641. function shouldHideListTimelineItem(type) {
  3642. switch (type) {
  3643. case 'RETWEET':
  3644. case 'RETWEETED_QUOTE_TWEET':
  3645. return config.listRetweets == 'hide'
  3646. case 'UNAVAILABLE_QUOTE_TWEET':
  3647. return config.hideUnavailableQuoteTweets
  3648. case 'UNAVAILABLE_RETWEET':
  3649. return config.hideUnavailableQuoteTweets || config.listRetweets == 'hide'
  3650. default:
  3651. return false
  3652. }
  3653. }
  3654.  
  3655. /**
  3656. * @param {import("./types").TimelineItemType} type
  3657. * @param {string} page
  3658. * @returns {boolean}
  3659. */
  3660. function shouldHideMainTimelineItem(type, page) {
  3661. switch (type) {
  3662. case 'QUOTE_TWEET':
  3663. return shouldHideSharedTweet(config.quoteTweets, page)
  3664. case 'RETWEET':
  3665. return selectedHomeTabIndex >= 2 ? config.listRetweets == 'hide' : shouldHideSharedTweet(config.retweets, page)
  3666. case 'RETWEETED_QUOTE_TWEET':
  3667. return selectedHomeTabIndex >= 2 ? (
  3668. config.listRetweets == 'hide'
  3669. ) : (
  3670. shouldHideSharedTweet(config.retweets, page) || shouldHideSharedTweet(config.quoteTweets, page)
  3671. )
  3672. case 'TWEET':
  3673. return page == separatedTweetsTimelineTitle
  3674. case 'UNAVAILABLE_QUOTE_TWEET':
  3675. return config.hideUnavailableQuoteTweets || shouldHideSharedTweet(config.quoteTweets, page)
  3676. case 'UNAVAILABLE_RETWEET':
  3677. return config.hideUnavailableQuoteTweets || selectedHomeTabIndex >= 2 ? config.listRetweets == 'hide' : shouldHideSharedTweet(config.retweets, page)
  3678. default:
  3679. return true
  3680. }
  3681. }
  3682.  
  3683. /**
  3684. * @param {import("./types").TimelineItemType} type
  3685. * @returns {boolean}
  3686. */
  3687. function shouldHideProfileTimelineItem(type) {
  3688. switch (type) {
  3689. case 'PINNED_TWEET':
  3690. case 'QUOTE_TWEET':
  3691. case 'TWEET':
  3692. return false
  3693. case 'RETWEET':
  3694. case 'RETWEETED_QUOTE_TWEET':
  3695. return config.hideProfileRetweets
  3696. case 'UNAVAILABLE_QUOTE_TWEET':
  3697. return config.hideUnavailableQuoteTweets
  3698. default:
  3699. return true
  3700. }
  3701. }
  3702.  
  3703. /**
  3704. * @param {import("./types").TimelineItemType} type
  3705. * @returns {boolean}
  3706. */
  3707. function shouldHideOtherTimelineItem(type) {
  3708. switch (type) {
  3709. case 'QUOTE_TWEET':
  3710. case 'RETWEET':
  3711. case 'RETWEETED_QUOTE_TWEET':
  3712. case 'TWEET':
  3713. case 'UNAVAILABLE':
  3714. case 'UNAVAILABLE_QUOTE_TWEET':
  3715. case 'UNAVAILABLE_RETWEET':
  3716. return false
  3717. default:
  3718. return true
  3719. }
  3720. }
  3721.  
  3722. /**
  3723. * @param {import("./types").SharedTweetsConfig} config
  3724. * @param {string} page
  3725. * @returns {boolean}
  3726. */
  3727. function shouldHideSharedTweet(config, page) {
  3728. switch (config) {
  3729. case 'hide': return true
  3730. case 'ignore': return page == separatedTweetsTimelineTitle
  3731. case 'separate': return page != separatedTweetsTimelineTitle
  3732. }
  3733. }
  3734.  
  3735. async function tweakBookmarksPage() {
  3736. if (config.twitterBlueChecks != 'ignore') {
  3737. observeTimeline(currentPage, {
  3738. classifyTweets: false,
  3739. })
  3740. }
  3741. }
  3742.  
  3743. async function tweakExplorePage() {
  3744. if (!config.hideExplorePageContents) return
  3745.  
  3746. let $searchInput = await getElement('input[data-testid="SearchBox_Search_Input"]', {
  3747. name: 'explore page search input',
  3748. stopIf: () => !isOnExplorePage(),
  3749. })
  3750. if (!$searchInput) return
  3751.  
  3752. log('focusing search input')
  3753. $searchInput.focus()
  3754.  
  3755. if (mobile) {
  3756. // The back button appears after the search input is focused on mobile. When
  3757. // you tap it or otherwise navigate back, it's replaced with the slide-out
  3758. // menu button and Explore page contents are shown - we want to skip that.
  3759. let $backButton = await getElement('div[data-testid="app-bar-back"]', {
  3760. name: 'back button',
  3761. stopIf: () => !isOnExplorePage(),
  3762. })
  3763. if (!$backButton) return
  3764.  
  3765. pageObservers.push(
  3766. observeElement($backButton.parentElement, (mutations) => {
  3767. mutations.forEach((mutation) => {
  3768. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3769. if ($el.querySelector('[data-testid="DashButton_ProfileIcon_Link"]')) {
  3770. log('slide-out menu button appeared, going back to skip Explore page')
  3771. history.go(-2)
  3772. }
  3773. })
  3774. })
  3775. }, 'back button parent')
  3776. )
  3777. }
  3778. }
  3779.  
  3780. function tweakCommunitiesPage() {
  3781. observeTimeline(currentPage)
  3782. }
  3783.  
  3784. function tweakCommunityPage() {
  3785. if (config.twitterBlueChecks != 'ignore') {
  3786. observeTimeline(currentPage, {
  3787. classifyTweets: false,
  3788. isTabbed: true,
  3789. tabbedTimelineContainerSelector: `${Selectors.PRIMARY_COLUMN} > div > div:last-child`,
  3790. onTimelineAppeared() {
  3791. // The About tab has static content at the top which can include a check
  3792. if (/\/about\/?$/.test(location.pathname)) {
  3793. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  3794. }
  3795. }
  3796. })
  3797. }
  3798. }
  3799.  
  3800. function tweakCommunityMembersPage() {
  3801. if (config.twitterBlueChecks != 'ignore') {
  3802. observeTimeline(currentPage, {
  3803. classifyTweets: false,
  3804. isTabbed: true,
  3805. timelineSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  3806. })
  3807. }
  3808. }
  3809.  
  3810. function tweakFollowListPage() {
  3811. if (config.twitterBlueChecks != 'ignore') {
  3812. observeTimeline(currentPage, {
  3813. classifyTweets: false,
  3814. })
  3815. }
  3816. }
  3817.  
  3818. function tweakIndividualTweetPage() {
  3819. observeTimeline(currentPage, {
  3820. hideHeadings: false,
  3821. onTimelineItemsChanged: onIndividualTweetTimelineChange
  3822. })
  3823. }
  3824.  
  3825. function tweakListPage() {
  3826. observeTimeline(currentPage, {
  3827. hideHeadings: false,
  3828. })
  3829. }
  3830.  
  3831. async function tweakDesktopLogo() {
  3832. let $logoPath = await getElement(`h1 ${Selectors.X_LOGO_PATH}`, {name: 'desktop nav logo', timeout: 5000})
  3833. if ($logoPath) {
  3834. twitterLogo($logoPath)
  3835. }
  3836. }
  3837.  
  3838. async function tweakTweetBox() {
  3839. if (config.twitterBlueChecks == 'ignore') return
  3840.  
  3841. let $tweetTextarea = await getElement(`${desktop ? 'div[data-testid="primaryColumn"]': 'main'} label[data-testid^="tweetTextarea"]`, {
  3842. name: 'tweet textarea',
  3843. stopIf: pageIsNot(currentPage),
  3844. })
  3845. if (!$tweetTextarea) return
  3846.  
  3847. /** @type {HTMLElement} */
  3848. let $typeaheadDropdown
  3849.  
  3850. pageObservers.push(
  3851. observeElement($tweetTextarea.parentElement.parentElement.parentElement.parentElement, (mutations) => {
  3852. for (let mutation of mutations) {
  3853. if ($typeaheadDropdown && mutations.some(mutation => Array.from(mutation.removedNodes).includes($typeaheadDropdown))) {
  3854. disconnectPageObserver('tweet textarea typeahead dropdown')
  3855. $typeaheadDropdown = null
  3856. }
  3857. for (let $addedNode of mutation.addedNodes) {
  3858. if ($addedNode instanceof HTMLElement && $addedNode.getAttribute('id')?.startsWith('typeaheadDropdown')) {
  3859. $typeaheadDropdown = $addedNode
  3860. pageObservers.push(
  3861. observeElement($typeaheadDropdown, () => {
  3862. processBlueChecks($typeaheadDropdown)
  3863. }, 'tweet textarea typeahead dropdown')
  3864. )
  3865. }
  3866. }
  3867. }
  3868. }, 'tweet textarea typeahead dropdown container')
  3869. )
  3870. }
  3871.  
  3872. function tweakMainTimelinePage() {
  3873. if (desktop) {
  3874. tweakTweetBox()
  3875. }
  3876.  
  3877. let $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3878.  
  3879. // "Which version of the main timeline are we on?" hooks for styling
  3880. $body.classList.toggle('TabbedTimeline', $timelineTabs != null)
  3881. $body.classList.toggle('SeparatedTweets', isOnSeparatedTweetsTimeline())
  3882.  
  3883. if ($timelineTabs == null) {
  3884. warn('could not find timeline tabs')
  3885. return
  3886. }
  3887.  
  3888. tweakTimelineTabs($timelineTabs)
  3889. if (mobile && isSafari && config.replaceLogo) {
  3890. processTwitterLogos(document.querySelector(Selectors.MOBILE_TIMELINE_HEADER_NEW))
  3891. }
  3892.  
  3893. function updateSelectedHomeTabIndex() {
  3894. let $selectedHomeTabLink = $timelineTabs.querySelector('div[role="tablist"] a[aria-selected="true"]')
  3895. if ($selectedHomeTabLink) {
  3896. selectedHomeTabIndex = Array.from($selectedHomeTabLink.parentElement.parentElement.children).indexOf($selectedHomeTabLink.parentElement)
  3897. log({selectedHomeTabIndex})
  3898. } else {
  3899. warn('could not find selected Home tab link')
  3900. selectedHomeTabIndex = -1
  3901. }
  3902. }
  3903.  
  3904. updateSelectedHomeTabIndex()
  3905.  
  3906. // If there are pinned lists, the timeline tabs <nav> will be replaced when they load
  3907. pageObservers.push(
  3908. observeElement($timelineTabs.parentElement, (mutations) => {
  3909. let timelineTabsReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($timelineTabs))
  3910. if (timelineTabsReplaced) {
  3911. log('timeline tabs replaced')
  3912. $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3913. tweakTimelineTabs($timelineTabs)
  3914. }
  3915. }, 'timeline tabs nav container')
  3916. )
  3917.  
  3918. observeTimeline(currentPage, {
  3919. isTabbed: true,
  3920. onTabChanged: () => {
  3921. updateSelectedHomeTabIndex()
  3922. wasForYouTabSelected = selectedHomeTabIndex == 0
  3923. },
  3924. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child > div',
  3925. })
  3926. }
  3927.  
  3928. function tweakMobileComposeTweetPage() {
  3929. tweakTweetBox()
  3930. }
  3931.  
  3932. function tweakMobileMediaViewerPage() {
  3933. if (config.twitterBlueChecks == 'ignore') return
  3934.  
  3935. let $timeline = /** @type {HTMLElement} */ (document.querySelector('[data-testid="vss-scroll-view"] > div'))
  3936. if (!$timeline) {
  3937. warn('media viewer timeline not found')
  3938. return
  3939. }
  3940.  
  3941. observeElement($timeline, (mutations) => {
  3942. for (let mutation of mutations) {
  3943. if (!mutation.addedNodes) continue
  3944. for (let $addedNode of mutation.addedNodes) {
  3945. if ($addedNode.querySelector?.('div[data-testid^="immersive-tweet-ui-content-container"]')) {
  3946. processBlueChecks($addedNode)
  3947. }
  3948. }
  3949. }
  3950. }, 'media viewer timeline', {childList: true, subtree: true})
  3951. }
  3952.  
  3953. async function tweakTimelineTabs($timelineTabs) {
  3954. let $followingTabLink = /** @type {HTMLElement} */ ($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a'))
  3955.  
  3956. if (config.alwaysUseLatestTweets && !document.title.startsWith(separatedTweetsTimelineTitle)) {
  3957. let isForYouTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:first-child > a[aria-selected="true"]'))
  3958. if (isForYouTabSelected && (!wasForYouTabSelected || config.hideForYouTimeline)) {
  3959. log('switching to Following timeline')
  3960. $followingTabLink.click()
  3961. wasForYouTabSelected = false
  3962. } else {
  3963. wasForYouTabSelected = isForYouTabSelected
  3964. }
  3965. }
  3966.  
  3967. if (shouldShowSeparatedTweetsTab()) {
  3968. let $newTab = /** @type {HTMLElement} */ ($timelineTabs.querySelector('#tnt_separated_tweets_tab'))
  3969. if ($newTab) {
  3970. log('separated tweets timeline tab already present')
  3971. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  3972. }
  3973. else {
  3974. log('inserting separated tweets tab')
  3975. $newTab = /** @type {HTMLElement} */ ($followingTabLink.parentElement.cloneNode(true))
  3976. $newTab.id = 'tnt_separated_tweets_tab'
  3977. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  3978. let $link = $newTab.querySelector('a')
  3979. $link.removeAttribute('aria-selected')
  3980.  
  3981. // This script assumes navigation has occurred when the document title
  3982. // changes, so by changing the title we fake navigation to a non-existent
  3983. // page representing the separated tweets timeline.
  3984. $link.addEventListener('click', (e) => {
  3985. e.preventDefault()
  3986. e.stopPropagation()
  3987. if (!document.title.startsWith(separatedTweetsTimelineTitle)) {
  3988. // The separated tweets tab belongs to the Following tab
  3989. let isFollowingTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  3990. if (!isFollowingTabSelected) {
  3991. log('switching to the Following tab for separated tweets')
  3992. $followingTabLink.click()
  3993. }
  3994. setTitle(separatedTweetsTimelineTitle)
  3995. }
  3996. window.scrollTo({top: 0})
  3997. })
  3998. $followingTabLink.parentElement.insertAdjacentElement('afterend', $newTab)
  3999.  
  4000. // Return to the main timeline view when any other tab is clicked
  4001. $followingTabLink.parentElement.parentElement.addEventListener('click', () => {
  4002. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  4003. log('setting title to Home')
  4004. homeNavigationIsBeingUsed = true
  4005. setTitle(getString('HOME'))
  4006. }
  4007. })
  4008.  
  4009. // Return to the main timeline when the Home nav link is clicked
  4010. let $homeNavLink = await getElement(Selectors.NAV_HOME_LINK, {
  4011. name: 'home nav link',
  4012. stopIf: pathIsNot(currentPath),
  4013. })
  4014. if ($homeNavLink && !$homeNavLink.dataset.tweakNewTwitterListener) {
  4015. $homeNavLink.addEventListener('click', () => {
  4016. homeNavigationIsBeingUsed = true
  4017. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  4018. setTitle(getString('HOME'))
  4019. }
  4020. })
  4021. $homeNavLink.dataset.tweakNewTwitterListener = 'true'
  4022. }
  4023. }
  4024. } else {
  4025. removeMobileTimelineHeaderElements()
  4026. }
  4027. }
  4028.  
  4029. function tweakMobileUserListPage() {
  4030. if (config.twitterBlueChecks == 'ignore') return
  4031.  
  4032. observeUserListTimeline(undefined, currentPath)
  4033. }
  4034.  
  4035. function tweakNotificationsPage() {
  4036. let $navigationTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4037. if ($navigationTabs == null) {
  4038. warn('could not find Notifications tabs')
  4039. return
  4040. }
  4041.  
  4042. if (config.hideVerifiedNotificationsTab) {
  4043. let isVerifiedTabSelected = Boolean($navigationTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  4044. if (isVerifiedTabSelected) {
  4045. log('switching to All tab')
  4046. $navigationTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a')?.click()
  4047. }
  4048. }
  4049.  
  4050. if (config.twitterBlueChecks != 'ignore') {
  4051. observeTimeline(currentPage, {
  4052. classifyTweets: false,
  4053. isTabbed: true,
  4054. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  4055. })
  4056. }
  4057. }
  4058.  
  4059. function tweakProfilePage() {
  4060. if (config.twitterBlueChecks != 'ignore') {
  4061. if (mobile) {
  4062. processBlueChecks(document.querySelector(Selectors.MOBILE_TIMELINE_HEADER_NEW))
  4063. }
  4064. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  4065. }
  4066. observeTimeline(currentPage)
  4067. if (desktop && config.hideSidebarContent) {
  4068. observeProfileBlockedStatus(currentPage)
  4069. observeProfileSidebar(currentPage)
  4070. }
  4071. }
  4072.  
  4073. function tweakQuoteTweetsPage() {
  4074. if (config.twitterBlueChecks != 'ignore') {
  4075. observeTimeline(currentPage)
  4076. }
  4077. }
  4078.  
  4079. function tweakSearchPage() {
  4080. let $searchTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4081. if ($searchTabs != null) {
  4082. if (config.defaultToLatestSearch) {
  4083. let isTopTabSelected = Boolean($searchTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a[aria-selected="true"]'))
  4084. if (isTopTabSelected) {
  4085. log('switching to Latest tab')
  4086. $searchTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a')?.click()
  4087. }
  4088. }
  4089. } else {
  4090. warn('could not find Search tabs')
  4091. }
  4092.  
  4093. observeTimeline(currentPage, {
  4094. hideHeadings: false,
  4095. isTabbed: true,
  4096. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  4097. })
  4098. }
  4099. //#endregion
  4100.  
  4101. //#region Main
  4102. async function main() {
  4103. let $settings = /** @type {HTMLScriptElement} */ (document.querySelector('script#tnt_settings'))
  4104. if ($settings) {
  4105. try {
  4106. Object.assign(config, JSON.parse($settings.innerText))
  4107. } catch(e) {
  4108. error('error parsing initial settings', e)
  4109. }
  4110.  
  4111. let settingsChangeObserver = new MutationObserver(() => {
  4112. /** @type {Partial<import("./types").Config>} */
  4113. let configChanges
  4114. try {
  4115. configChanges = JSON.parse($settings.innerText)
  4116. } catch(e) {
  4117. error('error parsing incoming settings change', e)
  4118. return
  4119. }
  4120.  
  4121. if ('debug' in configChanges) {
  4122. log('disabling debug mode')
  4123. debug = configChanges.debug
  4124. log('enabled debug mode')
  4125. configureThemeCss()
  4126. return
  4127. }
  4128.  
  4129. Object.assign(config, configChanges)
  4130. configChanged(configChanges)
  4131. })
  4132. settingsChangeObserver.observe($settings, {childList: true})
  4133. }
  4134.  
  4135. if (config.debug) {
  4136. debug = true
  4137. }
  4138.  
  4139. observeTitle()
  4140.  
  4141. let $loadingStyle
  4142. if (config.replaceLogo) {
  4143. getElement('html', {name: 'html element'}).then(($html) => {
  4144. $loadingStyle = document.createElement('style')
  4145. $loadingStyle.dataset.insertedBy = 'control-panel-for-twitter'
  4146. $loadingStyle.dataset.role = 'loading-logo'
  4147. let logoThemeColor = themeColor || Array.from(THEME_COLORS)[0]
  4148. $loadingStyle.textContent = dedent(`
  4149. ${Selectors.X_LOGO_PATH} {
  4150. fill: ${isSafari ? 'transparent' : logoThemeColor};
  4151. d: path("${Svgs.TWITTER_LOGO_PATH}");
  4152. }
  4153. .tnt_logo {
  4154. fill: ${logoThemeColor};
  4155. }
  4156. `)
  4157. $html.appendChild($loadingStyle)
  4158. })
  4159.  
  4160. if (isSafari) {
  4161. getElement(Selectors.X_LOGO_PATH, {name: 'pre-loading indicator logo', timeout: 1000}).then(($logoPath) => {
  4162. if ($logoPath) {
  4163. twitterLogo($logoPath)
  4164. }
  4165. })
  4166. }
  4167.  
  4168. observeFavicon()
  4169. }
  4170.  
  4171. let $appWrapper = await getElement('#layers + div', {name: 'app wrapper'})
  4172.  
  4173. $html = document.querySelector('html')
  4174. $body = document.body
  4175. $reactRoot = document.querySelector('#react-root')
  4176. lang = $html.lang
  4177. dir = $html.dir
  4178. ltr = dir == 'ltr'
  4179. let lastFlexDirection
  4180.  
  4181. observeElement($appWrapper, () => {
  4182. let flexDirection = getComputedStyle($appWrapper).flexDirection
  4183.  
  4184. mobile = flexDirection == 'column'
  4185. desktop = !mobile
  4186.  
  4187. /** @type {'mobile' | 'desktop'} */
  4188. let version = mobile ? 'mobile' : 'desktop'
  4189.  
  4190. if (version != config.version) {
  4191. log('setting version to', version)
  4192. config.version = version
  4193. // Let the options page know which version is being used
  4194. storeConfigChanges({version})
  4195. }
  4196.  
  4197. if (lastFlexDirection == null) {
  4198. log('initial config', {config, lang, version})
  4199.  
  4200. // One-time setup
  4201. checkReactNativeStylesheet()
  4202. observeBodyBackgroundColor()
  4203. observeColor()
  4204.  
  4205. // Repeatable configuration setup
  4206. configureSeparatedTweetsTimelineTitle()
  4207. configureCss()
  4208. configureThemeCss()
  4209. observeHtmlFontSize()
  4210. observePopups()
  4211.  
  4212. // Start taking action on page changes
  4213. observingPageChanges = true
  4214.  
  4215. // Delay removing loading icon styles to avoid Flash of X
  4216. if ($loadingStyle) {
  4217. setTimeout(() => $loadingStyle.remove(), 1000)
  4218. }
  4219. }
  4220. else if (flexDirection != lastFlexDirection) {
  4221. observeHtmlFontSize()
  4222. configChanged({version})
  4223. }
  4224.  
  4225. $body.classList.toggle('Mobile', mobile)
  4226. $body.classList.toggle('Desktop', desktop)
  4227.  
  4228. lastFlexDirection = flexDirection
  4229. }, 'app wrapper class attribute for version changes (mobile ↔ desktop)', {
  4230. attributes: true,
  4231. attributeFilter: ['class']
  4232. })
  4233. }
  4234.  
  4235. /**
  4236. * @param {Partial<import("./types").Config>} changes
  4237. */
  4238. function configChanged(changes) {
  4239. log('config changed', changes)
  4240.  
  4241. configureCss()
  4242. configureFont()
  4243. configureNavFontSizeCss()
  4244. configureThemeCss()
  4245. observeFavicon()
  4246. observePopups()
  4247.  
  4248. // Only re-process the current page if navigation wasn't already triggered
  4249. // while applying the following config changes (if there were any).
  4250. let navigationTriggered = (
  4251. configureSeparatedTweetsTimelineTitle() ||
  4252. checkforDisabledHomeTimeline()
  4253. )
  4254. if (!navigationTriggered) {
  4255. processCurrentPage()
  4256. }
  4257. }
  4258.  
  4259. main()
  4260. //#endregion
  4261.  
  4262. }()