Tweak New Twitter

Remove algorithmic content from Twitter, hide news & trends, control which shared tweets appear on your timeline, and improve the UI

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

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