Tweak New Twitter

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

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

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