Tweak New Twitter

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

当前为 2022-11-15 提交的版本,查看 最新版本

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