Tweak New Twitter

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

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

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