Control Panel for Twitter

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

当前为 2023-06-20 提交的版本,查看 最新版本

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