Control Panel for Twitter

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

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

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