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 124
  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. * MutationObservers active on the current page, or anything else we want to
  885. * clean up when the user moves off the current page.
  886. * @type {import("./types").Disconnectable[]}
  887. */
  888. let pageObservers = []
  889.  
  890. /** `true` when a 'Pin to your profile' menu item was seen in the last popup. */
  891. let pinMenuItemSeen = false
  892.  
  893. /** @type {number} */
  894. let selectedHomeTabIndex = -1
  895.  
  896. /**
  897. * Title for the fake timeline used to separate out retweets and quote tweets.
  898. * @type {string}
  899. */
  900. let separatedTweetsTimelineTitle = null
  901.  
  902. /**
  903. * The current "Color" setting, which can be changed in "Customize your view".
  904. * @type {string}
  905. */
  906. let themeColor = localStorage.lastThemeColor
  907.  
  908. /**
  909. * `true` when "For you" was the last tab selected on the main timeline.
  910. */
  911. let wasForYouTabSelected = false
  912.  
  913. function isOnBookmarksPage() {
  914. return currentPath == PagePaths.BOOKMARKS
  915. }
  916.  
  917. function isOnCommunitiesPage() {
  918. return URL_COMMUNITIES_RE.test(currentPath)
  919. }
  920.  
  921. function isOnCommunityPage() {
  922. return URL_COMMUNITY_RE.test(currentPath)
  923. }
  924.  
  925. function isOnCommunityMembersPage() {
  926. return URL_COMMUNITY_MEMBERS_RE.test(currentPath)
  927. }
  928.  
  929. function isOnDiscoverCommunitiesPage() {
  930. return URL_DISCOVER_COMMUNITIES_RE.test(currentPath)
  931. }
  932.  
  933. function isOnExplorePage() {
  934. return currentPath.startsWith('/explore')
  935. }
  936.  
  937. function isOnFollowListPage() {
  938. return URL_PROFILE_FOLLOWS_RE.test(currentPath)
  939. }
  940.  
  941. function isOnHomeTimeline() {
  942. return currentPage == getString('HOME')
  943. }
  944.  
  945. function isOnIndividualTweetPage() {
  946. return URL_TWEET_RE.test(currentPath)
  947. }
  948.  
  949. function isOnListPage() {
  950. return URL_LIST_RE.test(currentPath)
  951. }
  952.  
  953. function isOnMainTimelinePage() {
  954. return currentPath == PagePaths.HOME || (
  955. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW &&
  956. isOnHomeTimeline() ||
  957. isOnSeparatedTweetsTimeline()
  958. )
  959. }
  960.  
  961. function isOnNotificationsPage() {
  962. return currentPath.startsWith('/notifications')
  963. }
  964.  
  965. function isOnProfilePage() {
  966. let profilePathUsername = currentPath.match(URL_PROFILE_RE)?.[1]
  967. if (!profilePathUsername) return false
  968. // twitter.com/user and its sub-URLs put @user in the title
  969. return currentPage.toLowerCase().includes(`${ltr ? '@' : ''}${profilePathUsername.toLowerCase()}${!ltr ? '@' : ''}`)
  970. }
  971.  
  972. function isOnQuoteTweetsPage() {
  973. return currentPath.endsWith('/retweets/with_comments')
  974. }
  975.  
  976. function isOnSearchPage() {
  977. return currentPath.startsWith('/search') || currentPath.startsWith('/hashtag/')
  978. }
  979.  
  980. function isOnSeparatedTweetsTimeline() {
  981. return currentPage == separatedTweetsTimelineTitle
  982. }
  983.  
  984. function isOnSettingsPage() {
  985. return currentPath.startsWith('/settings')
  986. }
  987.  
  988. function shouldHideSidebar() {
  989. return isOnExplorePage() || isOnDiscoverCommunitiesPage()
  990. }
  991.  
  992. function shouldShowSeparatedTweetsTab() {
  993. return config.retweets == 'separate' || config.quoteTweets == 'separate'
  994. }
  995. //#endregion
  996.  
  997. //#region Utility functions
  998. /**
  999. * @param {string} role
  1000. * @return {HTMLStyleElement}
  1001. */
  1002. function addStyle(role) {
  1003. let $style = document.createElement('style')
  1004. $style.dataset.insertedBy = 'control-panel-for-twitter'
  1005. $style.dataset.role = role
  1006. document.head.appendChild($style)
  1007. return $style
  1008. }
  1009.  
  1010. /**
  1011. * @param {Element} $svg
  1012. */
  1013. function blueCheck($svg) {
  1014. if (!$svg) {
  1015. warn('blueCheck was given', $svg)
  1016. return
  1017. }
  1018. $svg.classList.add('tnt_blue_check')
  1019. // Safari doesn't support using `d: path(…)` to replace paths in an SVG, so
  1020. // we have to manually patch the path in it.
  1021. if (isSafari && config.twitterBlueChecks == 'replace') {
  1022. $svg.firstElementChild.firstElementChild.setAttribute('d', Svgs.BLUE_LOGO_PATH)
  1023. }
  1024. }
  1025.  
  1026. /**
  1027. * @param {Element} $svgPath
  1028. */
  1029. function twitterLogo($svgPath) {
  1030. // Safari doesn't support using `d: path(…)` to replace paths in an SVG, so
  1031. // we have to manually patch the path in it.
  1032. $svgPath.setAttribute('d', Svgs.TWITTER_LOGO_PATH)
  1033. $svgPath.parentElement.classList.add('tnt_logo')
  1034. }
  1035.  
  1036. /**
  1037. * @param {string} str
  1038. * @return {string}
  1039. */
  1040. function dedent(str) {
  1041. str = str.replace(/^[ \t]*\r?\n/, '')
  1042. let indent = /^[ \t]+/m.exec(str)
  1043. if (indent) str = str.replace(new RegExp('^' + indent[0], 'gm'), '')
  1044. return str.replace(/(\r?\n)[ \t]+$/, '$1')
  1045. }
  1046.  
  1047. /**
  1048. * @param {string} name
  1049. * @param {import("./types").Disconnectable[]} observers
  1050. * @param {string?} type
  1051. */
  1052. function disconnectObserver(name, observers, type = 'observer') {
  1053. for (let i = observers.length -1; i >= 0; i--) {
  1054. let observer = observers[i]
  1055. if ('name' in observer && observer.name == name) {
  1056. observer.disconnect()
  1057. observers.splice(i, 1)
  1058. log(`disconnected ${name} ${type}`)
  1059. }
  1060. }
  1061. }
  1062.  
  1063. function disconnectModalObserver(name) {
  1064. disconnectObserver(name, modalObservers)
  1065. }
  1066.  
  1067. function disconnectAllModalObservers() {
  1068. if (modalObservers.length > 0) {
  1069. log(
  1070. `disconnecting ${modalObservers.length} modal observer${s(modalObservers.length)}`,
  1071. modalObservers.map(observer => observer['name'])
  1072. )
  1073. modalObservers.forEach(observer => observer.disconnect())
  1074. modalObservers = []
  1075. }
  1076. }
  1077.  
  1078. function disconnectPageObserver(name) {
  1079. disconnectObserver(name, pageObservers, 'page observer')
  1080. }
  1081.  
  1082. /**
  1083. * @param {string} selector
  1084. * @param {{
  1085. * name?: string
  1086. * stopIf?: () => boolean
  1087. * timeout?: number
  1088. * context?: Document | HTMLElement
  1089. * }?} options
  1090. * @returns {Promise<HTMLElement | null>}
  1091. */
  1092. function getElement(selector, {
  1093. name = null,
  1094. stopIf = null,
  1095. timeout = Infinity,
  1096. context = document,
  1097. } = {}) {
  1098. return new Promise((resolve) => {
  1099. let startTime = Date.now()
  1100. let rafId
  1101. let timeoutId
  1102.  
  1103. function stop($element, reason) {
  1104. if ($element == null) {
  1105. warn(`stopped waiting for ${name || selector} after ${reason}`)
  1106. }
  1107. else if (Date.now() > startTime) {
  1108. log(`${name || selector} appeared after ${Date.now() - startTime}ms`)
  1109. }
  1110. if (rafId) {
  1111. cancelAnimationFrame(rafId)
  1112. }
  1113. if (timeoutId) {
  1114. clearTimeout(timeoutId)
  1115. }
  1116. resolve($element)
  1117. }
  1118.  
  1119. if (timeout !== Infinity) {
  1120. timeoutId = setTimeout(stop, timeout, null, `${timeout}ms timeout`)
  1121. }
  1122.  
  1123. function queryElement() {
  1124. let $element = context.querySelector(selector)
  1125. if ($element) {
  1126. stop($element)
  1127. }
  1128. else if (stopIf?.() === true) {
  1129. stop(null, 'stopIf condition met')
  1130. }
  1131. else {
  1132. rafId = requestAnimationFrame(queryElement)
  1133. }
  1134. }
  1135.  
  1136. queryElement()
  1137. })
  1138. }
  1139.  
  1140. /**
  1141. * Gets cached user info from React state.
  1142. * @returns {import("./types").UserInfoObject}
  1143. */
  1144. function getUserInfo() {
  1145. /** @type {import("./types").UserInfoObject} */
  1146. let userInfo = {}
  1147. let reactRootContainer = ($reactRoot?.wrappedJSObject ? $reactRoot.wrappedJSObject : $reactRoot)?._reactRootContainer
  1148. if (reactRootContainer) {
  1149. let userEntities = reactRootContainer?._internalRoot?.current?.memoizedState?.element?.props?.children?.props?.store?.getState()?.entities?.users?.entities
  1150. if (userEntities) {
  1151. for (let user of Object.values(userEntities)) {
  1152. userInfo[user.screen_name] = {following: user.following, followedBy: user.followed_by, followersCount: user.followers_count}
  1153. }
  1154. } else {
  1155. warn('user entities not found')
  1156. }
  1157. } else {
  1158. warn('React root container not found')
  1159. }
  1160. return userInfo
  1161. }
  1162.  
  1163. function log(...args) {
  1164. if (debug) {
  1165. console.log(`${currentPage ? `(${
  1166. currentPage.length < 70 ? currentPage : currentPage.slice(0, 70) + '…'
  1167. })` : ''}`, ...args)
  1168. }
  1169. }
  1170.  
  1171. function warn(...args) {
  1172. if (debug) {
  1173. console.log(`❗ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1174. }
  1175. }
  1176.  
  1177. function error(...args) {
  1178. console.log(`❌ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1179. }
  1180.  
  1181. /**
  1182. * @param {() => boolean} condition
  1183. * @returns {() => boolean}
  1184. */
  1185. function not(condition) {
  1186. return () => !condition()
  1187. }
  1188.  
  1189. /**
  1190. * Convenience wrapper for the MutationObserver API - the callback is called
  1191. * immediately to support using an observer and its options as a trigger for any
  1192. * change, without looking at MutationRecords.
  1193. * @param {Node} $element
  1194. * @param {MutationCallback} callback
  1195. * @param {string} name
  1196. * @param {MutationObserverInit} options
  1197. * @return {import("./types").NamedMutationObserver}
  1198. */
  1199. function observeElement($element, callback, name = '', options = {childList: true}) {
  1200. if (name) {
  1201. if (options.childList && callback.length > 0) {
  1202. log(`observing ${name}`, $element)
  1203. } else {
  1204. log (`observing ${name}`)
  1205. }
  1206. }
  1207.  
  1208. let observer = new MutationObserver(callback)
  1209. callback([], observer)
  1210. observer.observe($element, options)
  1211. observer['name'] = name
  1212. return observer
  1213. }
  1214.  
  1215. /**
  1216. * @param {string} page
  1217. * @returns {() => boolean}
  1218. */
  1219. function pageIsNot(page) {
  1220. return () => page != currentPage
  1221. }
  1222.  
  1223. /**
  1224. * @param {string} path
  1225. * @returns {() => boolean}
  1226. */
  1227. function pathIsNot(path) {
  1228. return () => path != currentPath
  1229. }
  1230.  
  1231. /**
  1232. * @param {number} n
  1233. * @returns {string}
  1234. */
  1235. function s(n) {
  1236. return n == 1 ? '' : 's'
  1237. }
  1238.  
  1239. function storeConfigChanges(changes) {
  1240. window.postMessage({type: 'tntConfigChange', changes})
  1241. }
  1242. //#endregion
  1243.  
  1244. //#region Global observers
  1245. const checkReactNativeStylesheet = (() => {
  1246. /** @type {number} */
  1247. let startTime
  1248.  
  1249. return function checkReactNativeStylesheet() {
  1250. if (startTime == null) {
  1251. startTime = Date.now()
  1252. }
  1253.  
  1254. let $style = /** @type {HTMLStyleElement} */ (document.querySelector('style#react-native-stylesheet'))
  1255. if (!$style) {
  1256. warn('React Native stylesheet not found')
  1257. return
  1258. }
  1259.  
  1260. for (let rule of $style.sheet.cssRules) {
  1261. if (!(rule instanceof CSSStyleRule)) continue
  1262.  
  1263. if (fontFamilyRule == null &&
  1264. rule.style.fontFamily &&
  1265. rule.style.fontFamily.includes('TwitterChirp')) {
  1266. fontFamilyRule = rule
  1267. log('found Chirp fontFamily CSS rule in React Native stylesheet')
  1268. configureFont()
  1269. }
  1270.  
  1271. if (themeColor == null &&
  1272. rule.style.backgroundColor &&
  1273. THEME_COLORS.has(rule.style.backgroundColor)) {
  1274. themeColor = rule.style.backgroundColor
  1275. localStorage.lastThemeColor = themeColor
  1276. log(`found initial theme color in React Native stylesheet: ${themeColor}`)
  1277. configureThemeCss()
  1278. }
  1279. }
  1280.  
  1281. let elapsedTime = Date.now() - startTime
  1282. if (fontFamilyRule == null || themeColor == null) {
  1283. if (elapsedTime < 3000) {
  1284. setTimeout(checkReactNativeStylesheet, 100)
  1285. } else {
  1286. warn(`stopped checking React Native stylesheet after ${elapsedTime}ms`)
  1287. }
  1288. } else {
  1289. log(`finished checking React Native stylesheet in ${elapsedTime}ms`)
  1290. }
  1291. }
  1292. })()
  1293.  
  1294. /**
  1295. * When the "Background" setting is changed in "Customize your view", <body>'s
  1296. * backgroundColor is changed and the app is re-rendered, so we need to
  1297. * re-process the current page.
  1298. */
  1299. function observeBodyBackgroundColor() {
  1300. let lastBackgroundColor = null
  1301.  
  1302. observeElement($body, () => {
  1303. let backgroundColor = $body.style.backgroundColor
  1304. if (backgroundColor == lastBackgroundColor) return
  1305.  
  1306. $body.classList.toggle('Default', backgroundColor == 'rgb(255, 255, 255)')
  1307. $body.classList.toggle('Dim', backgroundColor == 'rgb(21, 32, 43)')
  1308. $body.classList.toggle('LightsOut', backgroundColor == 'rgb(0, 0, 0)')
  1309.  
  1310. if (lastBackgroundColor != null) {
  1311. log('Background setting changed - re-processing current page')
  1312. observePopups()
  1313. processCurrentPage()
  1314. }
  1315. lastBackgroundColor = backgroundColor
  1316. }, '<body> style attribute for background colour changes', {
  1317. attributes: true,
  1318. attributeFilter: ['style']
  1319. })
  1320. }
  1321.  
  1322. /**
  1323. * When the "Color" setting is changed in "Customize your view", the app
  1324. * re-renders from a certain point, so we need to re-process the current page.
  1325. */
  1326. async function observeColor() {
  1327. let $colorRerenderBoundary = await getElement('#react-root > div > div')
  1328.  
  1329. observeElement($colorRerenderBoundary, async () => {
  1330. if (location.pathname != PagePaths.CUSTOMIZE_YOUR_VIEW) return
  1331.  
  1332. let $doneButton = await getElement(desktop ? Selectors.DISPLAY_DONE_BUTTON_DESKTOP : Selectors.DISPLAY_DONE_BUTTON_MOBILE, {
  1333. name: 'Done button',
  1334. stopIf: not(() => location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW),
  1335. })
  1336. if (!$doneButton) return
  1337.  
  1338. let color = getComputedStyle($doneButton).backgroundColor
  1339. if (color == themeColor) return
  1340.  
  1341. log('Color setting changed - re-processing current page')
  1342. themeColor = color
  1343. localStorage.lastThemeColor = color
  1344. configureThemeCss()
  1345. observePopups()
  1346. processCurrentPage()
  1347. }, 'Color change re-render boundary')
  1348. }
  1349.  
  1350. /**
  1351. * When the "Font size" setting is changed in "Customize your view" on desktop,
  1352. * `<html>`'s fontSize is changed and the app is re-rendered.
  1353. */
  1354. const observeHtmlFontSize = (() => {
  1355. /** @type {MutationObserver} */
  1356. let fontSizeObserver
  1357.  
  1358. return function observeHtmlFontSize() {
  1359. if (fontSizeObserver) {
  1360. fontSizeObserver.disconnect()
  1361. fontSizeObserver = null
  1362. }
  1363.  
  1364. if (mobile) return
  1365.  
  1366. let lastOverflow = ''
  1367.  
  1368. fontSizeObserver = observeElement($html, () => {
  1369. if (!$html.style.fontSize) return
  1370.  
  1371. let hasFontSizeChanged = fontSize != null && $html.style.fontSize != fontSize
  1372.  
  1373. if ($html.style.fontSize != fontSize) {
  1374. fontSize = $html.style.fontSize
  1375. log(`<html> fontSize has changed to ${fontSize}`)
  1376. configureNavFontSizeCss()
  1377. }
  1378.  
  1379. // Ignore overflow changes, which happen when a dialog is shown or hidden
  1380. let hasOverflowChanged = $html.style.overflow != lastOverflow
  1381. lastOverflow = $html.style.overflow
  1382. if (!hasFontSizeChanged && hasOverflowChanged) {
  1383. log('ignoring <html> style overflow change')
  1384. return
  1385. }
  1386.  
  1387. // When you switch between the smallest "Font size" options, <html>'s
  1388. // style is updated but the font size is kept the same - re-process just
  1389. // in case.
  1390. if (hasFontSizeChanged ||
  1391. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW && fontSize == '14px') {
  1392. log('<html> style attribute changed, re-processing current page')
  1393. observePopups()
  1394. processCurrentPage()
  1395. }
  1396. }, '<html> style attribute for font size changes', {
  1397. attributes: true,
  1398. attributeFilter: ['style']
  1399. })
  1400. }
  1401. })()
  1402.  
  1403. async function observeDesktopModalTimeline() {
  1404. // Media modals remember if they were previously collapsed, so we could be
  1405. // waiting for the initial timeline to be either rendered or expanded.
  1406. let $initialTimeline = await getElement(Selectors.MODAL_TIMELINE, {
  1407. name: 'initial modal timeline',
  1408. stopIf: () => !isDesktopMediaModalOpen,
  1409. })
  1410.  
  1411. if ($initialTimeline == null) return
  1412.  
  1413. /**
  1414. * @param {HTMLElement} $timeline
  1415. */
  1416. function observeModalTimelineItems($timeline) {
  1417. disconnectModalObserver('modal timeline')
  1418. modalObservers.push(
  1419. observeElement($timeline, () => onIndividualTweetTimelineChange($timeline), 'modal timeline')
  1420. )
  1421.  
  1422. // If other media in the modal is clicked, the timeline is replaced.
  1423. disconnectModalObserver('modal timeline parent')
  1424. modalObservers.push(
  1425. observeElement($timeline.parentElement, (mutations) => {
  1426. mutations.forEach((mutation) => {
  1427. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1428. log('modal timeline replaced')
  1429. disconnectModalObserver('modal timeline')
  1430. modalObservers.push(
  1431. observeElement($newTimeline, () => onIndividualTweetTimelineChange($newTimeline), 'modal timeline')
  1432. )
  1433. })
  1434. })
  1435. }, 'modal timeline parent')
  1436. )
  1437. }
  1438.  
  1439. /**
  1440. * @param {HTMLElement} $timeline
  1441. */
  1442. function observeModalTimeline($timeline) {
  1443. // If the inital timeline doesn't have a style attribute it's a placeholder
  1444. if ($timeline.hasAttribute('style')) {
  1445. observeModalTimelineItems($timeline)
  1446. }
  1447. else {
  1448. log('waiting for modal timeline')
  1449. let startTime = Date.now()
  1450. modalObservers.push(
  1451. observeElement($timeline.parentElement, (mutations) => {
  1452. mutations.forEach((mutation) => {
  1453. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  1454. disconnectModalObserver('modal timeline parent')
  1455. if (Date.now() > startTime) {
  1456. log(`modal timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  1457. }
  1458. observeModalTimelineItems($timeline)
  1459. })
  1460. })
  1461. }, 'modal timeline parent')
  1462. )
  1463. }
  1464. }
  1465.  
  1466. // The modal timeline can be expanded and collapsed
  1467. let $expandedContainer = $initialTimeline.closest('[aria-expanded="true"]')
  1468. modalObservers.push(
  1469. observeElement($expandedContainer.parentElement, async (mutations) => {
  1470. if (mutations.some(mutation => mutation.removedNodes.length > 0)) {
  1471. log('modal timeline collapsed')
  1472. disconnectModalObserver('modal timeline parent')
  1473. disconnectModalObserver('modal timeline')
  1474. }
  1475. else if (mutations.some(mutation => mutation.addedNodes.length > 0)) {
  1476. log('modal timeline expanded')
  1477. let $timeline = await getElement(Selectors.MODAL_TIMELINE, {
  1478. name: 'expanded modal timeline',
  1479. stopIf: () => !isDesktopMediaModalOpen,
  1480. })
  1481. if ($timeline == null) return
  1482. observeModalTimeline($timeline)
  1483. }
  1484. }, 'collapsible modal timeline container')
  1485. )
  1486.  
  1487. observeModalTimeline($initialTimeline)
  1488. }
  1489.  
  1490. const observeFavicon = (() => {
  1491. /** @type {HTMLElement} */
  1492. let $shortcutIcon
  1493. /** @type {MutationObserver} */
  1494. let shortcutIconObserver
  1495.  
  1496. async function observeFavicon() {
  1497. if ($shortcutIcon == null) {
  1498. $shortcutIcon = await getElement('link[rel="shortcut icon"]', {name: 'shortcut icon'})
  1499. }
  1500.  
  1501. if (!config.replaceLogo) {
  1502. if (shortcutIconObserver != null) {
  1503. shortcutIconObserver.disconnect()
  1504. shortcutIconObserver = null
  1505. if ($shortcutIcon.getAttribute('href').startsWith('data:')) {
  1506. $shortcutIcon.setAttribute('href', `//abs.twimg.com/favicons/twitter${currentNotificationCount ? '-pip' : ''}.3.ico`)
  1507. }
  1508. }
  1509. return
  1510. }
  1511.  
  1512. shortcutIconObserver = observeElement($shortcutIcon, () => {
  1513. let href = $shortcutIcon.getAttribute('href')
  1514. if (href.startsWith('data:')) return
  1515. $shortcutIcon.setAttribute('href', href.includes('pip') ? Images.TWITTER_PIP_FAVICON : Images.TWITTER_FAVICON)
  1516. }, 'shortcut icon href', {
  1517. attributes: true,
  1518. attributeFilter: ['href']
  1519. })
  1520. }
  1521.  
  1522. observeFavicon.updatePip = function(showPip) {
  1523. if (!$shortcutIcon) return
  1524. let icon = showPip ? Images.TWITTER_PIP_FAVICON : Images.TWITTER_FAVICON
  1525. if ($shortcutIcon.getAttribute('href') != icon) {
  1526. $shortcutIcon.setAttribute('href', icon)
  1527. }
  1528. }
  1529.  
  1530. return observeFavicon
  1531. })()
  1532.  
  1533. /**
  1534. * Twitter displays popups in the #layers element. It also reuses open popups
  1535. * in certain cases rather than creating one from scratch, so we also need to
  1536. * deal with nested popups, e.g. if you hover over the caret menu in a Tweet, a
  1537. * popup will be created to display a "More" tootip and clicking to open the
  1538. * menu will create a nested element in the existing popup, whereas clicking the
  1539. * caret quickly without hovering over it will display the menu in new popup.
  1540. * Use of nested popups can also differ between desktop and mobile, so features
  1541. * need to be mindful of that.
  1542. */
  1543. const observePopups = (() => {
  1544. /** @type {MutationObserver} */
  1545. let popupObserver
  1546. /** @type {WeakMap<HTMLElement, {disconnect()}>} */
  1547. let nestedObservers = new WeakMap()
  1548.  
  1549. return async function observePopups() {
  1550. if (popupObserver) {
  1551. popupObserver.disconnect()
  1552. popupObserver = null
  1553. }
  1554.  
  1555. let $layers = await getElement('#layers', {
  1556. name: 'layers',
  1557. })
  1558.  
  1559. // There can be only one
  1560. if (popupObserver) {
  1561. popupObserver.disconnect()
  1562. }
  1563.  
  1564. popupObserver = observeElement($layers, (mutations) => {
  1565. mutations.forEach((mutation) => {
  1566. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1567. let nestedObserver = onPopup($el)
  1568. if (nestedObserver) {
  1569. nestedObservers.set($el, nestedObserver)
  1570. }
  1571. })
  1572. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1573. if (nestedObservers.has($el)) {
  1574. nestedObservers.get($el).disconnect()
  1575. nestedObservers.delete($el)
  1576. }
  1577. })
  1578. })
  1579. }, 'popup container')
  1580. }
  1581. })()
  1582.  
  1583. async function observeTitle() {
  1584. let $title = await getElement('title', {name: '<title>'})
  1585. observeElement($title, () => {
  1586. let title = $title.textContent
  1587. if (config.replaceLogo && (ltr ? /X$/ : /^(?:\(\d+\+?\) )?X/).test(title)) {
  1588. document.title = title.replace(ltr ? /X$/ : 'X', getString('TWITTER'))
  1589. return
  1590. }
  1591. onTitleChange(title)
  1592. }, '<title>')
  1593. }
  1594. //#endregion
  1595.  
  1596. //#region Page observers
  1597. /**
  1598. * If a profile is blocked its media box won't appear, add a `Blocked` class to
  1599. * `<body>` to hide sidebar content.
  1600. * @param {string} currentPage
  1601. */
  1602. async function observeProfileBlockedStatus(currentPage) {
  1603. let $buttonContainer = await getElement(`[data-testid="userActions"] ~ [data-testid="placementTracking"], a[href="${PagePaths.PROFILE_SETTINGS}"]`, {
  1604. name: 'Follow / Unblock button container or Edit profile button',
  1605. stopIf: pageIsNot(currentPage),
  1606. })
  1607. if ($buttonContainer == null) return
  1608.  
  1609. if ($buttonContainer.hasAttribute('href')) {
  1610. log('on own profile page')
  1611. $body.classList.remove('Blocked')
  1612. return
  1613. }
  1614.  
  1615. pageObservers.push(
  1616. observeElement($buttonContainer, () => {
  1617. let isBlocked = (/** @type {HTMLElement} */ ($buttonContainer.querySelector('[role="button"]'))?.dataset.testid ?? '').endsWith('unblock')
  1618. $body.classList.toggle('Blocked', isBlocked)
  1619. }, 'Follow / Unblock button container')
  1620. )
  1621. }
  1622.  
  1623. /**
  1624. * If an account has never tweeted any media, add a `NoMedia` class to `<body>`
  1625. * to hide the "You might like" section which will appear where the media box
  1626. * would have been.
  1627. * @param {string} currentPage
  1628. */
  1629. async function observeProfileSidebar(currentPage) {
  1630. let $sidebarContent = await getElement(Selectors.SIDEBAR_WRAPPERS, {
  1631. name: 'profile sidebar content container',
  1632. stopIf: pageIsNot(currentPage),
  1633. })
  1634. if ($sidebarContent == null) return
  1635.  
  1636. let sidebarContentObserver = observeElement($sidebarContent, () => {
  1637. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1638. }, 'profile sidebar content container')
  1639. pageObservers.push(sidebarContentObserver)
  1640.  
  1641. // On initial appearance, the sidebar is injected with static HTML with
  1642. // spinner placeholders, which gets replaced. When this happens we need to
  1643. // observe the new content container instead.
  1644. let $sidebarContentParent = $sidebarContent.parentElement
  1645. pageObservers.push(
  1646. observeElement($sidebarContentParent, (mutations) => {
  1647. let sidebarContentReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($sidebarContent))
  1648. if (sidebarContentReplaced) {
  1649. log('profile sidebar content container replaced, observing new container')
  1650. sidebarContentObserver.disconnect()
  1651. pageObservers.splice(pageObservers.indexOf(sidebarContentObserver), 1)
  1652. $sidebarContent = /** @type {HTMLElement} */ ($sidebarContentParent.firstElementChild)
  1653. pageObservers.push(
  1654. observeElement($sidebarContent, () => {
  1655. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1656. }, 'sidebar content container')
  1657. )
  1658. }
  1659. }, 'sidebar content container parent')
  1660. )
  1661. }
  1662.  
  1663. async function observeSidebar() {
  1664. let $primaryColumn = await getElement(Selectors.PRIMARY_COLUMN, {
  1665. name: 'primary column'
  1666. })
  1667. let $sidebarContainer = $primaryColumn.parentElement
  1668. pageObservers.push(
  1669. observeElement($sidebarContainer, () => {
  1670. let $sidebar = $sidebarContainer.querySelector(Selectors.SIDEBAR)
  1671. log(`sidebar ${$sidebar ? 'appeared' : 'disappeared'}`)
  1672. $body.classList.toggle('Sidebar', Boolean($sidebar))
  1673. if ($sidebar && config.twitterBlueChecks != 'ignore' && !isOnSearchPage() && !isOnExplorePage()) {
  1674. observeSearchForm()
  1675. }
  1676. }, 'sidebar container')
  1677. )
  1678. }
  1679.  
  1680. async function observeSearchForm() {
  1681. let $searchForm = await getElement('form[role="search"]', {
  1682. name: 'search form',
  1683. stopIf: pageIsNot(currentPage),
  1684. // The sidebar on Profile pages can be really slow
  1685. timeout: 2000,
  1686. })
  1687. if (!$searchForm) return
  1688. let $results = /** @type {HTMLElement} */ ($searchForm.lastElementChild)
  1689. pageObservers.push(
  1690. observeElement($results, () => {
  1691. processBlueChecks($results)
  1692. }, 'search results', {childList: true, subtree: true})
  1693. )
  1694. }
  1695.  
  1696. /**
  1697. * @param {string} page
  1698. * @param {import("./types").TimelineOptions?} options
  1699. */
  1700. async function observeTimeline(page, options = {}) {
  1701. let {
  1702. isTabbed = false,
  1703. onTabChanged = null,
  1704. onTimelineAppeared = null,
  1705. onTimelineItemsChanged = onTimelineChange,
  1706. tabbedTimelineContainerSelector = null,
  1707. timelineSelector = Selectors.TIMELINE,
  1708. } = options
  1709.  
  1710. let $timeline = await getElement(timelineSelector, {
  1711. name: 'initial timeline',
  1712. stopIf: pageIsNot(page),
  1713. })
  1714.  
  1715. if ($timeline == null) return
  1716.  
  1717. /**
  1718. * @param {HTMLElement} $timeline
  1719. */
  1720. function observeTimelineItems($timeline) {
  1721. disconnectPageObserver('timeline')
  1722. pageObservers.push(
  1723. observeElement($timeline, () => onTimelineItemsChanged($timeline, page, options), 'timeline')
  1724. )
  1725. onTimelineAppeared?.()
  1726. if (isTabbed) {
  1727. // When a tab which has been viewed before is revisited, the timeline is
  1728. // replaced.
  1729. disconnectPageObserver('timeline parent')
  1730. pageObservers.push(
  1731. observeElement($timeline.parentElement, (mutations) => {
  1732. mutations.forEach((mutation) => {
  1733. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1734. disconnectPageObserver('timeline')
  1735. log('tab changed')
  1736. onTabChanged?.()
  1737. pageObservers.push(
  1738. observeElement($newTimeline, () => onTimelineItemsChanged($newTimeline, page, options), 'timeline')
  1739. )
  1740. })
  1741. })
  1742. }, 'timeline parent')
  1743. )
  1744. }
  1745. }
  1746.  
  1747. // If the inital timeline doesn't have a style attribute it's a placeholder
  1748. if ($timeline.hasAttribute('style')) {
  1749. observeTimelineItems($timeline)
  1750. }
  1751. else {
  1752. log('waiting for timeline')
  1753. let startTime = Date.now()
  1754. pageObservers.push(
  1755. observeElement($timeline.parentElement, (mutations) => {
  1756. mutations.forEach((mutation) => {
  1757. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  1758. disconnectPageObserver('timeline parent')
  1759. if (Date.now() > startTime) {
  1760. log(`timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  1761. }
  1762. observeTimelineItems($timeline)
  1763. })
  1764. })
  1765. }, 'timeline parent')
  1766. )
  1767. }
  1768.  
  1769. // On some tabbed timeline pages, the first time a new tab is navigated to,
  1770. // the element containing the timeline is replaced with a loading spinner.
  1771. if (isTabbed && tabbedTimelineContainerSelector) {
  1772. let $tabbedTimelineContainer = document.querySelector(tabbedTimelineContainerSelector)
  1773. if ($tabbedTimelineContainer) {
  1774. let waitingForNewTimeline = false
  1775. pageObservers.push(
  1776. observeElement($tabbedTimelineContainer, async (mutations) => {
  1777. // This is going to fire twice on a new tab, as the spinner is added
  1778. // then replaced with the new timeline element.
  1779. if (!mutations.some(mutation => mutation.addedNodes.length > 0) || waitingForNewTimeline) return
  1780.  
  1781. waitingForNewTimeline = true
  1782. let $newTimeline = await getElement(timelineSelector, {
  1783. name: 'new timeline',
  1784. stopIf: pageIsNot(page),
  1785. })
  1786. waitingForNewTimeline = false
  1787. if (!$newTimeline) return
  1788.  
  1789. log('tab changed')
  1790. onTabChanged?.()
  1791. observeTimelineItems($newTimeline)
  1792. }, 'tabbed timeline container')
  1793. )
  1794. } else {
  1795. warn('tabbed timeline container not found')
  1796. }
  1797. }
  1798. }
  1799.  
  1800. /**
  1801. * @param {HTMLElement} $context
  1802. * @param {string} initialPath
  1803. */
  1804. async function observeUserListTimeline($context, initialPath) {
  1805. let $timeline = await getElement('h1[id^="accessible-list"] + div > div > div > div', {
  1806. context: $context,
  1807. name: 'user list timeline',
  1808. stopIf: not(() => initialPath == location.pathname),
  1809. })
  1810. if (!$timeline) return
  1811.  
  1812. modalObservers.push(
  1813. observeElement($timeline, () => {
  1814. processBlueChecks($timeline)
  1815. }, 'user list timeline')
  1816. )
  1817. }
  1818. //#endregion
  1819.  
  1820. //#region Tweak functions
  1821. /**
  1822. * Add an "Add muted word" menu item after the given link which takes you
  1823. * straight to entering a new muted word (by clicking its way through all the
  1824. * individual screens!).
  1825. * @param {HTMLElement} $link
  1826. * @param {string} linkSelector
  1827. */
  1828. async function addAddMutedWordMenuItem($link, linkSelector) {
  1829. log('adding "Add muted word" menu item')
  1830.  
  1831. // Wait for the dropdown to appear on desktop
  1832. if (desktop) {
  1833. $link = await getElement(`#layers div[data-testid="Dropdown"] ${linkSelector}`, {
  1834. name: 'rendered menu item',
  1835. timeout: 100,
  1836. })
  1837. if (!$link) return
  1838. }
  1839.  
  1840. let $addMutedWord = /** @type {HTMLElement} */ ($link.parentElement.cloneNode(true))
  1841. $addMutedWord.classList.add('tnt_menu_item')
  1842. $addMutedWord.querySelector('a').href = PagePaths.ADD_MUTED_WORD
  1843. $addMutedWord.querySelector('span').textContent = getString('ADD_MUTED_WORD')
  1844. $addMutedWord.querySelector('svg').innerHTML = Svgs.MUTE
  1845. $addMutedWord.addEventListener('click', (e) => {
  1846. e.preventDefault()
  1847. addMutedWord()
  1848. })
  1849. $link.parentElement.insertAdjacentElement('afterend', $addMutedWord)
  1850. }
  1851.  
  1852. function addCaretMenuListenerForQuoteTweet($tweet) {
  1853. let $caret = /** @type {HTMLElement} */ ($tweet.querySelector('[data-testid="caret"]'))
  1854. if ($caret && !$caret.dataset.tweakNewTwitterListener) {
  1855. $caret.addEventListener('click', () => {
  1856. quotedTweet = getQuotedTweetDetails($tweet, {getText: true})
  1857. })
  1858. $caret.dataset.tweakNewTwitterListener = 'true'
  1859. }
  1860. }
  1861.  
  1862. /**
  1863. * Add a "Mute this conversation" menu item to a Quote Tweet's menu.
  1864. * @param {HTMLElement} $blockMenuItem
  1865. */
  1866. async function addMuteQuotesMenuItem($blockMenuItem) {
  1867. log('adding "Mute this conversation" menu item')
  1868.  
  1869. // Wait for the menu to render properly on desktop
  1870. if (desktop) {
  1871. $blockMenuItem = await getElement(`:scope > div > div > div > ${Selectors.BLOCK_MENU_ITEM}`, {
  1872. context: $blockMenuItem.parentElement,
  1873. name: 'rendered block menu item',
  1874. timeout: 100,
  1875. })
  1876. if (!$blockMenuItem) return
  1877. }
  1878.  
  1879. let $muteQuotes = /** @type {HTMLElement} */ ($blockMenuItem.previousElementSibling.cloneNode(true))
  1880. $muteQuotes.classList.add('tnt_menu_item')
  1881. $muteQuotes.querySelector('span').textContent = getString('MUTE_THIS_CONVERSATION')
  1882. $muteQuotes.addEventListener('click', (e) => {
  1883. e.preventDefault()
  1884. log('muting quotes of a tweet', quotedTweet)
  1885. config.mutedQuotes = config.mutedQuotes.concat(quotedTweet)
  1886. storeConfigChanges({mutedQuotes: config.mutedQuotes})
  1887. processCurrentPage()
  1888. // Dismiss the menu
  1889. let $menuLayer = /** @type {HTMLElement} */ ($blockMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  1890. if (!$menuLayer) {
  1891. log('could not find menu layer to dismiss menu')
  1892. }
  1893. $menuLayer?.click()
  1894. })
  1895.  
  1896. $blockMenuItem.insertAdjacentElement('beforebegin', $muteQuotes)
  1897. }
  1898.  
  1899. async function addMutedWord() {
  1900. if (!document.querySelector('a[href="/settings')) {
  1901. let $settingsAndSupport = /** @type {HTMLElement} */ (document.querySelector('[data-testid="settingsAndSupport"]'))
  1902. $settingsAndSupport?.click()
  1903. }
  1904.  
  1905. for (let path of [
  1906. '/settings',
  1907. '/settings/privacy_and_safety',
  1908. '/settings/mute_and_block',
  1909. '/settings/muted_keywords',
  1910. '/settings/add_muted_keyword',
  1911. ]) {
  1912. let $link = await getElement(`a[href="${path}"]`, {timeout: 500})
  1913. if (!$link) return
  1914. $link.click()
  1915. }
  1916. let $input = await getElement('input[name="keyword"]')
  1917. setTimeout(() => $input.focus(), 100)
  1918. }
  1919.  
  1920. /**
  1921. * Add a "Turn on/off Retweets" menu item to a List's menu.
  1922. * @param {HTMLElement} $switchMenuItem
  1923. */
  1924. async function addToggleListRetweetsMenuItem($switchMenuItem) {
  1925. log('adding "Turn on/off Retweets" menu item')
  1926.  
  1927. // Wait for the menu to render properly on desktop
  1928. if (desktop) {
  1929. $switchMenuItem = await getElement(':scope > div > div > div > [role="menuitem"]', {
  1930. context: $switchMenuItem.parentElement,
  1931. name: 'rendered switch menu item',
  1932. timeout: 100,
  1933. })
  1934. if (!$switchMenuItem) return
  1935. }
  1936.  
  1937. let $toggleRetweets = /** @type {HTMLElement} */ ($switchMenuItem.cloneNode(true))
  1938. $toggleRetweets.classList.add('tnt_menu_item')
  1939. $toggleRetweets.querySelector('span').textContent = getString(`TURN_${config.listRetweets == 'ignore' ? 'OFF' : 'ON'}_RETWEETS`)
  1940. $toggleRetweets.querySelector('svg').innerHTML = config.listRetweets == 'ignore' ? Svgs.RETWEETS_OFF : Svgs.RETWEET
  1941. $toggleRetweets.querySelector(':scope > div:last-child > div:last-child')?.remove()
  1942. $toggleRetweets.addEventListener('click', (e) => {
  1943. e.preventDefault()
  1944. log('toggling list retweets')
  1945. config.listRetweets = config.listRetweets == 'ignore' ? 'hide' : 'ignore'
  1946. storeConfigChanges({listRetweets: config.listRetweets})
  1947. processCurrentPage()
  1948. // Dismiss the menu
  1949. let $menuLayer = /** @type {HTMLElement} */ ($switchMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  1950. if (!$menuLayer) {
  1951. log('could not find menu layer to dismiss menu')
  1952. }
  1953. $menuLayer?.click()
  1954. })
  1955.  
  1956. $switchMenuItem.insertAdjacentElement('beforebegin', $toggleRetweets)
  1957. }
  1958.  
  1959. /**
  1960. * Redirects away from the home timeline if we're on it and it's been disabled.
  1961. * @returns {boolean} `true` if redirected as a result of this call
  1962. */
  1963. function checkforDisabledHomeTimeline() {
  1964. if (config.disableHomeTimeline && location.pathname == '/home') {
  1965. log(`home timeline disabled, redirecting to /${config.disabledHomeTimelineRedirect}`)
  1966. let primaryNavSelector = desktop ? Selectors.PRIMARY_NAV_DESKTOP : Selectors.PRIMARY_NAV_MOBILE
  1967. ;/** @type {HTMLElement} */ (
  1968. document.querySelector(`${primaryNavSelector} a[href="/${config.disabledHomeTimelineRedirect}"]`)
  1969. ).click()
  1970. return true
  1971. }
  1972. }
  1973.  
  1974. const configureCss = (() => {
  1975. let $style
  1976.  
  1977. return function configureCss() {
  1978. if ($style == null) {
  1979. $style = addStyle('features')
  1980. }
  1981. let cssRules = []
  1982. let hideCssSelectors = []
  1983. let menuRole = `[role="${desktop ? 'menu' : 'dialog'}"]`
  1984.  
  1985. // Hover colours for custom menu items
  1986. cssRules.push(`
  1987. body.Default .tnt_menu_item:hover { background-color: rgb(247, 249, 249) !important; }
  1988. body.Dim .tnt_menu_item:hover { background-color: rgb(30, 39, 50) !important; }
  1989. body.LightsOut .tnt_menu_item:hover { background-color: rgb(22, 24, 28) !important; }
  1990. `)
  1991.  
  1992. if (config.alwaysUseLatestTweets && config.hideForYouTimeline) {
  1993. cssRules.push(`
  1994. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child {
  1995. flex: 0;
  1996. }
  1997. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child > a {
  1998. display: none;
  1999. }
  2000. `)
  2001. }
  2002. if (config.disableTweetTextFormatting) {
  2003. cssRules.push(`
  2004. div[data-testid="tweetText"] span {
  2005. font-style: normal;
  2006. font-weight: normal;
  2007. }
  2008. `)
  2009. }
  2010. if (config.dropdownMenuFontWeight) {
  2011. cssRules.push(`
  2012. [data-testid="${desktop ? 'Dropdown' : 'sheetDialog'}"] [role="menuitem"] [dir] {
  2013. font-weight: normal;
  2014. }
  2015. `)
  2016. }
  2017. if (config.hideAnalyticsNav) {
  2018. hideCssSelectors.push(`${menuRole} a[href*="analytics.twitter.com"]`)
  2019. }
  2020. if (config.hideBookmarkButton) {
  2021. hideCssSelectors.push(
  2022. // Under individual tweets
  2023. '[data-testid="tweet"][tabindex="-1"] [role="group"][id^="id__"] > div:nth-child(4)',
  2024. )
  2025. }
  2026. if (config.hideBookmarksNav) {
  2027. hideCssSelectors.push(`${menuRole} a[href$="/bookmarks"]`)
  2028. }
  2029. if (config.hideCommunitiesNav) {
  2030. hideCssSelectors.push(`${menuRole} a[href$="/communities"]`)
  2031. }
  2032. if (config.hideShareTweetButton) {
  2033. hideCssSelectors.push(
  2034. // Under timeline tweets
  2035. `[data-testid="tweet"][tabindex="0"] [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2036. // Under individual tweets
  2037. `[data-testid="tweet"][tabindex="-1"] [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2038. )
  2039. }
  2040. if (config.hideSubscriptions) {
  2041. hideCssSelectors.push(
  2042. // Subscribe buttons in profile (multiple locations)
  2043. 'body.Profile [role="button"][style*="border-color: rgb(201, 54, 204)"]',
  2044. // Subscriptions count in profile
  2045. 'body.Profile a[href$="/creator-subscriptions/subscriptions"]',
  2046. // Subs tab in profile (3rd of 5, or 6 if they have Highlights)
  2047. 'body.Profile [data-testid="ScrollSnap-List"] > [role="presentation"]:nth-child(3):is(:nth-last-child(3), :nth-last-child(4))',
  2048. // Subscribe button in focused tweet
  2049. '[data-testid="tweet"][tabindex="-1"] [data-testid$="-subscribe"]',
  2050. // "Subscribe to" dropdown item (desktop)
  2051. '[data-testid="Dropdown"] > [data-testid="subscribe"]',
  2052. // "Subscribe to" menu item (mobile)
  2053. '[data-testid="sheetDialog"] > [data-testid="subscribe"]',
  2054. // "Subscriber" indicator in replies from subscribers
  2055. 'body.Default [data-testid="tweet"] [data-testid="userFollowIndicator"][style*="color: rgb(141, 32, 144)"]',
  2056. 'body:is(.Dim, .LightsOut) [data-testid="tweet"] [data-testid="userFollowIndicator"][style*="color: rgb(223, 130, 224)"]',
  2057. // Monetization and Subscriptions items in Settings
  2058. 'body.Settings a[href="/settings/monetization"]',
  2059. 'body.Settings a[href="/settings/manage_subscriptions"]',
  2060. )
  2061. }
  2062. if (config.hideHelpCenterNav) {
  2063. hideCssSelectors.push(`${menuRole} a[href*="support.twitter.com"]`)
  2064. }
  2065. if (config.hideMetrics) {
  2066. configureHideMetricsCss(cssRules, hideCssSelectors)
  2067. }
  2068. if (config.hideMonetizationNav) {
  2069. hideCssSelectors.push(`${menuRole} a[href$="/settings/monetization"]`)
  2070. }
  2071. if (config.hideTweetAnalyticsLinks) {
  2072. hideCssSelectors.push('[data-testid="analyticsButton"]')
  2073. }
  2074. if (config.hideTwitterAdsNav) {
  2075. hideCssSelectors.push(`${menuRole} a[href*="ads.twitter.com"]`)
  2076. }
  2077. if (config.hideTwitterBlueUpsells) {
  2078. hideCssSelectors.push(
  2079. // Twitter Blue menu item
  2080. `${menuRole} a[href$="/i/blue_sign_up"]`,
  2081. // "Highlight on your profile" on your tweets
  2082. '[role="menuitem"][data-testid="highlightUpsell"]',
  2083. // "Edit with Twitter Blue" on recent tweets
  2084. '[role="menuitem"][data-testid="editWithTwitterBlue"]',
  2085. // Twitter Blue item in Settings
  2086. 'body.Settings a[href="/i/blue_sign_up"]',
  2087. // "Highlight your best content instead" on the pin modal
  2088. '.PinModal [data-testid="sheetDialog"] > div > div:last-child > div > div > div:first-child',
  2089. // Highlight button on the pin modal
  2090. '.PinModal [data-testid="sheetDialog"] [role="button"]:first-child:nth-last-child(3)',
  2091. )
  2092. // Allow Pin and Cancel buttons go to max-width on the pin modal
  2093. cssRules.push(`
  2094. .PinModal [data-testid="sheetDialog"] > div > div:last-child > div > div {
  2095. width: 100%;
  2096. margin-top: 0;
  2097. padding-left: 32px;
  2098. padding-right: 32px;
  2099. }
  2100. `)
  2101. }
  2102. if (config.hideVerifiedNotificationsTab) {
  2103. hideCssSelectors.push(
  2104. `body.Notifications ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:nth-child(2)`
  2105. )
  2106. }
  2107. if (config.hideViews) {
  2108. hideCssSelectors.push(
  2109. // "Views" under individual tweets
  2110. '[data-testid="tweet"][tabindex="-1"] div[dir] + div[aria-hidden="true"]:nth-child(2):nth-last-child(2)',
  2111. '[data-testid="tweet"][tabindex="-1"] div[dir] + div[aria-hidden="true"]:nth-child(2):nth-last-child(2) + div[dir]:last-child'
  2112. )
  2113. }
  2114. if (config.hideWhoToFollowEtc) {
  2115. hideCssSelectors.push(`body.Profile ${Selectors.PRIMARY_COLUMN} aside[role="complementary"]`)
  2116. }
  2117. if (config.reducedInteractionMode) {
  2118. hideCssSelectors.push(
  2119. '[data-testid="tweet"] [role="group"]',
  2120. 'body.Tweet a:is([href$="/retweets"], [href$="/likes"])',
  2121. 'body.Tweet [data-testid="tweet"] + div > div [role="group"]',
  2122. )
  2123. }
  2124. if (config.tweakQuoteTweetsPage) {
  2125. // Hide the quoted tweet, which is repeated in every quote tweet
  2126. hideCssSelectors.push('body.QuoteTweets [data-testid="tweet"] [aria-labelledby] > div:last-child')
  2127. }
  2128. if (config.twitterBlueChecks == 'hide') {
  2129. hideCssSelectors.push('.tnt_blue_check')
  2130. }
  2131. if (config.twitterBlueChecks == 'replace') {
  2132. cssRules.push(`
  2133. :is(${Selectors.VERIFIED_TICK}, svg[data-testid="verificationBadge"]).tnt_blue_check path {
  2134. d: path("${Svgs.BLUE_LOGO_PATH}");
  2135. }
  2136. `)
  2137. }
  2138.  
  2139. // Hide "Creator Studio" if all its contents are hidden
  2140. if (config.hideAnalyticsNav) {
  2141. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(1)`)
  2142. }
  2143. // Hide "Professional Tools" if all its contents are hidden
  2144. if (config.hideTwitterAdsNav) {
  2145. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(2)`)
  2146. }
  2147.  
  2148. if (shouldShowSeparatedTweetsTab()) {
  2149. cssRules.push(`
  2150. body.Default {
  2151. --active-tab-text: rgb(15, 20, 25);
  2152. --inactive-tab-text: rgb(83, 100, 113);
  2153. --tab-border: rgb(239, 243, 244);
  2154. --tab-hover: rgba(15, 20, 25, 0.1);
  2155. }
  2156. body.Dim {
  2157. --active-tab-text: rgb(247, 249, 249);
  2158. --inactive-tab-text: rgb(139, 152, 165);
  2159. --tab-border: rgb(56, 68, 77);
  2160. --tab-hover: rgba(247, 249, 249, 0.1);
  2161. }
  2162. body.LightsOut {
  2163. --active-tab-text: rgb(247, 249, 249);
  2164. --inactive-tab-text: rgb(113, 118, 123);
  2165. --tab-border: rgb(47, 51, 54);
  2166. --tab-hover: rgba(231, 233, 234, 0.1);
  2167. }
  2168.  
  2169. /* Tabbed timeline */
  2170. body.Desktop #tnt_separated_tweets_tab:hover,
  2171. body.Mobile:not(.SeparatedTweets) #tnt_separated_tweets_tab:hover,
  2172. body.Mobile #tnt_separated_tweets_tab:active {
  2173. background-color: var(--tab-hover);
  2174. }
  2175. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div,
  2176. 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 {
  2177. font-weight: normal !important;
  2178. color: var(--inactive-tab-text) !important;
  2179. }
  2180. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div {
  2181. font-weight: bold;
  2182. color: var(--active-tab-text); !important;
  2183. }
  2184. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div > div,
  2185. 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 {
  2186. height: 0 !important;
  2187. }
  2188. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2189. height: 4px !important;
  2190. min-width: 56px;
  2191. width: 100%;
  2192. position: absolute;
  2193. bottom: 0;
  2194. border-radius: 9999px;
  2195. }
  2196. `)
  2197. }
  2198.  
  2199. if (desktop) {
  2200. if (config.navDensity == 'comfortable' || config.navDensity == 'compact') {
  2201. cssRules.push(`
  2202. header nav > a,
  2203. header nav > div[data-testid="AppTabBar_More_Menu"] {
  2204. padding-top: 0 !important;
  2205. padding-bottom: 0 !important;
  2206. }
  2207. `)
  2208. }
  2209. if (config.navDensity == 'compact') {
  2210. cssRules.push(`
  2211. header nav > a > div,
  2212. header nav > div[data-testid="AppTabBar_More_Menu"] > div {
  2213. padding-top: 6px !important;
  2214. padding-bottom: 6px !important;
  2215. }
  2216. `)
  2217. }
  2218. if (config.hideHomeHeading) {
  2219. hideCssSelectors.push(`body.TabbedTimeline ${Selectors.DESKTOP_TIMELINE_HEADER} > div:first-child > div:first-child`)
  2220. }
  2221. if (config.hideSeeNewTweets) {
  2222. hideCssSelectors.push(`body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div > div:first-child > div[style^="transform"]`)
  2223. }
  2224. if (config.disableHomeTimeline) {
  2225. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/home"]`)
  2226. }
  2227. if (config.fullWidthContent) {
  2228. cssRules.push(`
  2229. /* Use full width when the sidebar is visible */
  2230. body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN},
  2231. body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2232. max-width: 990px;
  2233. }
  2234. /* Make the "What's happening" input keep its original width */
  2235. body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div:first-child > div:nth-of-type(3) div[role="progressbar"] + div {
  2236. max-width: 598px;
  2237. }
  2238. /* Use full width when the sidebar is not visible */
  2239. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} header[role="banner"] {
  2240. flex-grow: 0;
  2241. }
  2242. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} main[role="main"] > div {
  2243. width: 100%;
  2244. }
  2245. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} {
  2246. max-width: unset;
  2247. width: 100%;
  2248. }
  2249. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:first-child div,
  2250. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2251. max-width: unset;
  2252. }
  2253. `)
  2254. if (!config.fullWidthMedia) {
  2255. // Make media & cards keep their original width
  2256. cssRules.push(`
  2257. 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) {
  2258. max-width: 504px;
  2259. }
  2260. `)
  2261. }
  2262. // Hide the sidebar when present
  2263. hideCssSelectors.push(`body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.SIDEBAR}`)
  2264. }
  2265. if (config.hideAccountSwitcher) {
  2266. cssRules.push(`
  2267. header[role="banner"] > div > div > div > div:last-child {
  2268. flex-shrink: 1 !important;
  2269. align-items: flex-end !important;
  2270. }
  2271. `)
  2272. hideCssSelectors.push(
  2273. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child:not(:only-child)',
  2274. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child + div',
  2275. )
  2276. }
  2277. if (config.hideExplorePageContents) {
  2278. hideCssSelectors.push(
  2279. // Tabs
  2280. `body.Explore ${Selectors.DESKTOP_TIMELINE_HEADER} nav`,
  2281. // Content
  2282. `body.Explore ${Selectors.TIMELINE}`,
  2283. )
  2284. }
  2285. if (config.hideConnectNav) {
  2286. hideCssSelectors.push(`${menuRole} a[href$="/i/connect_people"]`)
  2287. }
  2288. if (config.hideKeyboardShortcutsNav) {
  2289. hideCssSelectors.push(`${menuRole} a[href$="/i/keyboard_shortcuts"]`)
  2290. }
  2291. if (config.hideListsNav) {
  2292. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/lists"]`)
  2293. }
  2294. if (config.hideTwitterBlueUpsells) {
  2295. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/i/verified-choose"]`)
  2296. }
  2297. if (config.hideSidebarContent) {
  2298. // Only show the first sidebar item by default
  2299. // Re-show subsequent non-algorithmic sections on specific pages
  2300. cssRules.push(`
  2301. ${Selectors.SIDEBAR_WRAPPERS} > div:not(:first-of-type) {
  2302. display: none;
  2303. }
  2304. body.Profile:not(.Blocked, .NoMedia) ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2305. display: block;
  2306. }
  2307. body.Search ${Selectors.SIDEBAR_WRAPPERS} > div:nth-of-type(2) {
  2308. display: block;
  2309. }
  2310. `)
  2311. if (config.showRelevantPeople) {
  2312. cssRules.push(`
  2313. body.Tweet ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2314. display: block;
  2315. }
  2316. `)
  2317. }
  2318. hideCssSelectors.push(`body.HideSidebar ${Selectors.SIDEBAR}`)
  2319. } else if (config.hideTwitterBlueUpsells) {
  2320. hideCssSelectors.push(
  2321. `body.MainTimeline ${Selectors.SIDEBAR_WRAPPERS} > div:nth-of-type(3)`
  2322. )
  2323. }
  2324. if (config.hideShareTweetButton) {
  2325. hideCssSelectors.push(
  2326. // In media modal
  2327. `[aria-modal="true"] [role="group"] > div[style]:not([role]):not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2328. )
  2329. }
  2330. if (config.hideExploreNav) {
  2331. // When configured, hide Explore only when the sidebar is showing, or
  2332. // when on a page full-width content is enabled on.
  2333. let bodySelector = `${config.hideExploreNavWithSidebar ? `body.Sidebar${config.fullWidthContent ? `:not(${FULL_WIDTH_BODY_PSEUDO})` : ''} ` : ''}`
  2334. hideCssSelectors.push(`${bodySelector}${Selectors.PRIMARY_NAV_DESKTOP} a[href="/explore"]`)
  2335. }
  2336. if (config.hideBookmarksNav) {
  2337. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/i/bookmarks"]`)
  2338. }
  2339. if (config.hideCommunitiesNav) {
  2340. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/communities"]`)
  2341. }
  2342. if (config.hideMessagesDrawer) {
  2343. cssRules.push(`${Selectors.MESSAGES_DRAWER} { visibility: hidden; }`)
  2344. }
  2345. if (config.hideViews) {
  2346. hideCssSelectors.push(
  2347. // Under timeline tweets
  2348. // The Buffer extension adds a new button in position 2 - use their added class to avoid
  2349. // hiding the wrong button (#209)
  2350. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-of-type(4)',
  2351. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-of-type(5)',
  2352. )
  2353. }
  2354. if (config.retweets != 'separate' && config.quoteTweets != 'separate') {
  2355. hideCssSelectors.push('#tnt_separated_tweets_tab')
  2356. }
  2357. }
  2358.  
  2359. if (mobile) {
  2360. if (config.disableHomeTimeline) {
  2361. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/home"]`)
  2362. }
  2363. if (config.hideSeeNewTweets) {
  2364. hideCssSelectors.push(`body.MainTimeline ${Selectors.MOBILE_TIMELINE_HEADER_NEW} ~ div[style^="transform"]:last-child`)
  2365. }
  2366. if (config.hideAppNags) {
  2367. cssRules.push(`
  2368. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_OLD} div:nth-of-type(3) > div > [role="button"],
  2369. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_NEW} div:nth-of-type(3) > div > [role="button"] {
  2370. visibility: hidden;
  2371. }
  2372. `)
  2373. }
  2374. if (config.hideExplorePageContents) {
  2375. // Hide explore page contents so we don't get a brief flash of them
  2376. // before automatically switching the page to search mode.
  2377. hideCssSelectors.push(
  2378. // Tabs
  2379. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div:nth-of-type(2)`,
  2380. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:nth-of-type(2)`,
  2381. // Content
  2382. `body.Explore ${Selectors.TIMELINE}`,
  2383. )
  2384. }
  2385. if (config.hideListsNav) {
  2386. hideCssSelectors.push(`${menuRole} a[href$="/lists"]`)
  2387. }
  2388. if (config.hideMessagesBottomNavItem) {
  2389. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/messages"]`)
  2390. }
  2391. if (config.hideShareTweetButton) {
  2392. hideCssSelectors.push(
  2393. // In media modal
  2394. `body.MobileMedia [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2395. )
  2396. }
  2397. if (config.hideViews) {
  2398. hideCssSelectors.push(
  2399. // Under timeline tweets
  2400. // Views only display on mobile at larger widths - only hide the 4th button if there are 5
  2401. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-child(4):nth-last-child(2)',
  2402. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-child(4):nth-last-child(2)',
  2403. )
  2404. }
  2405. }
  2406.  
  2407. if (hideCssSelectors.length > 0) {
  2408. cssRules.push(`
  2409. ${hideCssSelectors.join(',\n')} {
  2410. display: none !important;
  2411. }
  2412. `)
  2413. }
  2414.  
  2415. $style.textContent = cssRules.map(dedent).join('\n')
  2416. }
  2417. })()
  2418.  
  2419. function configureFont() {
  2420. if (!fontFamilyRule) {
  2421. warn('no fontFamilyRule found for configureFont to use')
  2422. return
  2423. }
  2424.  
  2425. if (config.dontUseChirpFont) {
  2426. if (fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2427. fontFamilyRule.style.fontFamily = fontFamilyRule.style.fontFamily.replace(/"?TwitterChirp"?, ?/, '')
  2428. log('disabled Chirp font')
  2429. }
  2430. } else if (!fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2431. fontFamilyRule.style.fontFamily = `"TwitterChirp", ${fontFamilyRule.style.fontFamily}`
  2432. log(`enabled Chirp font`)
  2433. }
  2434. }
  2435.  
  2436. /**
  2437. * @param {string[]} cssRules
  2438. * @param {string[]} hideCssSelectors
  2439. */
  2440. function configureHideMetricsCss(cssRules, hideCssSelectors) {
  2441. if (config.hideFollowingMetrics) {
  2442. // User profile hover card and page metrics
  2443. hideCssSelectors.push(
  2444. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) > :first-child'
  2445. )
  2446. // Fix display of whitespace after hidden metrics
  2447. cssRules.push(
  2448. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) { white-space: pre-line; }'
  2449. )
  2450. }
  2451.  
  2452. if (config.hideTotalTweetsMetrics) {
  2453. // Tweet count under username header on profile pages
  2454. hideCssSelectors.push(
  2455. mobile ? `
  2456. body.Profile header > div > div:first-of-type h2 + div[dir],
  2457. body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:first-of-type h2 + div[dir]
  2458. ` : `body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 + div[dir]`
  2459. )
  2460. }
  2461.  
  2462. let individualTweetMetricSelectors = [
  2463. config.hideRetweetMetrics && '[href$="/retweets"]',
  2464. config.hideLikeMetrics && '[href$="/likes"]',
  2465. config.hideQuoteTweetMetrics && '[href$="/retweets/with_comments"]',
  2466. ].filter(Boolean).join(', ')
  2467.  
  2468. if (individualTweetMetricSelectors) {
  2469. // Individual tweet metrics
  2470. hideCssSelectors.push(
  2471. `body.Tweet a:is(${individualTweetMetricSelectors}) > :first-child`,
  2472. `[aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) > :first-child`
  2473. )
  2474. // Fix display of whitespace after hidden metrics
  2475. cssRules.push(
  2476. `body.Tweet a:is(${individualTweetMetricSelectors}), [aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) { white-space: pre-line; }`
  2477. )
  2478. }
  2479.  
  2480. if (config.hideBookmarkMetrics) {
  2481. // Bookmark metrics are the only one without a link
  2482. hideCssSelectors.push('[data-testid="tweet"][tabindex="-1"] [role="group"]:not([id]) > div > div')
  2483. }
  2484.  
  2485. let timelineMetricSelectors = [
  2486. config.hideReplyMetrics && '[data-testid="reply"]',
  2487. config.hideRetweetMetrics && '[data-testid$="retweet"]',
  2488. config.hideLikeMetrics && '[data-testid$="like"]',
  2489. ].filter(Boolean).join(', ')
  2490.  
  2491. if (timelineMetricSelectors) {
  2492. cssRules.push(
  2493. `[role="group"] div:is(${timelineMetricSelectors}) span { visibility: hidden; }`
  2494. )
  2495. }
  2496. }
  2497.  
  2498. const configureNavFontSizeCss = (() => {
  2499. let $style
  2500.  
  2501. return function configureNavFontSizeCss() {
  2502. if ($style == null) {
  2503. $style = addStyle('nav-font-size')
  2504. }
  2505. let cssRules = []
  2506.  
  2507. if (fontSize != null && config.navBaseFontSize) {
  2508. cssRules.push(`
  2509. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] span { font-size: ${fontSize}; font-weight: normal; }
  2510. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] { margin-top: -4px; }
  2511. `)
  2512. }
  2513.  
  2514. $style.textContent = cssRules.map(dedent).join('\n')
  2515. }
  2516. })()
  2517.  
  2518. /**
  2519. * Configures – or re-configures – the separated tweets timeline title.
  2520. *
  2521. * If we're currently on the separated tweets timeline and…
  2522. * - …its title has changed, the page title will be changed to "navigate" to it.
  2523. * - …the separated tweets timeline is no longer needed, we'll change the page
  2524. * title to "navigate" back to the main timeline.
  2525. *
  2526. * @returns {boolean} `true` if "navigation" was triggered by this call
  2527. */
  2528. function configureSeparatedTweetsTimelineTitle() {
  2529. let wasOnSeparatedTweetsTimeline = isOnSeparatedTweetsTimeline()
  2530. let previousTitle = separatedTweetsTimelineTitle
  2531.  
  2532. if (config.retweets == 'separate' && config.quoteTweets == 'separate') {
  2533. separatedTweetsTimelineTitle = getString('SHARED_TWEETS')
  2534. } else if (config.retweets == 'separate') {
  2535. separatedTweetsTimelineTitle = getString('RETWEETS')
  2536. } else if (config.quoteTweets == 'separate') {
  2537. separatedTweetsTimelineTitle = getString('QUOTE_TWEETS')
  2538. } else {
  2539. separatedTweetsTimelineTitle = null
  2540. }
  2541.  
  2542. let titleChanged = previousTitle != separatedTweetsTimelineTitle
  2543. if (wasOnSeparatedTweetsTimeline) {
  2544. if (separatedTweetsTimelineTitle == null) {
  2545. log('moving from separated tweets timeline to main timeline after config change')
  2546. setTitle(getString('HOME'))
  2547. return true
  2548. }
  2549. if (titleChanged) {
  2550. log('applying new separated tweets timeline title after config change')
  2551. setTitle(separatedTweetsTimelineTitle)
  2552. return true
  2553. }
  2554. } else {
  2555. if (titleChanged && previousTitle != null && lastMainTimelineTitle == previousTitle) {
  2556. log('updating lastMainTimelineTitle with new separated tweets timeline title')
  2557. lastMainTimelineTitle = separatedTweetsTimelineTitle
  2558. }
  2559. }
  2560. }
  2561.  
  2562. const configureThemeCss = (() => {
  2563. let $style
  2564.  
  2565. return function configureThemeCss() {
  2566. if ($style == null) {
  2567. $style = addStyle('theme')
  2568. }
  2569. let cssRules = []
  2570.  
  2571. if (debug) {
  2572. cssRules.push(`
  2573. [data-item-type]::after {
  2574. position: absolute;
  2575. top: 0;
  2576. ${ltr ? 'right': 'left'}: 50px;
  2577. content: attr(data-item-type);
  2578. font-family: ${fontFamilyRule?.style.fontFamily || '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial'};
  2579. background-color: rgb(242, 29, 29);
  2580. color: white;
  2581. font-size: 11px;
  2582. font-weight: bold;
  2583. padding: 4px 6px;
  2584. border-bottom-left-radius: 1em;
  2585. border-bottom-right-radius: 1em;
  2586. }
  2587. `)
  2588. }
  2589.  
  2590. // Active tab colour for custom tabs
  2591. if (themeColor != null && shouldShowSeparatedTweetsTab()) {
  2592. cssRules.push(`
  2593. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2594. background-color: ${themeColor} !important;
  2595. }
  2596. `)
  2597. }
  2598.  
  2599. if (config.replaceLogo) {
  2600. cssRules.push(`
  2601. ${Selectors.X_LOGO_PATH} {
  2602. ${themeColor ? `fill: ${themeColor};` : ''}
  2603. d: path("${Svgs.TWITTER_LOGO_PATH}");
  2604. }
  2605. .tnt_logo {
  2606. ${themeColor ? `fill: ${themeColor};` : ''}
  2607. }
  2608. `)
  2609. }
  2610.  
  2611. if (config.uninvertFollowButtons) {
  2612. // Shared styles for Following and Follow buttons
  2613. cssRules.push(`
  2614. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2615. border-color: rgba(0, 0, 0, 0) !important;
  2616. }
  2617. [role="button"][data-testid$="-follow"] {
  2618. background-color: rgba(0, 0, 0, 0) !important;
  2619. }
  2620. `)
  2621. if (config.followButtonStyle == 'monochrome' || themeColor == null) {
  2622. cssRules.push(`
  2623. /* Following button */
  2624. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2625. background-color: rgb(15, 20, 25) !important;
  2626. }
  2627. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2628. color: rgb(255, 255, 255) !important;
  2629. }
  2630. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2631. background-color: rgb(255, 255, 255) !important;
  2632. }
  2633. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2634. color: rgb(15, 20, 25) !important;
  2635. }
  2636. /* Follow button */
  2637. body.Default [role="button"][data-testid$="-follow"] {
  2638. border-color: rgb(207, 217, 222) !important;
  2639. }
  2640. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] {
  2641. border-color: rgb(83, 100, 113) !important;
  2642. }
  2643. body.Default [role="button"][data-testid$="-follow"] > :is(div, span) {
  2644. color: rgb(15, 20, 25) !important;
  2645. }
  2646. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] > :is(div, span) {
  2647. color: rgb(255, 255, 255) !important;
  2648. }
  2649. body.Default [role="button"][data-testid$="-follow"]:hover {
  2650. background-color: rgba(15, 20, 25, 0.1) !important;
  2651. }
  2652. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"]:hover {
  2653. background-color: rgba(255, 255, 255, 0.1) !important;
  2654. }
  2655. `)
  2656. }
  2657. if (config.followButtonStyle == 'themed' && themeColor != null) {
  2658. cssRules.push(`
  2659. /* Following button */
  2660. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2661. background-color: ${themeColor} !important;
  2662. }
  2663. [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2664. color: rgb(255, 255, 255) !important;
  2665. }
  2666. /* Follow button */
  2667. [role="button"][data-testid$="-follow"] {
  2668. border-color: ${themeColor} !important;
  2669. }
  2670. [role="button"][data-testid$="-follow"] > :is(div, span) {
  2671. color: ${themeColor} !important;
  2672. }
  2673. [role="button"][data-testid$="-follow"]:hover {
  2674. background-color: ${themeColor} !important;
  2675. }
  2676. [role="button"][data-testid$="-follow"]:hover > :is(div, span) {
  2677. color: rgb(255, 255, 255) !important;
  2678. }
  2679. `)
  2680. }
  2681. if (mobile) {
  2682. cssRules.push(`
  2683. body.MediaViewer [role="button"][data-testid$="follow"]:not(:hover) {
  2684. border: revert !important;
  2685. background-color: transparent !important;
  2686. }
  2687. body.MediaViewer [role="button"][data-testid$="follow"]:not(:hover) > div {
  2688. color: ${themeColor} !important;
  2689. }
  2690. `)
  2691. }
  2692. }
  2693.  
  2694. $style.textContent = cssRules.map(dedent).join('\n')
  2695. }
  2696. })()
  2697.  
  2698. /**
  2699. * @param {HTMLElement} $tweet
  2700. * @param {?{getText?: boolean}} options
  2701. * @returns {import("./types").QuotedTweet}
  2702. */
  2703. function getQuotedTweetDetails($tweet, options = {}) {
  2704. let {getText = false} = options
  2705. let $quotedTweet = $tweet.querySelector('div[id^="id__"] > div[dir] > span').parentElement.nextElementSibling
  2706. let $userName = $quotedTweet?.querySelector('[data-testid="User-Name"]')
  2707. let user = $userName?.querySelector('[tabindex="-1"]')?.textContent
  2708. let time = $userName?.querySelector('time')?.dateTime
  2709. if (!getText) return {user, time}
  2710.  
  2711. let $heading = $quotedTweet?.querySelector(':scope > div > div:first-child')
  2712. let $qtText = $heading?.nextElementSibling?.querySelector('[lang]')
  2713. let text = $qtText && Array.from($qtText.childNodes, node => {
  2714. if (node.nodeType == 1) {
  2715. if (node.nodeName == 'IMG') return node.alt
  2716. return node.textContent
  2717. }
  2718. return node.nodeValue
  2719. }).join('')
  2720. return {user, time, text}
  2721. }
  2722.  
  2723. /**
  2724. * Attempts to determine the type of a timeline Tweet given the element with
  2725. * data-testid="tweet" on it, falling back to TWEET if it doesn't appear to be
  2726. * one of the particular types we care about.
  2727. * @param {HTMLElement} $tweet
  2728. * @param {?boolean} checkSocialContext
  2729. * @returns {import("./types").TweetType}
  2730. */
  2731. function getTweetType($tweet, checkSocialContext = false) {
  2732. if ($tweet.closest(Selectors.PROMOTED_TWEET_CONTAINER)) {
  2733. return 'PROMOTED_TWEET'
  2734. }
  2735. // Assume social context tweets are Retweets
  2736. if ($tweet.querySelector('[data-testid="socialContext"]')) {
  2737. if (checkSocialContext) {
  2738. let svgPath = $tweet.querySelector('svg path')?.getAttribute('d') ?? ''
  2739. if (svgPath.startsWith('M7 4.5C7 3.12 8.12 2 9.5 2h5C1')) return 'PINNED_TWEET'
  2740. }
  2741. // Quoted tweets from accounts you blocked or muted are displayed as an
  2742. // <article> with "This Tweet is unavailable."
  2743. if ($tweet.querySelector('article')) {
  2744. return 'UNAVAILABLE_RETWEET'
  2745. }
  2746. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2747. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2748. return 'RETWEETED_QUOTE_TWEET'
  2749. }
  2750. return 'RETWEET'
  2751. }
  2752. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2753. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2754. return 'QUOTE_TWEET'
  2755. }
  2756. // Quoted tweets from accounts you blocked or muted are displayed as an
  2757. // <article> with "This Tweet is unavailable."
  2758. if ($tweet.querySelector('article')) {
  2759. return 'UNAVAILABLE_QUOTE_TWEET'
  2760. }
  2761. return 'TWEET'
  2762. }
  2763.  
  2764. // Add 1 every time this gets broken: 6
  2765. function getVerifiedProps($svg) {
  2766. let propsGetter = (props) => props?.children?.props?.children?.[0]?.[0]?.props
  2767. let $parent = $svg.parentElement.parentElement
  2768. // Verified badge button on the profile screen
  2769. if (isOnProfilePage() && $svg.parentElement.getAttribute('role') == 'button') {
  2770. $parent = $svg.closest('span').parentElement
  2771. }
  2772. // Link variant in "user followed/liked/retweeted" notifications
  2773. else if (isOnNotificationsPage() && $parent.getAttribute('role') == 'link') {
  2774. propsGetter = (props) => {
  2775. let linkChildren = props?.children?.props?.children?.[0]
  2776. return linkChildren?.[linkChildren.length - 1]?.props
  2777. }
  2778. }
  2779. if ($parent.wrappedJSObject) {
  2780. $parent = $parent.wrappedJSObject
  2781. }
  2782. let reactPropsKey = Object.keys($parent).find(key => key.startsWith('__reactProps$'))
  2783. let props = propsGetter($parent[reactPropsKey])
  2784. if (!props) {
  2785. warn('React props not found for', $svg)
  2786. }
  2787. else if (!('isVerified' in props)) {
  2788. warn('isVerified not in React props for', $svg, {props})
  2789. }
  2790. return props
  2791. }
  2792.  
  2793. /**
  2794. * @param {HTMLElement} $popup
  2795. * @returns {{tookAction: boolean, onPopupClosed?: () => void}}
  2796. */
  2797. function handlePopup($popup) {
  2798. let result = {tookAction: false, onPopupClosed: null}
  2799.  
  2800. if (desktop && !isDesktopMediaModalOpen && URL_MEDIA_RE.test(location.pathname) && currentPath != location.pathname) {
  2801. log('media modal opened')
  2802. isDesktopMediaModalOpen = true
  2803. observeDesktopModalTimeline()
  2804. return {
  2805. tookAction: true,
  2806. onPopupClosed() {
  2807. log('media modal closed')
  2808. isDesktopMediaModalOpen = false
  2809. disconnectAllModalObservers()
  2810. }
  2811. }
  2812. }
  2813.  
  2814. if (config.twitterBlueChecks != 'ignore' && desktop && !isDesktopUserListModalOpen && URL_TWEET_LIKES_RETWEETS_RE.test(location.pathname)) {
  2815. let modalType = URL_TWEET_LIKES_RETWEETS_RE.exec(location.pathname)[1]
  2816. log(`${modalType} modal opened`)
  2817. isDesktopUserListModalOpen = true
  2818. observeUserListTimeline($popup, location.pathname)
  2819. return {
  2820. tookAction: true,
  2821. onPopupClosed() {
  2822. log(`${modalType} modal closed`)
  2823. isDesktopUserListModalOpen = false
  2824. disconnectAllModalObservers()
  2825. }
  2826. }
  2827. }
  2828.  
  2829. if (isOnListPage()) {
  2830. let $switchSvg = $popup.querySelector(`svg path[d^="M12 3.75c-4.56 0-8.25 3.69-8.25 8.25s"]`)
  2831. if ($switchSvg) {
  2832. addToggleListRetweetsMenuItem($popup.querySelector(`[role="menuitem"]`))
  2833. return {tookAction: true}
  2834. }
  2835. }
  2836.  
  2837. if (config.mutableQuoteTweets) {
  2838. if (quotedTweet) {
  2839. let $blockMenuItem = /** @type {HTMLElement} */ ($popup.querySelector(Selectors.BLOCK_MENU_ITEM))
  2840. if ($blockMenuItem) {
  2841. addMuteQuotesMenuItem($blockMenuItem)
  2842. result.tookAction = true
  2843. // Clear the quoted tweet when the popup closes
  2844. result.onPopupClosed = () => {
  2845. quotedTweet = null
  2846. }
  2847. } else {
  2848. quotedTweet = null
  2849. }
  2850. }
  2851. }
  2852.  
  2853. if (config.fastBlock) {
  2854. if (blockMenuItemSeen && $popup.querySelector('[data-testid="confirmationSheetConfirm"]')) {
  2855. log('fast blocking')
  2856. ;/** @type {HTMLElement} */ ($popup.querySelector('[data-testid="confirmationSheetConfirm"]')).click()
  2857. result.tookAction = true
  2858. }
  2859. else if ($popup.querySelector(Selectors.BLOCK_MENU_ITEM)) {
  2860. log('preparing for fast blocking')
  2861. blockMenuItemSeen = true
  2862. // Create a nested observer for mobile, as it reuses the popup element
  2863. result.tookAction = !mobile
  2864. } else {
  2865. blockMenuItemSeen = false
  2866. }
  2867. }
  2868.  
  2869. if (config.hideTwitterBlueUpsells) {
  2870. // The "Pin to your profile" menu item is currently the only one which opens
  2871. // a sheet dialog.
  2872. if (pinMenuItemSeen && $popup.querySelector('[data-testid="sheetDialog"]')) {
  2873. log('pin to your profile modal opened')
  2874. $popup.classList.add('PinModal')
  2875. result.tookAction = true
  2876. }
  2877. else if ($popup.querySelector('[data-testid="highlighOnPin"]')) {
  2878. log('preparing to hide Twitter Blue upsell when pinning a tweet')
  2879. pinMenuItemSeen = true
  2880. // Create a nested observer for mobile, as it reuses the popup element
  2881. result.tookAction = !mobile
  2882. } else {
  2883. pinMenuItemSeen = false
  2884. }
  2885. }
  2886.  
  2887. if (config.addAddMutedWordMenuItem) {
  2888. let linkSelector = desktop ? 'a[href$="/compose/tweet/unsent/drafts"]' : 'a[href$="/bookmarks"]'
  2889. let $link = /** @type {HTMLElement} */ ($popup.querySelector(linkSelector))
  2890. if ($link) {
  2891. addAddMutedWordMenuItem($link, linkSelector)
  2892. result.tookAction = true
  2893. }
  2894. }
  2895.  
  2896. if (config.twitterBlueChecks != 'ignore') {
  2897. // User typeahead dropdown
  2898. let $typeaheadDropdown = /** @type {HTMLElement} */ ($popup.querySelector('div[id^="typeaheadDropdown"]'))
  2899. if ($typeaheadDropdown) {
  2900. log('typeahead dropdown appeared')
  2901. let observer = observeElement($typeaheadDropdown, () => {
  2902. processBlueChecks($typeaheadDropdown)
  2903. }, 'popup typeahead dropdown')
  2904. return {
  2905. tookAction: true,
  2906. onPopupClosed() {
  2907. log('typeahead dropdown closed')
  2908. observer.disconnect()
  2909. }
  2910. }
  2911. }
  2912.  
  2913. // User hovercard popup
  2914. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  2915. if ($hoverCard) {
  2916. result.tookAction = true
  2917. getElement('div[data-testid^="UserAvatar-Container"]', {
  2918. context: $hoverCard,
  2919. name: 'user hovercard contents',
  2920. timeout: 500,
  2921. }).then(($contents) => {
  2922. if ($contents) processBlueChecks($popup)
  2923. })
  2924. }
  2925. }
  2926.  
  2927. // Verified account popup when you press the check button on a profile page
  2928. if (config.twitterBlueChecks == 'replace' && isOnProfilePage()) {
  2929. if (mobile) {
  2930. let $verificationBadge = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="sheetDialog"] [data-testid="verificationBadge"]'))
  2931. if ($verificationBadge) {
  2932. result.tookAction = true
  2933. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} .tnt_blue_check`)
  2934. if ($headerBlueCheck) {
  2935. blueCheck($verificationBadge)
  2936. }
  2937. }
  2938. } else {
  2939. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  2940. if ($hoverCard) {
  2941. result.tookAction = true
  2942. getElement(':scope > div > div > div > svg[data-testid="verificationBadge"]', {
  2943. context: $hoverCard,
  2944. name: 'verified account hovercard verification badge',
  2945. timeout: 500,
  2946. }).then(($verificationBadge) => {
  2947. if (!$verificationBadge) return
  2948.  
  2949. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 .tnt_blue_check`)
  2950. if (!$headerBlueCheck) return
  2951.  
  2952. // Wait for the hovercard to render its contents
  2953. let popupRenderObserver = observeElement($popup, (mutations) => {
  2954. if (!mutations.length) return
  2955. blueCheck($popup.querySelector('svg[data-testid="verificationBadge"]'))
  2956. popupRenderObserver.disconnect()
  2957. }, 'verified popup render', {childList: true, subtree: true})
  2958. })
  2959. }
  2960. }
  2961. }
  2962.  
  2963. return result
  2964. }
  2965.  
  2966. function isBlueVerified($svg) {
  2967. let props = getVerifiedProps($svg)
  2968. return Boolean(props && props.isBlueVerified && !(props.verifiedType || props.affiliateBadgeInfo?.userLabelType == 'BusinessLabel'))
  2969. }
  2970.  
  2971. /**
  2972. * Checks if a tweet is preceded by an element creating a vertical reply line.
  2973. * @param {HTMLElement} $tweet
  2974. * @returns {boolean}
  2975. */
  2976. function isReplyToPreviousTweet($tweet) {
  2977. let $replyLine = $tweet.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild
  2978. if ($replyLine) {
  2979. return getComputedStyle($replyLine).width == '2px'
  2980. }
  2981. }
  2982.  
  2983. /**
  2984. * @returns {{disconnect()}}
  2985. */
  2986. function onPopup($popup) {
  2987. log('popup appeared', $popup)
  2988.  
  2989. // If handlePopup did something, we don't need to observe nested popups
  2990. let {tookAction, onPopupClosed} = handlePopup($popup)
  2991. if (tookAction) {
  2992. return onPopupClosed ? {disconnect: onPopupClosed} : null
  2993. }
  2994.  
  2995. /** @type {HTMLElement} */
  2996. let $nestedPopup
  2997.  
  2998. let nestedObserver = observeElement($popup, (mutations) => {
  2999. mutations.forEach((mutation) => {
  3000. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3001. log('nested popup appeared', $el)
  3002. $nestedPopup = $el
  3003. ;({onPopupClosed} = handlePopup($el))
  3004. })
  3005. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3006. if ($el !== $nestedPopup) return
  3007. if (onPopupClosed) {
  3008. log('cleaning up after nested popup removed')
  3009. onPopupClosed()
  3010. }
  3011. })
  3012. })
  3013. })
  3014.  
  3015. let disconnect = nestedObserver.disconnect.bind(nestedObserver)
  3016. nestedObserver.disconnect = () => {
  3017. if (onPopupClosed) {
  3018. log('cleaning up after nested popup observer disconnected')
  3019. onPopupClosed()
  3020. }
  3021. disconnect()
  3022. }
  3023.  
  3024. return nestedObserver
  3025. }
  3026.  
  3027. /**
  3028. * @param {HTMLElement} $timeline
  3029. * @param {string} page
  3030. * @param {import("./types").TimelineOptions?} options
  3031. */
  3032. function onTimelineChange($timeline, page, options = {}) {
  3033. let startTime = Date.now()
  3034. let {classifyTweets = true, hideHeadings = true} = options
  3035.  
  3036. let isOnMainTimeline = isOnMainTimelinePage()
  3037. let isOnListTimeline = isOnListPage()
  3038. let isOnProfileTimeline = isOnProfilePage()
  3039. let timelineHasSpecificHandling = isOnMainTimeline || isOnListTimeline || isOnProfileTimeline
  3040.  
  3041. if (config.twitterBlueChecks != 'ignore' && !timelineHasSpecificHandling) {
  3042. processBlueChecks($timeline)
  3043. }
  3044.  
  3045. if (isSafari && config.replaceLogo && isOnNotificationsPage()) {
  3046. processTwitterLogos($timeline)
  3047. }
  3048.  
  3049. if (!classifyTweets) return
  3050.  
  3051. let itemTypes = {}
  3052. let hiddenItemCount = 0
  3053. let hiddenItemTypes = {}
  3054.  
  3055. /** @type {?boolean} */
  3056. let hidPreviousItem = null
  3057. /** @type {{$item: Element, hideItem?: boolean}[]} */
  3058. let changes = []
  3059.  
  3060. for (let $item of $timeline.children) {
  3061. /** @type {?import("./types").TimelineItemType} */
  3062. let itemType = null
  3063. /** @type {?boolean} */
  3064. let hideItem = null
  3065. /** @type {?HTMLElement} */
  3066. let $tweet = $item.querySelector(Selectors.TWEET)
  3067. /** @type {boolean} */
  3068. let isReply = false
  3069. /** @type {boolean} */
  3070. let isBlueTweet = false
  3071.  
  3072. if ($tweet != null) {
  3073. itemType = getTweetType($tweet, isOnProfileTimeline)
  3074. if (timelineHasSpecificHandling) {
  3075. isReply = isReplyToPreviousTweet($tweet)
  3076. if (isReply && hidPreviousItem != null) {
  3077. hideItem = hidPreviousItem
  3078. } else {
  3079. if (isOnMainTimeline) {
  3080. hideItem = shouldHideMainTimelineItem(itemType, page)
  3081. }
  3082. else if (isOnListTimeline) {
  3083. hideItem = shouldHideListTimelineItem(itemType)
  3084. }
  3085. else if (isOnProfileTimeline) {
  3086. hideItem = shouldHideProfileTimelineItem(itemType)
  3087. }
  3088. }
  3089.  
  3090. if (!hideItem && config.mutableQuoteTweets && (itemType == 'QUOTE_TWEET' || itemType == 'RETWEETED_QUOTE_TWEET')) {
  3091. if (config.mutedQuotes.length > 0) {
  3092. let quotedTweet = getQuotedTweetDetails($tweet)
  3093. hideItem = config.mutedQuotes.some(muted => muted.user == quotedTweet.user && muted.time == quotedTweet.time)
  3094. }
  3095. if (!hideItem) {
  3096. addCaretMenuListenerForQuoteTweet($tweet)
  3097. }
  3098. }
  3099.  
  3100. if (config.twitterBlueChecks != 'ignore') {
  3101. for (let $svg of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  3102. let isBlueCheck = isBlueVerified($svg)
  3103. if (!isBlueCheck) continue
  3104.  
  3105. blueCheck($svg)
  3106.  
  3107. let userProfileLink = $svg.closest('a[role="link"]:not([href^="/i/status"])')
  3108. if (!userProfileLink) continue
  3109.  
  3110. isBlueTweet = true
  3111. }
  3112. }
  3113. }
  3114. }
  3115. else if (!timelineHasSpecificHandling) {
  3116. if ($item.querySelector(':scope > div > div > div > article')) {
  3117. itemType = 'UNAVAILABLE'
  3118. }
  3119. }
  3120.  
  3121. if (!timelineHasSpecificHandling) {
  3122. if (itemType != null) {
  3123. hideItem = shouldHideOtherTimelineItem(itemType)
  3124. }
  3125. }
  3126.  
  3127. if (itemType == null) {
  3128. if ($item.querySelector(Selectors.TIMELINE_HEADING)) {
  3129. itemType = 'HEADING'
  3130. hideItem = hideHeadings && config.hideWhoToFollowEtc
  3131. }
  3132. }
  3133.  
  3134. if (debug && itemType != null) {
  3135. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${isBlueTweet ? ' / BLUE' : ''}`
  3136. }
  3137.  
  3138. // Assume a non-identified item following an identified item is related
  3139. if (itemType == null && hidPreviousItem != null) {
  3140. hideItem = hidPreviousItem
  3141. itemType = 'SUBSEQUENT_ITEM'
  3142. }
  3143.  
  3144. if (itemType != null) {
  3145. itemTypes[itemType] ||= 0
  3146. itemTypes[itemType]++
  3147. }
  3148.  
  3149. if (hideItem) {
  3150. hiddenItemCount++
  3151. hiddenItemTypes[itemType] ||= 0
  3152. hiddenItemTypes[itemType]++
  3153. }
  3154.  
  3155. if (hideItem != null && $item.firstElementChild) {
  3156. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  3157. changes.push({$item, hideItem})
  3158. }
  3159. }
  3160.  
  3161. hidPreviousItem = hideItem
  3162. }
  3163.  
  3164. for (let change of changes) {
  3165. /** @type {HTMLElement} */ (change.$item.firstElementChild).style.display = change.hideItem ? 'none' : ''
  3166. }
  3167.  
  3168. log(
  3169. `processed ${$timeline.children.length} timeline item${s($timeline.children.length)} in ${Date.now() - startTime}ms`,
  3170. itemTypes, `hid ${hiddenItemCount}`, hiddenItemTypes
  3171. )
  3172. }
  3173.  
  3174. /**
  3175. * @param {HTMLElement} $timeline
  3176. */
  3177. function onIndividualTweetTimelineChange($timeline) {
  3178. let startTime = Date.now()
  3179.  
  3180. let itemTypes = {}
  3181. let hiddenItemCount = 0
  3182. let hiddenItemTypes = {}
  3183.  
  3184. /** @type {?boolean} */
  3185. let hidPreviousItem = null
  3186. /** @type {boolean} */
  3187. let hideAllSubsequentItems = false
  3188. /** @type {string} */
  3189. let opScreenName = /^\/([a-zA-Z\d_]{1,20})\//.exec(location.pathname)[1].toLowerCase()
  3190. /** @type {{$item: Element, hideItem?: boolean}[]} */
  3191. let changes = []
  3192. /** @type {import("./types").UserInfoObject} */
  3193. let userInfo = getUserInfo()
  3194.  
  3195. for (let $item of $timeline.children) {
  3196. /** @type {?import("./types").TimelineItemType} */
  3197. let itemType = null
  3198. /** @type {?boolean} */
  3199. let hideItem = null
  3200. /** @type {?HTMLElement} */
  3201. let $tweet = $item.querySelector(Selectors.TWEET)
  3202. /** @type {boolean} */
  3203. let isFocusedTweet = false
  3204. /** @type {boolean} */
  3205. let isReply = false
  3206. /** @type {boolean} */
  3207. let isBlueTweet = false
  3208. /** @type {?string} */
  3209. let screenName = null
  3210.  
  3211. if (hideAllSubsequentItems) {
  3212. hideItem = true
  3213. itemType = 'DISCOVER_MORE_TWEET'
  3214. }
  3215. else if ($tweet != null) {
  3216. isFocusedTweet = $tweet.tabIndex == -1
  3217. isReply = isReplyToPreviousTweet($tweet)
  3218. if (isFocusedTweet) {
  3219. itemType = 'FOCUSED_TWEET'
  3220. hideItem = false
  3221. } else {
  3222. itemType = getTweetType($tweet)
  3223. if (isReply && hidPreviousItem != null) {
  3224. hideItem = hidPreviousItem
  3225. } else {
  3226. hideItem = shouldHideIndividualTweetTimelineItem(itemType)
  3227. }
  3228. }
  3229.  
  3230. if (config.twitterBlueChecks != 'ignore' || config.hideTwitterBlueReplies) {
  3231. for (let $svg of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  3232. let isBlueCheck = isBlueVerified($svg)
  3233. if (!isBlueCheck) continue
  3234.  
  3235. if (config.twitterBlueChecks != 'ignore') {
  3236. blueCheck($svg)
  3237. }
  3238.  
  3239. let userProfileLink = /** @type {HTMLAnchorElement} */ ($svg.closest('a[role="link"]:not([href^="/i/status"])'))
  3240. if (!userProfileLink) continue
  3241.  
  3242. isBlueTweet = true
  3243. screenName = userProfileLink.href.split('/').pop()
  3244. }
  3245.  
  3246. // Replies to the focused tweet don't have the reply indicator
  3247. if (isBlueTweet && !isFocusedTweet && !isReply && screenName.toLowerCase() != opScreenName) {
  3248. itemType = 'BLUE_REPLY'
  3249. if (!hideItem) {
  3250. let user = userInfo[screenName]
  3251. hideItem = config.hideTwitterBlueReplies && (user == null || !(
  3252. user.following && !config.hideBlueReplyFollowing ||
  3253. user.followedBy && !config.hideBlueReplyFollowedBy ||
  3254. user.followersCount >= 1000000 && config.showBlueReplyFollowersCount
  3255. ))
  3256. }
  3257. }
  3258. }
  3259. }
  3260. else if ($item.querySelector('article')) {
  3261. if ($item.querySelector('[role="button"]')?.textContent == getString('SHOW')) {
  3262. itemType = 'SHOW_MORE'
  3263. } else {
  3264. itemType = 'UNAVAILABLE'
  3265. hideItem = config.hideUnavailableQuoteTweets
  3266. }
  3267. } else {
  3268. // We need to identify "Show more replies" so it doesn't get hidden if the
  3269. // item immediately before it was hidden.
  3270. let $button = $item.querySelector('div[role="button"]')
  3271. if ($button) {
  3272. if ($button?.textContent == getString('SHOW_MORE_REPLIES')) {
  3273. itemType = 'SHOW_MORE'
  3274. }
  3275. } else {
  3276. let $heading = $item.querySelector(Selectors.TIMELINE_HEADING)
  3277. if ($heading) {
  3278. // Discover More headings have a description next to them
  3279. if ($heading.nextElementSibling &&
  3280. $heading.nextElementSibling.tagName == 'DIV' &&
  3281. $heading.nextElementSibling.getAttribute('dir') != null) {
  3282. itemType = 'DISCOVER_MORE_HEADING'
  3283. hideItem = config.hideMoreTweets
  3284. hideAllSubsequentItems = config.hideMoreTweets
  3285. } else {
  3286. itemType = 'HEADING'
  3287. }
  3288. }
  3289. }
  3290. }
  3291.  
  3292. if (debug && itemType != null) {
  3293. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${isBlueTweet && itemType != 'BLUE_REPLY' ? ' / BLUE' : ''}`
  3294. }
  3295.  
  3296. // Assume a non-identified item following an identified item is related
  3297. if (itemType == null && hidPreviousItem != null) {
  3298. hideItem = hidPreviousItem
  3299. itemType = 'SUBSEQUENT_ITEM'
  3300. }
  3301.  
  3302. if (itemType != null) {
  3303. itemTypes[itemType] ||= 0
  3304. itemTypes[itemType]++
  3305. }
  3306.  
  3307. if (hideItem) {
  3308. hiddenItemCount++
  3309. hiddenItemTypes[itemType] ||= 0
  3310. hiddenItemTypes[itemType]++
  3311. }
  3312.  
  3313. if (isFocusedTweet) {
  3314. // Tweets prior to the focused tweet should never be hidden
  3315. changes = []
  3316. hiddenItemCount = 0
  3317. hiddenItemTypes = {}
  3318. }
  3319. else if (hideItem != null && $item.firstElementChild) {
  3320. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  3321. changes.push({$item, hideItem})
  3322. }
  3323. }
  3324.  
  3325. hidPreviousItem = hideItem
  3326. }
  3327.  
  3328. for (let change of changes) {
  3329. /** @type {HTMLElement} */ (change.$item.firstElementChild).style.display = change.hideItem ? 'none' : ''
  3330. }
  3331.  
  3332. log(
  3333. `processed ${$timeline.children.length} thread item${s($timeline.children.length)} in ${Date.now() - startTime}ms`,
  3334. itemTypes, `hid ${hiddenItemCount}`, hiddenItemTypes
  3335. )
  3336. }
  3337.  
  3338. /**
  3339. * Title format (including notification count):
  3340. * - LTR: (3) ${title} / X
  3341. * - RTL: (3) X \ ${title}
  3342. * @param {string} title
  3343. */
  3344. function onTitleChange(title) {
  3345. log('title changed', {title, path: location.pathname})
  3346.  
  3347. if (checkforDisabledHomeTimeline()) return
  3348.  
  3349. // Ignore leading notification counts in titles
  3350. let notificationCount = ''
  3351. if (TITLE_NOTIFICATION_RE.test(title)) {
  3352. notificationCount = TITLE_NOTIFICATION_RE.exec(title)[0]
  3353. title = title.replace(TITLE_NOTIFICATION_RE, '')
  3354. }
  3355.  
  3356. if (config.replaceLogo && Boolean(notificationCount) != Boolean(currentNotificationCount)) {
  3357. observeFavicon.updatePip(Boolean(notificationCount))
  3358. }
  3359.  
  3360. let homeNavigationWasUsed = homeNavigationIsBeingUsed
  3361. homeNavigationIsBeingUsed = false
  3362.  
  3363. if (title == 'X' || title == getString('TWITTER')) {
  3364. // Mobile uses "Twitter" when viewing media - we need to let these process
  3365. // so the next page will be re-processed when the media is closed.
  3366. if (mobile && (URL_MEDIA_RE.test(location.pathname) || URL_MEDIAVIEWER_RE.test(location.pathname))) {
  3367. log('viewing media on mobile')
  3368. }
  3369. // Ignore Flash of Uninitialised Title when navigating to a page for the
  3370. // first time.
  3371. else {
  3372. log('ignoring Flash of Uninitialised Title')
  3373. return
  3374. }
  3375. }
  3376.  
  3377. // Remove " / Twitter" or "Twitter \ " from the title
  3378. let newPage = title
  3379. if (newPage != 'X' && newPage != getString('TWITTER')) {
  3380. newPage = title.slice(...ltr ? [0, title.lastIndexOf('/') - 1] : [title.indexOf('\\') + 2])
  3381. }
  3382.  
  3383. // Only allow the same page to re-process after a title change on desktop if
  3384. // the "Customize your view" dialog is currently open.
  3385. if (newPage == currentPage && !(desktop && location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW)) {
  3386. log('ignoring duplicate title change')
  3387. currentNotificationCount = notificationCount
  3388. return
  3389. }
  3390.  
  3391. // Search terms are shown in the title
  3392. if (currentPath == PagePaths.SEARCH && location.pathname == PagePaths.SEARCH) {
  3393. log('ignoring title change on Search page')
  3394. currentNotificationCount = notificationCount
  3395. return
  3396. }
  3397.  
  3398. // On desktop, stay on the separated tweets timeline when…
  3399. if (desktop && currentPage == separatedTweetsTimelineTitle &&
  3400. // …the title has changed back to the main timeline…
  3401. (newPage == getString('HOME')) &&
  3402. // …the Home nav link or Following / Home header _wasn't_ clicked and…
  3403. !homeNavigationWasUsed &&
  3404. (
  3405. // …the user viewed media.
  3406. URL_MEDIA_RE.test(location.pathname) ||
  3407. // …the user stopped viewing media.
  3408. URL_MEDIA_RE.test(currentPath) ||
  3409. // …the user opened or used the "Customize your view" dialog.
  3410. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  3411. // …the user closed the "Customize your view" dialog.
  3412. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  3413. // …the user opened the "Send via Direct Message" dialog.
  3414. location.pathname == PagePaths.COMPOSE_MESSAGE ||
  3415. // …the user closed the "Send via Direct Message" dialog.
  3416. currentPath == PagePaths.COMPOSE_MESSAGE ||
  3417. // …the user opened the compose Tweet dialog.
  3418. location.pathname == PagePaths.COMPOSE_TWEET ||
  3419. // …the user closed the compose Tweet dialog.
  3420. currentPath == PagePaths.COMPOSE_TWEET ||
  3421. // …the notification count in the title changed.
  3422. notificationCount != currentNotificationCount
  3423. )) {
  3424. log('ignoring title change on separated tweets timeline')
  3425. currentNotificationCount = notificationCount
  3426. currentPath = location.pathname
  3427. setTitle(separatedTweetsTimelineTitle)
  3428. return
  3429. }
  3430.  
  3431. // Restore display of the separated tweets timelne if it's the last one we
  3432. // saw, and the user navigated back home without using the Home navigation
  3433. // item.
  3434. if (location.pathname == PagePaths.HOME &&
  3435. currentPath != PagePaths.HOME &&
  3436. !homeNavigationWasUsed &&
  3437. lastMainTimelineTitle != null &&
  3438. separatedTweetsTimelineTitle != null &&
  3439. lastMainTimelineTitle == separatedTweetsTimelineTitle) {
  3440. log('restoring display of the separated tweets timeline')
  3441. currentNotificationCount = notificationCount
  3442. currentPath = location.pathname
  3443. setTitle(separatedTweetsTimelineTitle)
  3444. return
  3445. }
  3446.  
  3447. // Assumption: all non-FOUT, non-duplicate title changes are navigation, which
  3448. // need the page to be re-processed.
  3449.  
  3450. currentPage = newPage
  3451. currentNotificationCount = notificationCount
  3452. currentPath = location.pathname
  3453.  
  3454. if (isOnMainTimelinePage()) {
  3455. lastMainTimelineTitle = currentPage
  3456. }
  3457.  
  3458. log('processing new page')
  3459.  
  3460. processCurrentPage()
  3461. }
  3462.  
  3463. /**
  3464. * Processes all Twitter Blue checks inside an element.
  3465. * @param {HTMLElement} $el
  3466. */
  3467. function processBlueChecks($el) {
  3468. for (let $svg of $el.querySelectorAll(`${Selectors.VERIFIED_TICK}:not(.tnt_blue_check)`)) {
  3469. if (isBlueVerified($svg)) {
  3470. blueCheck($svg)
  3471. }
  3472. }
  3473. }
  3474.  
  3475. /**
  3476. * Processes all Twitter logos inside an element.
  3477. */
  3478. function processTwitterLogos($el) {
  3479. for (let $svgPath of $el.querySelectorAll(Selectors.X_LOGO_PATH)) {
  3480. twitterLogo($svgPath)
  3481. }
  3482. }
  3483.  
  3484. function processCurrentPage() {
  3485. if (pageObservers.length > 0) {
  3486. log(
  3487. `disconnecting ${pageObservers.length} page observer${s(pageObservers.length)}`,
  3488. pageObservers.map(observer => observer['name'])
  3489. )
  3490. pageObservers.forEach(observer => observer.disconnect())
  3491. pageObservers = []
  3492. }
  3493.  
  3494. // Hooks for styling pages
  3495. $body.classList.toggle('Community', isOnCommunityPage())
  3496. $body.classList.toggle('Explore', isOnExplorePage())
  3497. $body.classList.toggle('HideSidebar', shouldHideSidebar())
  3498. $body.classList.toggle('List', isOnListPage())
  3499. $body.classList.toggle('MainTimeline', isOnMainTimelinePage())
  3500. $body.classList.toggle('Notifications', isOnNotificationsPage())
  3501. $body.classList.toggle('Profile', isOnProfilePage())
  3502. if (!isOnProfilePage()) {
  3503. $body.classList.remove('Blocked', 'NoMedia')
  3504. }
  3505. $body.classList.toggle('QuoteTweets', isOnQuoteTweetsPage())
  3506. $body.classList.toggle('Tweet', isOnIndividualTweetPage())
  3507. $body.classList.toggle('Search', isOnSearchPage())
  3508. $body.classList.toggle('Settings', isOnSettingsPage())
  3509. $body.classList.toggle('MobileMedia', mobile && URL_MEDIA_RE.test(location.pathname))
  3510. $body.classList.toggle('MediaViewer', mobile && URL_MEDIAVIEWER_RE.test(location.pathname))
  3511. $body.classList.remove('TabbedTimeline')
  3512. $body.classList.remove('SeparatedTweets')
  3513.  
  3514. if (desktop) {
  3515. if (config.twitterBlueChecks != 'ignore' || config.fullWidthContent && (isOnMainTimelinePage() || isOnListPage())) {
  3516. observeSidebar()
  3517. } else {
  3518. $body.classList.remove('Sidebar')
  3519. }
  3520. if (isSafari && config.replaceLogo) {
  3521. tweakDesktopLogo()
  3522. }
  3523. }
  3524.  
  3525. if (config.twitterBlueChecks != 'ignore' && (isOnSearchPage() || isOnExplorePage())) {
  3526. observeSearchForm()
  3527. }
  3528.  
  3529. if (isOnMainTimelinePage()) {
  3530. tweakMainTimelinePage()
  3531. }
  3532. else {
  3533. removeMobileTimelineHeaderElements()
  3534. }
  3535.  
  3536. if (isOnProfilePage()) {
  3537. tweakProfilePage()
  3538. }
  3539. else if (isOnFollowListPage()) {
  3540. tweakFollowListPage()
  3541. }
  3542. else if (isOnIndividualTweetPage()) {
  3543. tweakIndividualTweetPage()
  3544. }
  3545. else if (isOnNotificationsPage()) {
  3546. tweakNotificationsPage()
  3547. }
  3548. else if (isOnSearchPage()) {
  3549. tweakSearchPage()
  3550. }
  3551. else if (isOnQuoteTweetsPage()) {
  3552. tweakQuoteTweetsPage()
  3553. }
  3554. else if (isOnListPage()) {
  3555. tweakListPage()
  3556. }
  3557. else if (isOnExplorePage()) {
  3558. tweakExplorePage()
  3559. }
  3560. else if (isOnBookmarksPage()) {
  3561. tweakBookmarksPage()
  3562. }
  3563. else if (isOnCommunitiesPage()) {
  3564. tweakCommunitiesPage()
  3565. }
  3566. else if (isOnCommunityPage()) {
  3567. tweakCommunityPage()
  3568. }
  3569. else if (isOnCommunityMembersPage()) {
  3570. tweakCommunityMembersPage()
  3571. }
  3572.  
  3573. // On mobile, these are pages instead of modals
  3574. if (mobile) {
  3575. if (currentPath == PagePaths.COMPOSE_TWEET) {
  3576. tweakMobileComposeTweetPage()
  3577. }
  3578. else if (URL_MEDIAVIEWER_RE.test(currentPath)) {
  3579. tweakMobileMediaViewerPage()
  3580. }
  3581. else if (URL_TWEET_LIKES_RETWEETS_RE.test(currentPath)) {
  3582. tweakMobileUserListPage()
  3583. }
  3584. }
  3585. }
  3586.  
  3587. /**
  3588. * The mobile version of Twitter reuses heading elements between screens, so we
  3589. * always remove any elements which could be there from the previous page and
  3590. * re-add them later when needed.
  3591. */
  3592. function removeMobileTimelineHeaderElements() {
  3593. if (mobile) {
  3594. document.querySelector('#tnt_separated_tweets_tab')?.remove()
  3595. }
  3596. }
  3597.  
  3598. /**
  3599. * Sets the page name in <title>, retaining any current notification count.
  3600. * @param {string} page
  3601. */
  3602. function setTitle(page) {
  3603. document.title = ltr ? (
  3604. `${currentNotificationCount}${page} / ${getString('TWITTER')}`
  3605. ) : (
  3606. `${currentNotificationCount}${getString('TWITTER')} \\ ${page}`
  3607. )
  3608. }
  3609.  
  3610. /**
  3611. * @param {import("./types").TimelineItemType} type
  3612. * @returns {boolean}
  3613. */
  3614. function shouldHideIndividualTweetTimelineItem(type) {
  3615. switch (type) {
  3616. case 'QUOTE_TWEET':
  3617. case 'RETWEET':
  3618. case 'RETWEETED_QUOTE_TWEET':
  3619. case 'TWEET':
  3620. return false
  3621. case 'UNAVAILABLE_QUOTE_TWEET':
  3622. case 'UNAVAILABLE_RETWEET':
  3623. return config.hideUnavailableQuoteTweets
  3624. default:
  3625. return true
  3626. }
  3627. }
  3628.  
  3629. /**
  3630. * @param {import("./types").TimelineItemType} type
  3631. * @returns {boolean}
  3632. */
  3633. function shouldHideListTimelineItem(type) {
  3634. switch (type) {
  3635. case 'RETWEET':
  3636. case 'RETWEETED_QUOTE_TWEET':
  3637. return config.listRetweets == 'hide'
  3638. case 'UNAVAILABLE_QUOTE_TWEET':
  3639. return config.hideUnavailableQuoteTweets
  3640. case 'UNAVAILABLE_RETWEET':
  3641. return config.hideUnavailableQuoteTweets || config.listRetweets == 'hide'
  3642. default:
  3643. return false
  3644. }
  3645. }
  3646.  
  3647. /**
  3648. * @param {import("./types").TimelineItemType} type
  3649. * @param {string} page
  3650. * @returns {boolean}
  3651. */
  3652. function shouldHideMainTimelineItem(type, page) {
  3653. switch (type) {
  3654. case 'QUOTE_TWEET':
  3655. return shouldHideSharedTweet(config.quoteTweets, page)
  3656. case 'RETWEET':
  3657. return selectedHomeTabIndex >= 2 ? config.listRetweets == 'hide' : shouldHideSharedTweet(config.retweets, page)
  3658. case 'RETWEETED_QUOTE_TWEET':
  3659. return selectedHomeTabIndex >= 2 ? (
  3660. config.listRetweets == 'hide'
  3661. ) : (
  3662. shouldHideSharedTweet(config.retweets, page) || shouldHideSharedTweet(config.quoteTweets, page)
  3663. )
  3664. case 'TWEET':
  3665. return page == separatedTweetsTimelineTitle
  3666. case 'UNAVAILABLE_QUOTE_TWEET':
  3667. return config.hideUnavailableQuoteTweets || shouldHideSharedTweet(config.quoteTweets, page)
  3668. case 'UNAVAILABLE_RETWEET':
  3669. return config.hideUnavailableQuoteTweets || selectedHomeTabIndex >= 2 ? config.listRetweets == 'hide' : shouldHideSharedTweet(config.retweets, page)
  3670. default:
  3671. return true
  3672. }
  3673. }
  3674.  
  3675. /**
  3676. * @param {import("./types").TimelineItemType} type
  3677. * @returns {boolean}
  3678. */
  3679. function shouldHideProfileTimelineItem(type) {
  3680. switch (type) {
  3681. case 'PINNED_TWEET':
  3682. case 'QUOTE_TWEET':
  3683. case 'TWEET':
  3684. return false
  3685. case 'RETWEET':
  3686. case 'RETWEETED_QUOTE_TWEET':
  3687. return config.hideProfileRetweets
  3688. case 'UNAVAILABLE_QUOTE_TWEET':
  3689. return config.hideUnavailableQuoteTweets
  3690. default:
  3691. return true
  3692. }
  3693. }
  3694.  
  3695. /**
  3696. * @param {import("./types").TimelineItemType} type
  3697. * @returns {boolean}
  3698. */
  3699. function shouldHideOtherTimelineItem(type) {
  3700. switch (type) {
  3701. case 'QUOTE_TWEET':
  3702. case 'RETWEET':
  3703. case 'RETWEETED_QUOTE_TWEET':
  3704. case 'TWEET':
  3705. case 'UNAVAILABLE':
  3706. case 'UNAVAILABLE_QUOTE_TWEET':
  3707. case 'UNAVAILABLE_RETWEET':
  3708. return false
  3709. default:
  3710. return true
  3711. }
  3712. }
  3713.  
  3714. /**
  3715. * @param {import("./types").SharedTweetsConfig} config
  3716. * @param {string} page
  3717. * @returns {boolean}
  3718. */
  3719. function shouldHideSharedTweet(config, page) {
  3720. switch (config) {
  3721. case 'hide': return true
  3722. case 'ignore': return page == separatedTweetsTimelineTitle
  3723. case 'separate': return page != separatedTweetsTimelineTitle
  3724. }
  3725. }
  3726.  
  3727. async function tweakBookmarksPage() {
  3728. if (config.twitterBlueChecks != 'ignore') {
  3729. observeTimeline(currentPage, {
  3730. classifyTweets: false,
  3731. })
  3732. }
  3733. }
  3734.  
  3735. async function tweakExplorePage() {
  3736. if (!config.hideExplorePageContents) return
  3737.  
  3738. let $searchInput = await getElement('input[data-testid="SearchBox_Search_Input"]', {
  3739. name: 'explore page search input',
  3740. stopIf: () => !isOnExplorePage(),
  3741. })
  3742. if (!$searchInput) return
  3743.  
  3744. log('focusing search input')
  3745. $searchInput.focus()
  3746.  
  3747. if (mobile) {
  3748. // The back button appears after the search input is focused on mobile. When
  3749. // you tap it or otherwise navigate back, it's replaced with the slide-out
  3750. // menu button and Explore page contents are shown - we want to skip that.
  3751. let $backButton = await getElement('div[data-testid="app-bar-back"]', {
  3752. name: 'back button',
  3753. stopIf: () => !isOnExplorePage(),
  3754. })
  3755. if (!$backButton) return
  3756.  
  3757. pageObservers.push(
  3758. observeElement($backButton.parentElement, (mutations) => {
  3759. mutations.forEach((mutation) => {
  3760. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3761. if ($el.querySelector('[data-testid="DashButton_ProfileIcon_Link"]')) {
  3762. log('slide-out menu button appeared, going back to skip Explore page')
  3763. history.go(-2)
  3764. }
  3765. })
  3766. })
  3767. }, 'back button parent')
  3768. )
  3769. }
  3770. }
  3771.  
  3772. function tweakCommunitiesPage() {
  3773. observeTimeline(currentPage)
  3774. }
  3775.  
  3776. function tweakCommunityPage() {
  3777. if (config.twitterBlueChecks != 'ignore') {
  3778. observeTimeline(currentPage, {
  3779. classifyTweets: false,
  3780. isTabbed: true,
  3781. tabbedTimelineContainerSelector: `${Selectors.PRIMARY_COLUMN} > div > div:last-child`,
  3782. onTimelineAppeared() {
  3783. // The About tab has static content at the top which can include a check
  3784. if (/\/about\/?$/.test(location.pathname)) {
  3785. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  3786. }
  3787. }
  3788. })
  3789. }
  3790. }
  3791.  
  3792. function tweakCommunityMembersPage() {
  3793. if (config.twitterBlueChecks != 'ignore') {
  3794. observeTimeline(currentPage, {
  3795. classifyTweets: false,
  3796. isTabbed: true,
  3797. timelineSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  3798. })
  3799. }
  3800. }
  3801.  
  3802. function tweakFollowListPage() {
  3803. if (config.twitterBlueChecks != 'ignore') {
  3804. observeTimeline(currentPage, {
  3805. classifyTweets: false,
  3806. })
  3807. }
  3808. }
  3809.  
  3810. function tweakIndividualTweetPage() {
  3811. observeTimeline(currentPage, {
  3812. hideHeadings: false,
  3813. onTimelineItemsChanged: onIndividualTweetTimelineChange
  3814. })
  3815. }
  3816.  
  3817. function tweakListPage() {
  3818. observeTimeline(currentPage, {
  3819. hideHeadings: false,
  3820. })
  3821. }
  3822.  
  3823. async function tweakDesktopLogo() {
  3824. let $logoPath = await getElement(`h1 ${Selectors.X_LOGO_PATH}`, {name: 'desktop nav logo', timeout: 5000})
  3825. if ($logoPath) {
  3826. twitterLogo($logoPath)
  3827. }
  3828. }
  3829.  
  3830. async function tweakTweetBox() {
  3831. if (config.twitterBlueChecks == 'ignore') return
  3832.  
  3833. let $tweetTextarea = await getElement(`${desktop ? 'div[data-testid="primaryColumn"]': 'main'} label[data-testid^="tweetTextarea"]`, {
  3834. name: 'tweet textarea',
  3835. stopIf: pageIsNot(currentPage),
  3836. })
  3837. if (!$tweetTextarea) return
  3838.  
  3839. /** @type {HTMLElement} */
  3840. let $typeaheadDropdown
  3841.  
  3842. pageObservers.push(
  3843. observeElement($tweetTextarea.parentElement.parentElement.parentElement.parentElement, (mutations) => {
  3844. for (let mutation of mutations) {
  3845. if ($typeaheadDropdown && mutations.some(mutation => Array.from(mutation.removedNodes).includes($typeaheadDropdown))) {
  3846. disconnectPageObserver('tweet textarea typeahead dropdown')
  3847. $typeaheadDropdown = null
  3848. }
  3849. for (let $addedNode of mutation.addedNodes) {
  3850. if ($addedNode instanceof HTMLElement && $addedNode.getAttribute('id')?.startsWith('typeaheadDropdown')) {
  3851. $typeaheadDropdown = $addedNode
  3852. pageObservers.push(
  3853. observeElement($typeaheadDropdown, () => {
  3854. processBlueChecks($typeaheadDropdown)
  3855. }, 'tweet textarea typeahead dropdown')
  3856. )
  3857. }
  3858. }
  3859. }
  3860. }, 'tweet textarea typeahead dropdown container')
  3861. )
  3862. }
  3863.  
  3864. function tweakMainTimelinePage() {
  3865. if (desktop) {
  3866. tweakTweetBox()
  3867. }
  3868.  
  3869. let $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3870.  
  3871. // "Which version of the main timeline are we on?" hooks for styling
  3872. $body.classList.toggle('TabbedTimeline', $timelineTabs != null)
  3873. $body.classList.toggle('SeparatedTweets', isOnSeparatedTweetsTimeline())
  3874.  
  3875. if ($timelineTabs == null) {
  3876. warn('could not find timeline tabs')
  3877. return
  3878. }
  3879.  
  3880. tweakTimelineTabs($timelineTabs)
  3881. if (mobile && isSafari && config.replaceLogo) {
  3882. processTwitterLogos(document.querySelector(Selectors.MOBILE_TIMELINE_HEADER_NEW))
  3883. }
  3884.  
  3885. function updateSelectedHomeTabIndex() {
  3886. let $selectedHomeTabLink = $timelineTabs.querySelector('div[role="tablist"] a[aria-selected="true"]')
  3887. if ($selectedHomeTabLink) {
  3888. selectedHomeTabIndex = Array.from($selectedHomeTabLink.parentElement.parentElement.children).indexOf($selectedHomeTabLink.parentElement)
  3889. log({selectedHomeTabIndex})
  3890. } else {
  3891. warn('could not find selected Home tab link')
  3892. selectedHomeTabIndex = -1
  3893. }
  3894. }
  3895.  
  3896. updateSelectedHomeTabIndex()
  3897.  
  3898. // If there are pinned lists, the timeline tabs <nav> will be replaced when they load
  3899. pageObservers.push(
  3900. observeElement($timelineTabs.parentElement, (mutations) => {
  3901. let timelineTabsReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($timelineTabs))
  3902. if (timelineTabsReplaced) {
  3903. log('timeline tabs replaced')
  3904. $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3905. tweakTimelineTabs($timelineTabs)
  3906. }
  3907. }, 'timeline tabs nav container')
  3908. )
  3909.  
  3910. observeTimeline(currentPage, {
  3911. isTabbed: true,
  3912. onTabChanged: () => {
  3913. updateSelectedHomeTabIndex()
  3914. wasForYouTabSelected = selectedHomeTabIndex == 0
  3915. },
  3916. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child > div',
  3917. })
  3918. }
  3919.  
  3920. function tweakMobileComposeTweetPage() {
  3921. tweakTweetBox()
  3922. }
  3923.  
  3924. function tweakMobileMediaViewerPage() {
  3925. if (config.twitterBlueChecks == 'ignore') return
  3926.  
  3927. let $timeline = /** @type {HTMLElement} */ (document.querySelector('[data-testid="vss-scroll-view"] > div'))
  3928. if (!$timeline) {
  3929. warn('media viewer timeline not found')
  3930. return
  3931. }
  3932.  
  3933. observeElement($timeline, (mutations) => {
  3934. for (let mutation of mutations) {
  3935. if (!mutation.addedNodes) continue
  3936. for (let $addedNode of mutation.addedNodes) {
  3937. if ($addedNode.querySelector?.('div[data-testid^="immersive-tweet-ui-content-container"]')) {
  3938. processBlueChecks($addedNode)
  3939. }
  3940. }
  3941. }
  3942. }, 'media viewer timeline', {childList: true, subtree: true})
  3943. }
  3944.  
  3945. async function tweakTimelineTabs($timelineTabs) {
  3946. let $followingTabLink = /** @type {HTMLElement} */ ($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a'))
  3947.  
  3948. if (config.alwaysUseLatestTweets && !document.title.startsWith(separatedTweetsTimelineTitle)) {
  3949. let isForYouTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:first-child > a[aria-selected="true"]'))
  3950. if (isForYouTabSelected && (!wasForYouTabSelected || config.hideForYouTimeline)) {
  3951. log('switching to Following timeline')
  3952. $followingTabLink.click()
  3953. wasForYouTabSelected = false
  3954. } else {
  3955. wasForYouTabSelected = isForYouTabSelected
  3956. }
  3957. }
  3958.  
  3959. if (shouldShowSeparatedTweetsTab()) {
  3960. let $newTab = /** @type {HTMLElement} */ ($timelineTabs.querySelector('#tnt_separated_tweets_tab'))
  3961. if ($newTab) {
  3962. log('separated tweets timeline tab already present')
  3963. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  3964. }
  3965. else {
  3966. log('inserting separated tweets tab')
  3967. $newTab = /** @type {HTMLElement} */ ($followingTabLink.parentElement.cloneNode(true))
  3968. $newTab.id = 'tnt_separated_tweets_tab'
  3969. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  3970. let $link = $newTab.querySelector('a')
  3971. $link.removeAttribute('aria-selected')
  3972.  
  3973. // This script assumes navigation has occurred when the document title
  3974. // changes, so by changing the title we fake navigation to a non-existent
  3975. // page representing the separated tweets timeline.
  3976. $link.addEventListener('click', (e) => {
  3977. e.preventDefault()
  3978. e.stopPropagation()
  3979. if (!document.title.startsWith(separatedTweetsTimelineTitle)) {
  3980. // The separated tweets tab belongs to the Following tab
  3981. let isFollowingTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  3982. if (!isFollowingTabSelected) {
  3983. log('switching to the Following tab for separated tweets')
  3984. $followingTabLink.click()
  3985. }
  3986. setTitle(separatedTweetsTimelineTitle)
  3987. }
  3988. window.scrollTo({top: 0})
  3989. })
  3990. $followingTabLink.parentElement.insertAdjacentElement('afterend', $newTab)
  3991.  
  3992. // Return to the main timeline view when any other tab is clicked
  3993. $followingTabLink.parentElement.parentElement.addEventListener('click', () => {
  3994. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  3995. log('setting title to Home')
  3996. homeNavigationIsBeingUsed = true
  3997. setTitle(getString('HOME'))
  3998. }
  3999. })
  4000.  
  4001. // Return to the main timeline when the Home nav link is clicked
  4002. let $homeNavLink = await getElement(Selectors.NAV_HOME_LINK, {
  4003. name: 'home nav link',
  4004. stopIf: pathIsNot(currentPath),
  4005. })
  4006. if ($homeNavLink && !$homeNavLink.dataset.tweakNewTwitterListener) {
  4007. $homeNavLink.addEventListener('click', () => {
  4008. homeNavigationIsBeingUsed = true
  4009. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  4010. setTitle(getString('HOME'))
  4011. }
  4012. })
  4013. $homeNavLink.dataset.tweakNewTwitterListener = 'true'
  4014. }
  4015. }
  4016. } else {
  4017. removeMobileTimelineHeaderElements()
  4018. }
  4019. }
  4020.  
  4021. function tweakMobileUserListPage() {
  4022. if (config.twitterBlueChecks == 'ignore') return
  4023.  
  4024. observeUserListTimeline(undefined, currentPath)
  4025. }
  4026.  
  4027. function tweakNotificationsPage() {
  4028. let $navigationTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4029. if ($navigationTabs == null) {
  4030. warn('could not find Notifications tabs')
  4031. return
  4032. }
  4033.  
  4034. if (config.hideVerifiedNotificationsTab) {
  4035. let isVerifiedTabSelected = Boolean($navigationTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  4036. if (isVerifiedTabSelected) {
  4037. log('switching to All tab')
  4038. $navigationTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a')?.click()
  4039. }
  4040. }
  4041.  
  4042. if (config.twitterBlueChecks != 'ignore') {
  4043. observeTimeline(currentPage, {
  4044. classifyTweets: false,
  4045. isTabbed: true,
  4046. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  4047. })
  4048. }
  4049. }
  4050.  
  4051. function tweakProfilePage() {
  4052. if (config.twitterBlueChecks != 'ignore') {
  4053. if (mobile) {
  4054. processBlueChecks(document.querySelector(Selectors.MOBILE_TIMELINE_HEADER_NEW))
  4055. }
  4056. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  4057. }
  4058. observeTimeline(currentPage)
  4059. if (desktop && config.hideSidebarContent) {
  4060. observeProfileBlockedStatus(currentPage)
  4061. observeProfileSidebar(currentPage)
  4062. }
  4063. }
  4064.  
  4065. function tweakQuoteTweetsPage() {
  4066. if (config.twitterBlueChecks != 'ignore') {
  4067. observeTimeline(currentPage)
  4068. }
  4069. }
  4070.  
  4071. function tweakSearchPage() {
  4072. let $searchTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4073. if ($searchTabs != null) {
  4074. if (config.defaultToLatestSearch) {
  4075. let isTopTabSelected = Boolean($searchTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a[aria-selected="true"]'))
  4076. if (isTopTabSelected) {
  4077. log('switching to Latest tab')
  4078. $searchTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a')?.click()
  4079. }
  4080. }
  4081. } else {
  4082. warn('could not find Search tabs')
  4083. }
  4084.  
  4085. observeTimeline(currentPage, {
  4086. hideHeadings: false,
  4087. isTabbed: true,
  4088. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  4089. })
  4090. }
  4091. //#endregion
  4092.  
  4093. //#region Main
  4094. async function main() {
  4095. let $settings = /** @type {HTMLScriptElement} */ (document.querySelector('script#tnt_settings'))
  4096. if ($settings) {
  4097. try {
  4098. Object.assign(config, JSON.parse($settings.innerText))
  4099. } catch(e) {
  4100. error('error parsing initial settings', e)
  4101. }
  4102.  
  4103. let settingsChangeObserver = new MutationObserver(() => {
  4104. /** @type {Partial<import("./types").Config>} */
  4105. let configChanges
  4106. try {
  4107. configChanges = JSON.parse($settings.innerText)
  4108. } catch(e) {
  4109. error('error parsing incoming settings change', e)
  4110. return
  4111. }
  4112.  
  4113. if ('debug' in configChanges) {
  4114. log('disabling debug mode')
  4115. debug = configChanges.debug
  4116. log('enabled debug mode')
  4117. configureThemeCss()
  4118. return
  4119. }
  4120.  
  4121. Object.assign(config, configChanges)
  4122. configChanged(configChanges)
  4123. })
  4124. settingsChangeObserver.observe($settings, {childList: true})
  4125. }
  4126.  
  4127. if (config.debug) {
  4128. debug = true
  4129. }
  4130.  
  4131. let $loadingStyle
  4132. if (config.replaceLogo) {
  4133. getElement('html', {name: 'html element'}).then(($html) => {
  4134. $loadingStyle = document.createElement('style')
  4135. $loadingStyle.dataset.insertedBy = 'control-panel-for-twitter'
  4136. $loadingStyle.dataset.role = 'loading-logo'
  4137. let logoThemeColor = themeColor || Array.from(THEME_COLORS)[0]
  4138. $loadingStyle.textContent = dedent(`
  4139. ${Selectors.X_LOGO_PATH} {
  4140. fill: ${isSafari ? 'transparent' : logoThemeColor};
  4141. d: path("${Svgs.TWITTER_LOGO_PATH}");
  4142. }
  4143. .tnt_logo {
  4144. fill: ${logoThemeColor};
  4145. }
  4146. `)
  4147. $html.appendChild($loadingStyle)
  4148. })
  4149.  
  4150. if (isSafari) {
  4151. getElement(Selectors.X_LOGO_PATH, {name: 'pre-loading indicator logo', timeout: 1000}).then(($logoPath) => {
  4152. if ($logoPath) {
  4153. twitterLogo($logoPath)
  4154. }
  4155. })
  4156. }
  4157.  
  4158. observeFavicon()
  4159. }
  4160.  
  4161. let $appWrapper = await getElement('#layers + div', {name: 'app wrapper'})
  4162.  
  4163. $html = document.querySelector('html')
  4164. $body = document.body
  4165. $reactRoot = document.querySelector('#react-root')
  4166. lang = $html.lang
  4167. dir = $html.dir
  4168. ltr = dir == 'ltr'
  4169. let lastFlexDirection
  4170.  
  4171. observeElement($appWrapper, () => {
  4172. let flexDirection = getComputedStyle($appWrapper).flexDirection
  4173.  
  4174. mobile = flexDirection == 'column'
  4175. desktop = !mobile
  4176.  
  4177. /** @type {'mobile' | 'desktop'} */
  4178. let version = mobile ? 'mobile' : 'desktop'
  4179.  
  4180. if (version != config.version) {
  4181. log('setting version to', version)
  4182. config.version = version
  4183. // Let the options page know which version is being used
  4184. storeConfigChanges({version})
  4185. }
  4186.  
  4187. if (lastFlexDirection == null) {
  4188. log('initial config', {config, lang, version})
  4189.  
  4190. // One-time setup
  4191. checkReactNativeStylesheet()
  4192. observeBodyBackgroundColor()
  4193. observeColor()
  4194.  
  4195. // Repeatable configuration setup
  4196. configureSeparatedTweetsTimelineTitle()
  4197. configureCss()
  4198. configureThemeCss()
  4199. observeHtmlFontSize()
  4200. observePopups()
  4201.  
  4202. // Start watching for page changes
  4203. observeTitle()
  4204.  
  4205. // Delay removing loading icon styles to avoid Flash of X
  4206. if ($loadingStyle) {
  4207. setTimeout(() => $loadingStyle.remove(), 1000)
  4208. }
  4209. }
  4210. else if (flexDirection != lastFlexDirection) {
  4211. observeHtmlFontSize()
  4212. configChanged({version})
  4213. }
  4214.  
  4215. $body.classList.toggle('Mobile', mobile)
  4216. $body.classList.toggle('Desktop', desktop)
  4217.  
  4218. lastFlexDirection = flexDirection
  4219. }, 'app wrapper class attribute for version changes (mobile ↔ desktop)', {
  4220. attributes: true,
  4221. attributeFilter: ['class']
  4222. })
  4223. }
  4224.  
  4225. /**
  4226. * @param {Partial<import("./types").Config>} changes
  4227. */
  4228. function configChanged(changes) {
  4229. log('config changed', changes)
  4230.  
  4231. configureCss()
  4232. configureFont()
  4233. configureNavFontSizeCss()
  4234. configureThemeCss()
  4235. observeFavicon()
  4236. observePopups()
  4237.  
  4238. // Only re-process the current page if navigation wasn't already triggered
  4239. // while applying the following config changes (if there were any).
  4240. let navigationTriggered = (
  4241. configureSeparatedTweetsTimelineTitle() ||
  4242. checkforDisabledHomeTimeline()
  4243. )
  4244. if (!navigationTriggered) {
  4245. processCurrentPage()
  4246. }
  4247. }
  4248.  
  4249. main()
  4250. //#endregion
  4251.  
  4252. }()