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-11 提交的版本,查看 最新版本

  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 65
  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. TIMELINE: 'div[data-testid="primaryColumn"] section > h1 + div[aria-label] > div',
  666. TIMELINE_HEADING: 'h2[role="heading"]',
  667. TWEET: '[data-testid="tweet"]',
  668. 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."]',
  669. }
  670.  
  671. /** @enum {string} */
  672. const Svgs = {
  673. 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>',
  674. 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>',
  675. 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>',
  676. }
  677.  
  678. const MOBILE_LOGGED_OUT_URLS = ['/', '/i/flow/login', '/i/flow/signup']
  679. const PROFILE_FOLLOWS_URL_RE = /\/[a-zA-Z\d_]{1,15}\/(following|followers|followers_you_follow)\/?$/
  680. const PROFILE_TABS_URL_RE = /\/[a-zA-Z\d_]{1,15}\/(with_replies|media|likes)\/?$/
  681. // https://twitter.com/${user}'s title ends with (@${user})
  682. const PROFILE_TITLE_RE = /\(@[a-zA-Z\d_]{1,15}\)$/
  683. const THEME_COLORS = new Set([
  684. 'rgb(29, 155, 240)', // blue
  685. 'rgb(255, 212, 0)', // yellow
  686. 'rgb(244, 33, 46)', // pink
  687. 'rgb(120, 86, 255)', // purple
  688. 'rgb(255, 122, 0)', // orange
  689. 'rgb(0, 186, 124)', // green
  690. ])
  691. const TITLE_NOTIFICATION_RE = /^\(\d+\+?\) /
  692. const URL_PHOTO_RE = /photo\/\d$/
  693. const URL_LIST_RE = /\/i\/lists\/\d+$/
  694. const URL_TWEET_ID_RE = /\/status\/(\d+)$/
  695.  
  696. /**
  697. * The quoted Tweet associated with a caret menu that's just been opened.
  698. * @type {import("./types").QuotedTweet}
  699. */
  700. let quotedTweet = null
  701.  
  702. /** `true` when a 'Block @${user}' menu item was seen in the last popup. */
  703. let blockMenuItemSeen = false
  704.  
  705. /** `'Home'` or `'Latest Tweets'` page title. */
  706. let currentMainTimelineType = ''
  707.  
  708. /** Notification count in the title (including trailing space), e.g. `'(1) '`. */
  709. let currentNotificationCount = ''
  710.  
  711. /** Title of the current page, without the `' / Twitter'` suffix. */
  712. let currentPage = ''
  713.  
  714. /** Current `location.pathname`. */
  715. let currentPath = ''
  716.  
  717. /**
  718. * CSS rule in the React Native stylesheet which defines the Chirp font-family
  719. * and fallbacks for the whole app.
  720. * @type {CSSStyleRule}
  721. */
  722. let fontFamilyRule = null
  723.  
  724. /** @type {string} */
  725. let fontSize = null
  726.  
  727. /** Set to `true` when a Home/Latest Tweets heading or Home nav link is used. */
  728. let homeNavigationIsBeingUsed = false
  729.  
  730. /**
  731. * Cache for the last page title which was used for the main timeline.
  732. * @type {string}
  733. */
  734. let lastMainTimelineTitle = null
  735.  
  736. /** `true` when `<title>` has appeared and we're observing it for changes. */
  737. let observingTitle = false
  738.  
  739. /**
  740. * MutationObservers active on the current page, or anything else we want to
  741. * clean up when the user moves off the current page.
  742. * @type {(MutationObserver|{disconnect(): void})[]}
  743. */
  744. let pageObservers = []
  745.  
  746. /**
  747. * Title for the fake timeline used to separate out retweets and quote tweets.
  748. * @type {string}
  749. */
  750. let separatedTweetsTimelineTitle = null
  751.  
  752. /**
  753. * The current "Color" setting, which can be changed in "Customize your view".
  754. * @type {string}
  755. */
  756. let themeColor = null
  757.  
  758. function isOnExplorePage() {
  759. return currentPath.startsWith('/explore')
  760. }
  761.  
  762. function isOnHomeTimeline() {
  763. return currentPage == getString('HOME')
  764. }
  765.  
  766. function isOnIndividualTweetPage() {
  767. return URL_TWEET_ID_RE.test(currentPath)
  768. }
  769.  
  770. function isOnLatestTweetsTimeline() {
  771. return currentPage == getString('LATEST_TWEETS')
  772. }
  773.  
  774. function isOnListPage() {
  775. return URL_LIST_RE.test(currentPath)
  776. }
  777.  
  778. function isOnMainTimelinePage() {
  779. return currentPath == PagePaths.HOME || (
  780. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW &&
  781. isOnHomeTimeline() ||
  782. isOnLatestTweetsTimeline() ||
  783. isOnSeparatedTweetsTimeline()
  784. )
  785. }
  786.  
  787. function isOnNotificationsPage() {
  788. return currentPath.startsWith('/notifications')
  789. }
  790.  
  791. function isOnProfilePage() {
  792. return PROFILE_TITLE_RE.test(currentPage) && !PROFILE_FOLLOWS_URL_RE.test(currentPath)
  793. }
  794.  
  795. function isOnQuoteTweetsPage() {
  796. return currentPath.endsWith('/retweets/with_comments')
  797. }
  798.  
  799. function isOnSearchPage() {
  800. return currentPath.startsWith('/search')
  801. }
  802.  
  803. function isOnSeparatedTweetsTimeline() {
  804. return currentPage == separatedTweetsTimelineTitle
  805. }
  806.  
  807. function isOnTabbedTimeline() {
  808. if (!isOnMainTimelinePage()) {
  809. return false
  810. }
  811. let $header = document.querySelector(desktop ? Selectors.DESKTOP_TIMELINE_HEADER : Selectors.MOBILE_TIMELINE_HEADER_OLD)
  812. return $header?.childElementCount == (desktop ? 3 : 2)
  813. }
  814.  
  815. function isOnTopicsPage() {
  816. return currentPath != '/topics' && Boolean(currentPath.match(/\/topics(\/|$)/))
  817. }
  818.  
  819. function shouldHideSidebar() {
  820. return isOnExplorePage()
  821. }
  822. //#endregion
  823.  
  824. //#region Utility functions
  825. /**
  826. * @param {string} role
  827. * @return {HTMLStyleElement}
  828. */
  829. function addStyle(role) {
  830. let $style = document.createElement('style')
  831. $style.dataset.insertedBy = 'tweak-new-twitter'
  832. $style.dataset.role = role
  833. document.head.appendChild($style)
  834. return $style
  835. }
  836.  
  837. /**
  838. * @param {string} str
  839. * @return {string}
  840. */
  841. function dedent(str) {
  842. str = str.replace(/^[ \t]*\r?\n/, '')
  843. let indent = /^[ \t]+/m.exec(str)
  844. if (indent) str = str.replace(new RegExp('^' + indent[0], 'gm'), '')
  845. return str.replace(/(\r?\n)[ \t]+$/, '$1')
  846. }
  847.  
  848. /**
  849. * @param {string} selector
  850. * @param {{
  851. * name?: string
  852. * stopIf?: () => boolean
  853. * timeout?: number
  854. * context?: Document | HTMLElement
  855. * }} [options]
  856. * @returns {Promise<HTMLElement | null>}
  857. */
  858. function getElement(selector, {
  859. name = null,
  860. stopIf = null,
  861. timeout = Infinity,
  862. context = document,
  863. } = {}) {
  864. return new Promise((resolve) => {
  865. let startTime = Date.now()
  866. let rafId
  867. let timeoutId
  868.  
  869. function stop($element, reason) {
  870. if ($element == null) {
  871. warn(`stopped waiting for ${name || selector} after ${reason}`)
  872. }
  873. else if (Date.now() > startTime) {
  874. log(`${name || selector} appeared after ${Date.now() - startTime}ms`)
  875. }
  876. if (rafId) {
  877. cancelAnimationFrame(rafId)
  878. }
  879. if (timeoutId) {
  880. clearTimeout(timeoutId)
  881. }
  882. resolve($element)
  883. }
  884.  
  885. if (timeout !== Infinity) {
  886. timeoutId = setTimeout(stop, timeout, null, `${timeout}ms timeout`)
  887. }
  888.  
  889. function queryElement() {
  890. let $element = context.querySelector(selector)
  891. if ($element) {
  892. stop($element)
  893. }
  894. else if (stopIf?.() === true) {
  895. stop(null, 'stopIf condition met')
  896. }
  897. else {
  898. rafId = requestAnimationFrame(queryElement)
  899. }
  900. }
  901.  
  902. queryElement()
  903. })
  904. }
  905.  
  906. function log(...args) {
  907. if (debug) {
  908. console.log(`🧨${currentPage ? `(${currentPage})` : ''}`, ...args)
  909. }
  910. }
  911.  
  912. function warn(...args) {
  913. if (debug) {
  914. console.log(`⚠${currentPage ? `(${currentPage})` : ''}`, ...args)
  915. }
  916. }
  917.  
  918. /**
  919. * @param {() => boolean} condition
  920. * @returns {() => boolean}
  921. */
  922. function not(condition) {
  923. return () => !condition()
  924. }
  925.  
  926. /**
  927. * Convenience wrapper for the MutationObserver API - the callback is called
  928. * immediately to support using an observer and its options as a trigger for any
  929. * change, without looking at MutationRecords.
  930. * @param {Node} $element
  931. * @param {MutationCallback} callback
  932. * @param {string} name
  933. * @param {MutationObserverInit} options
  934. */
  935. function observeElement($element, callback, name = '', options = {childList: true}) {
  936. if (name) {
  937. if (options.childList && callback.length > 0) {
  938. log(`observing ${name}`, $element)
  939. } else {
  940. log (`observing ${name}`)
  941. }
  942. }
  943.  
  944. let observer = new MutationObserver(callback)
  945. callback([], observer)
  946. observer.observe($element, options)
  947. observer['name'] = name
  948. return observer
  949. }
  950.  
  951. /**
  952. * @param {Partial<import("./types").Config>} configChanges
  953. */
  954. function onSettingsChanged(configChanges) {
  955. if ('debug' in configChanges) {
  956. log('disabling debug mode')
  957. debug = configChanges.debug
  958. log('enabled debug mode')
  959. configureThemeCss()
  960. return
  961. }
  962. Object.assign(config, configChanges)
  963. configChanged(configChanges)
  964. }
  965.  
  966. /**
  967. * @param {string} page
  968. * @returns {() => boolean}
  969. */
  970. function pageIsNot(page) {
  971. return () => page != currentPage
  972. }
  973.  
  974. /**
  975. * @param {string} path
  976. * @returns {() => boolean}
  977. */
  978. function pathIsNot(path) {
  979. return () => path != currentPath
  980. }
  981.  
  982. /**
  983. * @param {number} n
  984. * @returns {string}
  985. */
  986. function s(n) {
  987. return n == 1 ? '' : 's'
  988. }
  989.  
  990. function storeConfigChanges(changes) {
  991. window.postMessage({type: 'tntConfigChange', changes})
  992. }
  993. //#endregion
  994.  
  995. //#region Global observers
  996. const checkReactNativeStylesheet = (() => {
  997. let startTime = Date.now()
  998.  
  999. return function checkReactNativeStylesheet() {
  1000. let $style = /** @type {HTMLStyleElement} */ (document.querySelector('style#react-native-stylesheet'))
  1001. if (!$style) {
  1002. warn('React Native stylesheet not found')
  1003. return
  1004. }
  1005.  
  1006. for (let rule of $style.sheet.cssRules) {
  1007. if (!(rule instanceof CSSStyleRule)) continue
  1008.  
  1009. if (fontFamilyRule == null &&
  1010. rule.style.fontFamily &&
  1011. rule.style.fontFamily.includes('TwitterChirp')) {
  1012. fontFamilyRule = rule
  1013. log('found Chirp fontFamily CSS rule in React Native stylesheet')
  1014. configureFont()
  1015. }
  1016.  
  1017. if (themeColor == null &&
  1018. rule.style.backgroundColor &&
  1019. THEME_COLORS.has(rule.style.backgroundColor)) {
  1020. themeColor = rule.style.backgroundColor
  1021. log(`found initial theme color in React Native stylesheet: ${themeColor}`)
  1022. configureThemeCss()
  1023. }
  1024. }
  1025.  
  1026. let elapsedTime = Date.now() - startTime
  1027. if (fontFamilyRule == null || themeColor == null) {
  1028. if (elapsedTime < 3000) {
  1029. setTimeout(checkReactNativeStylesheet, 100)
  1030. } else {
  1031. warn(`stopped checking React Native stylesheet after ${elapsedTime}ms`)
  1032. }
  1033. } else {
  1034. log(`finished checking React Native stylesheet in ${elapsedTime}ms`)
  1035. }
  1036. }
  1037. })()
  1038.  
  1039. /**
  1040. * When the "Background" setting is changed in "Customize your view", <body>'s
  1041. * backgroundColor is changed and the app is re-rendered, so we need to
  1042. * re-process the current page.
  1043. */
  1044. function observeBodyBackgroundColor() {
  1045. let lastBackgroundColor = null
  1046.  
  1047. observeElement($body, () => {
  1048. let backgroundColor = $body.style.backgroundColor
  1049. if (backgroundColor == lastBackgroundColor) return
  1050.  
  1051. $body.classList.toggle('Default', backgroundColor == 'rgb(255, 255, 255)')
  1052. $body.classList.toggle('Dim', backgroundColor == 'rgb(21, 32, 43)')
  1053. $body.classList.toggle('LightsOut', backgroundColor == 'rgb(0, 0, 0)')
  1054.  
  1055. if (lastBackgroundColor != null) {
  1056. log('Background setting changed - re-processing current page')
  1057. observePopups()
  1058. processCurrentPage()
  1059. }
  1060. lastBackgroundColor = backgroundColor
  1061. }, '<body> style attribute for backgroundColor', {
  1062. attributes: true,
  1063. attributeFilter: ['style']
  1064. })
  1065. }
  1066.  
  1067. /**
  1068. * When the "Color" setting is changed in "Customize your view", the app
  1069. * re-renders from a certain point, so we need to re-process the current page.
  1070. */
  1071. async function observeColor() {
  1072. let $colorRerenderBoundary = await getElement('#react-root > div > div')
  1073.  
  1074. observeElement($colorRerenderBoundary, async () => {
  1075. if (location.pathname != PagePaths.CUSTOMIZE_YOUR_VIEW) return
  1076.  
  1077. let $doneButton = await getElement(desktop ? Selectors.DISPLAY_DONE_BUTTON_DESKTOP : Selectors.DISPLAY_DONE_BUTTON_MOBILE, {
  1078. name: 'Done button',
  1079. stopIf: not(() => location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW),
  1080. })
  1081. if (!$doneButton) return
  1082.  
  1083. let color = getComputedStyle($doneButton).backgroundColor
  1084. if (color == themeColor) return
  1085.  
  1086. log('Color setting changed - re-processing current page')
  1087. themeColor = color
  1088. configureThemeCss()
  1089. observePopups()
  1090. processCurrentPage()
  1091. }, 'Color change re-render boundary')
  1092. }
  1093.  
  1094. /**
  1095. * When the "Font size" setting is changed in "Customize your view", `<html>`'s
  1096. * fontSize is changed and the app is re-rendered.
  1097. */
  1098. function observeHtmlFontSize() {
  1099. if (mobile) return
  1100.  
  1101. let lastOverflow = ''
  1102.  
  1103. observeElement($html, () => {
  1104. if (!$html.style.fontSize) return
  1105.  
  1106. let hasFontSizeChanged = fontSize != null && $html.style.fontSize != fontSize
  1107.  
  1108. if ($html.style.fontSize != fontSize) {
  1109. fontSize = $html.style.fontSize
  1110. log(`<html> fontSize has changed to ${fontSize}`)
  1111. configureNavFontSizeCss()
  1112. }
  1113.  
  1114. // Ignore overflow changes, which happen when a dialog is shown or hidden
  1115. let hasOverflowChanged = $html.style.overflow != lastOverflow
  1116. lastOverflow = $html.style.overflow
  1117. if (!hasFontSizeChanged && hasOverflowChanged) {
  1118. log('ignoring <html> style overflow change')
  1119. return
  1120. }
  1121.  
  1122. // When you switch between the smallest "Font size" options, <html>'s
  1123. // style is updated but the font size is kept the same - re-process just
  1124. // in case.
  1125. if (hasFontSizeChanged ||
  1126. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW && fontSize == '14px') {
  1127. log('<html> style attribute changed, re-processing current page')
  1128. observePopups()
  1129. processCurrentPage()
  1130. }
  1131. }, '<html> style attribute for fontSize', {
  1132. attributes: true,
  1133. attributeFilter: ['style']
  1134. })
  1135. }
  1136.  
  1137. /**
  1138. * Twitter displays popups in the #layers element. It also reuses open popups
  1139. * in certain cases rather than creating one from scratch, so we also need to
  1140. * deal with nested popups, e.g. if you hover over the caret menu in a Tweet, a
  1141. * popup will be created to display a "More" tootip and clicking to open the
  1142. * menu will create a nested element in the existing popup, whereas clicking the
  1143. * caret quickly without hovering over it will display the menu in new popup.
  1144. * Use of nested popups can also differ between desktop and mobile, so features
  1145. * need to be mindful of that.
  1146. */
  1147. const observePopups = (() => {
  1148. /** @type {MutationObserver} */
  1149. let popupObserver
  1150. /** @type {WeakMap<HTMLElement, {disconnect()}>} */
  1151. let nestedObservers = new WeakMap()
  1152.  
  1153. return async function observePopups() {
  1154. if (popupObserver) {
  1155. popupObserver.disconnect()
  1156. popupObserver = null
  1157. }
  1158.  
  1159. if (!(config.addAddMutedWordMenuItem ||
  1160. config.fastBlock ||
  1161. config.mutableQuoteTweets ||
  1162. config.twitterBlueChecks != 'ignore')) return
  1163.  
  1164. let $layers = await getElement('#layers', {
  1165. name: 'layers',
  1166. })
  1167.  
  1168. // There can be only one
  1169. if (popupObserver) {
  1170. popupObserver.disconnect()
  1171. }
  1172.  
  1173. popupObserver = observeElement($layers, (mutations) => {
  1174. mutations.forEach((mutation) => {
  1175. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1176. let nestedObserver = onPopup($el)
  1177. if (nestedObserver) {
  1178. nestedObservers.set($el, nestedObserver)
  1179. }
  1180. })
  1181. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1182. if (nestedObservers.has($el)) {
  1183. nestedObservers.get($el).disconnect()
  1184. nestedObservers.delete($el)
  1185. }
  1186. })
  1187. })
  1188. }, 'popup container')
  1189. }
  1190. })()
  1191.  
  1192. async function observeTitle() {
  1193. let $title = await getElement('title', {name: '<title>'})
  1194. observingTitle = true
  1195. observeElement($title, () => onTitleChange($title.textContent), '<title>')
  1196. }
  1197. //#endregion
  1198.  
  1199. //#region Page observers
  1200. /**
  1201. * If a profile is blocked its media box won't appear, add a `Blocked` class to
  1202. * `<body>` to hide sidebar content.
  1203. * @param {string} currentPage
  1204. */
  1205. async function observeProfileBlockedStatus(currentPage) {
  1206. let $buttonContainer = await getElement(`[data-testid="userActions"] ~ [data-testid="placementTracking"], a[href="${PagePaths.PROFILE_SETTINGS}"]`, {
  1207. name: 'Follow / Unblock button container or Edit profile button',
  1208. stopIf: pageIsNot(currentPage),
  1209. })
  1210. if ($buttonContainer == null) return
  1211.  
  1212. if ($buttonContainer.hasAttribute('href')) {
  1213. log('on own profile page')
  1214. $body.classList.remove('Blocked')
  1215. return
  1216. }
  1217.  
  1218. pageObservers.push(
  1219. observeElement($buttonContainer, () => {
  1220. let isBlocked = (/** @type {HTMLElement} */ ($buttonContainer.querySelector('[role="button"]'))?.dataset.testid ?? '').endsWith('unblock')
  1221. $body.classList.toggle('Blocked', isBlocked)
  1222. }, 'Follow / Unblock button container')
  1223. )
  1224. }
  1225.  
  1226. /**
  1227. * If an account has never tweeted any media, add a `NoMedia` class to `<body>`
  1228. * to hide the "You might like" section which will appear where the media box
  1229. * would have been.
  1230. * @param {string} currentPage
  1231. */
  1232. async function observeProfileSidebar(currentPage) {
  1233. let $sidebarContent = await getElement(Selectors.SIDEBAR_WRAPPERS, {
  1234. name: 'profile sidebar content container',
  1235. stopIf: pageIsNot(currentPage),
  1236. })
  1237. if ($sidebarContent == null) return
  1238.  
  1239. let sidebarContentObserver = observeElement($sidebarContent, () => {
  1240. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1241. }, 'profile sidebar content container')
  1242. pageObservers.push(sidebarContentObserver)
  1243.  
  1244. // On initial appearance, the sidebar is injected with static HTML with
  1245. // spinner placeholders, which gets replaced. When this happens we need to
  1246. // observe the new content container instead.
  1247. let $sidebarContentParent = $sidebarContent.parentElement
  1248. pageObservers.push(
  1249. observeElement($sidebarContentParent, (mutations) => {
  1250. let sidebarContentReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($sidebarContent))
  1251. if (sidebarContentReplaced) {
  1252. log('profile sidebar content container replaced, observing new container')
  1253. sidebarContentObserver.disconnect()
  1254. pageObservers.splice(pageObservers.indexOf(sidebarContentObserver), 1)
  1255. $sidebarContent = /** @type {HTMLElement} */ ($sidebarContentParent.firstElementChild)
  1256. pageObservers.push(
  1257. observeElement($sidebarContent, () => {
  1258. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1259. }, 'sidebar content container')
  1260. )
  1261. }
  1262. }, 'sidebar content container parent')
  1263. )
  1264. }
  1265.  
  1266. async function observeSidebar() {
  1267. let $primaryColumn = await getElement(Selectors.PRIMARY_COLUMN, {
  1268. name: 'primary column'
  1269. })
  1270. let $sidebarContainer = $primaryColumn.parentElement
  1271. pageObservers.push(
  1272. observeElement($sidebarContainer, () => {
  1273. let $sidebar = $sidebarContainer.querySelector(Selectors.SIDEBAR)
  1274. log(`sidebar ${$sidebar ? 'appeared' : 'disappeared'}`)
  1275. $body.classList.toggle('Sidebar', Boolean($sidebar))
  1276. if ($sidebar && config.twitterBlueChecks != 'ignore') {
  1277. observeSearchForm()
  1278. }
  1279. }, 'sidebar container')
  1280. )
  1281. }
  1282.  
  1283. async function observeSearchForm() {
  1284. let $searchForm = await getElement('form[role="search"]', {
  1285. name: 'search form',
  1286. stopIf: pageIsNot(currentPage),
  1287. // The sidebar on Profile pages can be really slow
  1288. timeout: 2000,
  1289. })
  1290. if (!$searchForm) return
  1291. let $results = /** @type {HTMLElement} */ ($searchForm.lastElementChild)
  1292. pageObservers.push(
  1293. observeElement($results, () => {
  1294. tagTwitterBlueCheckmarks($results)
  1295. }, 'search results', {childList: true, subtree: true})
  1296. )
  1297. }
  1298.  
  1299. /**
  1300. * @param {string} page
  1301. */
  1302. async function observeTimeline(page) {
  1303. let $timeline = await getElement(Selectors.TIMELINE, {
  1304. name: 'initial timeline',
  1305. stopIf: pageIsNot(page),
  1306. })
  1307.  
  1308. if ($timeline == null) return
  1309.  
  1310. // The inital timeline element is a placeholder without a style attribute
  1311. if ($timeline.hasAttribute('style')) {
  1312. pageObservers.push(
  1313. observeElement($timeline, () => onTimelineChange($timeline, page), 'timeline')
  1314. )
  1315. }
  1316. else {
  1317. log('waiting for timeline')
  1318. let startTime = Date.now()
  1319. pageObservers.push(
  1320. observeElement($timeline.parentNode, (mutations) => {
  1321. mutations.forEach((mutation) => {
  1322. mutation.addedNodes.forEach(($timeline) => {
  1323. if (Date.now() > startTime) {
  1324. log(`timeline appeared after ${Date.now() - startTime}ms`)
  1325. }
  1326. pageObservers.push(
  1327. observeElement($timeline, () => onTimelineChange($timeline, page), 'timeline')
  1328. )
  1329. })
  1330. })
  1331. }, 'timeline parent')
  1332. )
  1333. }
  1334. }
  1335. //#endregion
  1336.  
  1337. //#region Tweak functions
  1338. /**
  1339. * Add an "Add muted word" menu item after "Settings and privacy" which takes
  1340. * you straight to entering a new muted word (by clicking its way through all
  1341. * the individual screens!).
  1342. * @param {HTMLElement} $circleLink
  1343. */
  1344. async function addAddMutedWordMenuItem($circleLink) {
  1345. log('adding "Add muted word" menu item')
  1346.  
  1347. // Wait for the dropdown to appear on desktop
  1348. if (desktop) {
  1349. $circleLink = await getElement('#layers div[data-testid="Dropdown"] a[href$="/i/circles"]', {
  1350. name: 'rendered Twitter Circle menu item',
  1351. timeout: 100,
  1352. })
  1353. if (!$circleLink) return
  1354. }
  1355.  
  1356. let $addMutedWord = /** @type {HTMLElement} */ ($circleLink.parentElement.cloneNode(true))
  1357. $addMutedWord.classList.add('tnt_menu_item')
  1358. $addMutedWord.querySelector('a').href = PagePaths.ADD_MUTED_WORD
  1359. $addMutedWord.querySelector('span').textContent = getString('ADD_MUTED_WORD')
  1360. $addMutedWord.querySelector('svg').innerHTML = Svgs.MUTE
  1361. $addMutedWord.addEventListener('click', (e) => {
  1362. e.preventDefault()
  1363. addMutedWord()
  1364. })
  1365. $circleLink.parentElement.insertAdjacentElement('afterend', $addMutedWord)
  1366. }
  1367.  
  1368. function addCaretMenuListenerForQuoteTweet($tweet) {
  1369. let $caret = /** @type {HTMLElement} */ ($tweet.querySelector('[data-testid="caret"]'))
  1370. if ($caret && !$caret.dataset.tweakNewTwitterListener) {
  1371. $caret.addEventListener('click', () => {
  1372. quotedTweet = getQuotedTweetDetails($tweet)
  1373. })
  1374. $caret.dataset.tweakNewTwitterListener = 'true'
  1375. }
  1376. }
  1377.  
  1378. /**
  1379. * Add a "Mute this conversation" menu item to a Quote Tweet's menu.
  1380. * @param {HTMLElement} $blockMenuItem
  1381. */
  1382. async function addMuteQuotesMenuItem($blockMenuItem) {
  1383. log('adding "Mute this conversation" menu item')
  1384.  
  1385. // Wait for the menu to render properly on desktop
  1386. if (desktop) {
  1387. $blockMenuItem = await getElement(`:scope > div > div > div > ${Selectors.BLOCK_MENU_ITEM}`, {
  1388. context: $blockMenuItem.parentElement,
  1389. name: 'rendered block menu item',
  1390. timeout: 100,
  1391. })
  1392. if (!$blockMenuItem) return
  1393. }
  1394.  
  1395. let $muteQuotes = /** @type {HTMLElement} */ ($blockMenuItem.previousElementSibling.cloneNode(true))
  1396. $muteQuotes.classList.add('tnt_menu_item')
  1397. $muteQuotes.querySelector('span').textContent = getString('MUTE_THIS_CONVERSATION')
  1398. $muteQuotes.addEventListener('click', (e) => {
  1399. e.preventDefault()
  1400. log('muting quotes of a tweet', quotedTweet)
  1401. config.mutedQuotes = config.mutedQuotes.concat(quotedTweet)
  1402. storeConfigChanges({mutedQuotes: config.mutedQuotes})
  1403. processCurrentPage()
  1404. // Dismiss the menu
  1405. let $menuLayer = /** @type {HTMLElement} */ ($blockMenuItem.closest('[role="group"]')?.firstElementChild)
  1406. if (!$menuLayer) {
  1407. log('could not find menu layer to dismiss menu')
  1408. }
  1409. $menuLayer?.click()
  1410. })
  1411.  
  1412. $blockMenuItem.insertAdjacentElement('beforebegin', $muteQuotes)
  1413. }
  1414.  
  1415. async function addMutedWord() {
  1416. if (!document.querySelector('a[href="/settings')) {
  1417. let $settingsAndSupport = /** @type {HTMLElement} */ (document.querySelector('[data-testid="settingsAndSupport"]'))
  1418. $settingsAndSupport?.click()
  1419. }
  1420.  
  1421. for (let path of [
  1422. '/settings',
  1423. '/settings/privacy_and_safety',
  1424. '/settings/mute_and_block',
  1425. '/settings/muted_keywords',
  1426. '/settings/add_muted_keyword',
  1427. ]) {
  1428. let $link = await getElement(`a[href="${path}"]`, {timeout: 500})
  1429. if (!$link) return
  1430. $link.click()
  1431. }
  1432. let $input = await getElement('input[name="keyword"]')
  1433. setTimeout(() => $input.focus(), 100)
  1434. }
  1435.  
  1436. /**
  1437. * @param {string} page
  1438. */
  1439. async function addSeparatedTweetsTimelineControl(page) {
  1440. if (desktop) {
  1441. let $timelineTitle = await getElement('main h2', {
  1442. name: 'timeline title',
  1443. stopIf: pageIsNot(page),
  1444. })
  1445.  
  1446. if ($timelineTitle == null) return
  1447.  
  1448. let $newHeading = document.querySelector('#tnt_separated_tweets')
  1449. if ($newHeading) {
  1450. log('separated tweets timeline heading already present')
  1451. $newHeading.querySelector('span').textContent = separatedTweetsTimelineTitle
  1452. return
  1453. }
  1454.  
  1455. log('inserting separated tweets timeline heading')
  1456. $newHeading = /** @type {HTMLElement} */ ($timelineTitle.parentElement.cloneNode(true))
  1457. $newHeading.querySelector('h2').id = 'tnt_separated_tweets'
  1458. $newHeading.querySelector('span').textContent = separatedTweetsTimelineTitle
  1459.  
  1460. // This script assumes navigation has occurred when the document title
  1461. // changes, so by changing the title we fake navigation to a non-existent
  1462. // page representing the separated tweets timeline.
  1463. $newHeading.addEventListener('click', () => {
  1464. if (!document.title.startsWith(separatedTweetsTimelineTitle)) {
  1465. setTitle(separatedTweetsTimelineTitle)
  1466. }
  1467. window.scrollTo({top: 0})
  1468. })
  1469. $timelineTitle.parentElement.parentElement.insertAdjacentElement('afterend', $newHeading)
  1470.  
  1471. // Return to the main timeline when Latest Tweets / Home heading is clicked
  1472. $timelineTitle.parentElement.addEventListener('click', () => {
  1473. if (!document.title.startsWith(currentMainTimelineType)) {
  1474. homeNavigationIsBeingUsed = true
  1475. setTitle(currentMainTimelineType)
  1476. }
  1477. })
  1478.  
  1479. // Return to the main timeline when the Home nav link is clicked
  1480. let $homeNavLink = /** @type {HTMLElement} */ (document.querySelector(Selectors.NAV_HOME_LINK))
  1481. if (!$homeNavLink.dataset.tweakNewTwitterListener) {
  1482. $homeNavLink.addEventListener('click', () => {
  1483. homeNavigationIsBeingUsed = true
  1484. if (location.pathname == '/home' && !document.title.startsWith(currentMainTimelineType)) {
  1485. setTitle(currentMainTimelineType)
  1486. }
  1487. })
  1488. $homeNavLink.dataset.tweakNewTwitterListener = 'true'
  1489. }
  1490. }
  1491.  
  1492. if (mobile) {
  1493. let $toggle = document.createElement('div')
  1494. $toggle.id = 'tnt_switch_timeline'
  1495. let toggleColor = getComputedStyle(document.querySelector(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/home"] svg`)).color
  1496. $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;">
  1497. ${page == separatedTweetsTimelineTitle ? Svgs.HOME : Svgs.RETWEET}
  1498. </svg></span>`
  1499. let $span = /** @type {HTMLSpanElement} */ ($toggle.firstElementChild)
  1500. $span.title = `Switch to ${page == currentMainTimelineType ? separatedTweetsTimelineTitle : currentMainTimelineType}`
  1501. $span.addEventListener('click', () => {
  1502. let newTitle = page == separatedTweetsTimelineTitle ? currentMainTimelineType : separatedTweetsTimelineTitle
  1503. setTitle(newTitle)
  1504. $span.title = `Switch to ${newTitle == currentMainTimelineType ? separatedTweetsTimelineTitle : currentMainTimelineType}`
  1505. window.scrollTo({top: 0})
  1506. })
  1507.  
  1508. let $timelineTitle = document.querySelector(`
  1509. ${Selectors.MOBILE_TIMELINE_HEADER_OLD} h2,
  1510. ${Selectors.MOBILE_TIMELINE_HEADER_NEW} h2
  1511. `)
  1512.  
  1513. // Only the non-tabbed timeline has a heading in the header
  1514. if ($timelineTitle != null) {
  1515. // We hide the existing timeline title via CSS when it's not wanted instead
  1516. // of changing its text, as those changes persist when you view a tweet.
  1517. $timelineTitle.classList.add('tnt_home_timeline_title')
  1518. removeMobileTimelineHeaderElements()
  1519.  
  1520. log('inserting separated tweets timeline switcher in timeline title')
  1521. $timelineTitle.insertAdjacentElement('afterend', $toggle)
  1522.  
  1523. if (page == separatedTweetsTimelineTitle) {
  1524. let $sharedTweetsTitle = /** @type {HTMLElement} */ ($timelineTitle.cloneNode(true))
  1525. $sharedTweetsTitle.querySelector('span').textContent = separatedTweetsTimelineTitle
  1526. $sharedTweetsTitle.id = 'tnt_shared_tweets_timeline_title'
  1527. $sharedTweetsTitle.classList.remove('tnt_home_timeline_title')
  1528. $timelineTitle.insertAdjacentElement('afterend', $sharedTweetsTitle)
  1529. }
  1530. $timelineTitle.parentElement.classList.add('tnt_mobile_header')
  1531. }
  1532. else {
  1533. let $headerContent = document.querySelector(`${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div > div > div > div > div`)
  1534. if ($headerContent != null) {
  1535. if (config.alwaysUseLatestTweets) {
  1536. // This element reserves space for the timeline tabs - resize it for
  1537. // the header's contents, as the tabs are going to be hidden.
  1538. let $headerSizer = /** @type {HTMLDivElement} */ (document.querySelector(`${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div`))
  1539. if ($headerSizer) {
  1540. $headerSizer.style.height = getComputedStyle($headerContent).height
  1541. }
  1542. }
  1543.  
  1544. removeMobileTimelineHeaderElements()
  1545.  
  1546. log('inserting separated tweets timeline switcher in header')
  1547. $headerContent.appendChild($toggle)
  1548. }
  1549. else {
  1550. warn('could not find header content element')
  1551. }
  1552. }
  1553.  
  1554. // Go back to the main timeline when the Home bottom nav link is clicked on
  1555. // the shared tweets timeline.
  1556. let $homeBottomNavItem = /** @type {HTMLElement} */ (document.querySelector(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/home"]`))
  1557. if (!$homeBottomNavItem.dataset.tweakNewTwitterListener) {
  1558. $homeBottomNavItem.addEventListener('click', () => {
  1559. if (location.pathname == '/home' && currentPage == separatedTweetsTimelineTitle) {
  1560. setTitle(currentMainTimelineType)
  1561. }
  1562. })
  1563. $homeBottomNavItem.dataset.tweakNewTwitterListener = 'true'
  1564. }
  1565. }
  1566. }
  1567.  
  1568. /**
  1569. * Redirects away from the home timeline if we're on it and it's been disabled.
  1570. * @returns {boolean} `true` if redirected as a result of this call
  1571. */
  1572. function checkforDisabledHomeTimeline() {
  1573. if (config.disableHomeTimeline && location.pathname == '/home') {
  1574. log(`home timeline disabled, redirecting to /${config.disabledHomeTimelineRedirect}`)
  1575. let primaryNavSelector = desktop ? Selectors.PRIMARY_NAV_DESKTOP : Selectors.PRIMARY_NAV_MOBILE
  1576. ;/** @type {HTMLElement} */ (
  1577. document.querySelector(`${primaryNavSelector} a[href="/${config.disabledHomeTimelineRedirect}"]`)
  1578. ).click()
  1579. return true
  1580. }
  1581. }
  1582.  
  1583. const configureCss = (() => {
  1584. let $style = addStyle('features')
  1585.  
  1586. return function configureCss() {
  1587. let cssRules = []
  1588. let hideCssSelectors = []
  1589. let menuRole = `[role="${desktop ? 'menu' : 'dialog'}"]`
  1590.  
  1591. if (config.alwaysUseLatestTweets) {
  1592. // Hide the sparkle when automatically staying on Latest Tweets
  1593. hideCssSelectors.push(mobile
  1594. ? [`body.MainTimeline ${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div > div > div > div > div > div:nth-of-type(3)`,
  1595. `body.MainTimeline ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:first-of-type > div > div > div > div > div:nth-of-type(3)`,
  1596. ].join(', ')
  1597. : [`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)`,
  1598. `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)`,
  1599. ].join(', ')
  1600. )
  1601. // Hide timeline tabs
  1602. hideCssSelectors.push(mobile
  1603. ? `body.TimelineTabs ${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div:nth-of-type(2)`
  1604. : `body.TimelineTabs ${Selectors.DESKTOP_TIMELINE_HEADER} > div:nth-of-type(2):not(:last-child)`
  1605. )
  1606. }
  1607. if (config.hideAnalyticsNav) {
  1608. hideCssSelectors.push(`${menuRole} a[href*="analytics.twitter.com"]`)
  1609. }
  1610. if (config.hideBookmarksNav) {
  1611. hideCssSelectors.push(`${menuRole} a[href$="/bookmarks"]`)
  1612. }
  1613. if (config.hideTwitterCircleNav) {
  1614. hideCssSelectors.push(`${menuRole} a[href$="/i/circles"]`)
  1615. }
  1616. if (config.hideShareTweetButton) {
  1617. hideCssSelectors.push(
  1618. // Under timeline-style tweets
  1619. '[data-testid="tweet"] [role="group"] > div:nth-of-type(4)',
  1620. // Under individual tweets
  1621. 'body.Tweet [data-testid="tweet"] + div > div > [role="group"] > div:nth-of-type(4)',
  1622. // In media modal
  1623. '[aria-modal="true"] [role="group"] > div:nth-of-type(4)',
  1624. )
  1625. }
  1626. if (config.hideHelpCenterNav) {
  1627. hideCssSelectors.push(`${menuRole} a[href*="support.twitter.com"]`)
  1628. }
  1629. if (config.hideListsNav) {
  1630. hideCssSelectors.push(`${menuRole} a[href$="/lists"]`)
  1631. }
  1632. if (config.hideMetrics) {
  1633. configureHideMetricsCss(cssRules, hideCssSelectors)
  1634. }
  1635. if (config.hideMomentsNav) {
  1636. hideCssSelectors.push(`${menuRole} a[href$="/moment_maker"]`)
  1637. }
  1638. if (config.hideMonetizationNav) {
  1639. hideCssSelectors.push(`${menuRole} a[href$="/settings/monetization"]`)
  1640. }
  1641. if (config.hideNewslettersNav) {
  1642. hideCssSelectors.push(`${menuRole} a[href$="/newsletters"]`)
  1643. }
  1644. if (config.hideTopicsNav) {
  1645. hideCssSelectors.push(`${menuRole} a[href$="/topics"]`)
  1646. }
  1647. if (config.hideTweetAnalyticsLinks) {
  1648. hideCssSelectors.push(
  1649. // Under timeline-style tweets
  1650. '[data-testid="tweet"] [role="group"] > div:nth-of-type(5)',
  1651. // Under individual tweets
  1652. '[data-testid="analyticsButton"]',
  1653. )
  1654. }
  1655. if (config.hideTwitterAdsNav) {
  1656. hideCssSelectors.push(`${menuRole} a[href*="ads.twitter.com"]`)
  1657. }
  1658. if (config.hideTwitterBlueNav) {
  1659. hideCssSelectors.push(`${menuRole} a[href$="/twitter_blue_sign_up"]`)
  1660. }
  1661. if (config.hideTwitterForProfessionalsNav) {
  1662. hideCssSelectors.push(`${menuRole} a[href$="/convert_to_professional"]`)
  1663. }
  1664. if (config.hideVerifiedNotificationsTab) {
  1665. hideCssSelectors.push('body.Notifications [data-testid="ScrollSnap-List"] > div:nth-child(2)')
  1666. }
  1667. if (config.hideWhoToFollowEtc) {
  1668. hideCssSelectors.push(`body.Profile ${Selectors.PRIMARY_COLUMN} aside[role="complementary"]`)
  1669. }
  1670. if (config.reducedInteractionMode) {
  1671. hideCssSelectors.push(
  1672. '[data-testid="tweet"] [role="group"]',
  1673. 'body.Tweet a:is([href$="/retweets"], [href$="/likes"])',
  1674. 'body.Tweet [data-testid="tweet"] + div > div [role="group"]',
  1675. )
  1676. }
  1677. if (config.tweakQuoteTweetsPage) {
  1678. // Hide the quoted tweet, which is repeated in every quote tweet
  1679. hideCssSelectors.push('body.QuoteTweets [data-testid="tweet"] [aria-labelledby] > div:last-child')
  1680. }
  1681. if (config.twitterBlueChecks == 'hide') {
  1682. hideCssSelectors.push('.tnt_blue_check')
  1683. }
  1684. if (config.twitterBlueChecks == 'dim') {
  1685. cssRules.push(`
  1686. .tnt_blue_check path { opacity: .75; }
  1687. body.Default .tnt_blue_check path { color: rgb(83, 100, 113) !important; }
  1688. body.Dim .tnt_blue_check path { color: rgb(139, 152, 165) !important; }
  1689. body.LightsOut .tnt_blue_check path { color: rgb(113, 118, 123) !important; }
  1690. `)
  1691. }
  1692.  
  1693. // Hide "Creator Studio" if all its contents are hidden
  1694. if (config.hideMomentsNav && config.hideNewslettersNav && config.hideAnalyticsNav) {
  1695. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(1)`)
  1696. }
  1697. // Hide "Professional Tools" if all its contents are hidden
  1698. if (config.hideTwitterForProfessionalsNav && config.hideTwitterAdsNav && config.hideMonetizationNav) {
  1699. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(2)`)
  1700. }
  1701.  
  1702. if (desktop) {
  1703. if (config.disableHomeTimeline) {
  1704. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/home"]`)
  1705. }
  1706. if (config.fullWidthContent) {
  1707. // Pseudo-selector for pages full-width is enabled on
  1708. let pageSelector = ':is(.List, .MainTimeline)'
  1709. cssRules.push(`
  1710. /* Use full width when the sidebar is visible */
  1711. body.Sidebar${pageSelector} ${Selectors.PRIMARY_COLUMN},
  1712. body.Sidebar${pageSelector} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  1713. max-width: 990px;
  1714. }
  1715. /* Make the "What's happening" input keep its original width */
  1716. body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div:first-child > div:nth-of-type(2) div[role="progressbar"] + div {
  1717. max-width: 598px;
  1718. }
  1719. /* Use full width when the sidebar is not visible */
  1720. body:not(.Sidebar)${pageSelector} header[role="banner"] {
  1721. flex-grow: 0;
  1722. }
  1723. body:not(.Sidebar)${pageSelector} main[role="main"] > div {
  1724. width: 100%;
  1725. }
  1726. body:not(.Sidebar)${pageSelector} ${Selectors.PRIMARY_COLUMN} {
  1727. max-width: unset;
  1728. width: 100%;
  1729. }
  1730. body:not(.Sidebar)${pageSelector} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:first-child div,
  1731. body:not(.Sidebar)${pageSelector} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  1732. max-width: unset;
  1733. }
  1734. `)
  1735. if (!config.fullWidthMedia) {
  1736. // Make media & cards keep their original width
  1737. cssRules.push(`
  1738. 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) {
  1739. max-width: 504px;
  1740. }
  1741. `)
  1742. }
  1743. // Hide the sidebar when present
  1744. hideCssSelectors.push(`body.Sidebar${pageSelector} ${Selectors.SIDEBAR}`)
  1745. }
  1746. if (config.hideAccountSwitcher) {
  1747. cssRules.push(`
  1748. header[role="banner"] > div > div > div > div:last-child {
  1749. flex-shrink: 1 !important;
  1750. align-items: flex-end !important;
  1751. }
  1752. `)
  1753. hideCssSelectors.push(
  1754. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child:not(:only-child)',
  1755. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child + div',
  1756. )
  1757. }
  1758. if (config.hideCommunitiesNav) {
  1759. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/communities"]`)
  1760. }
  1761. if (config.addAddMutedWordMenuItem || config.mutableQuoteTweets) {
  1762. // Hover colors for custom menu items
  1763. cssRules.push(`
  1764. body.Default .tnt_menu_item:hover a { background-color: rgb(247, 249, 249) !important; }
  1765. body.Dim .tnt_menu_item:hover a { background-color: rgb(30, 39, 50) !important; }
  1766. body.LightsOut .tnt_menu_item:hover a { background-color: rgb(22, 24, 28) !important; }
  1767. `)
  1768. }
  1769. if (config.hideExplorePageContents) {
  1770. hideCssSelectors.push(
  1771. // Tabs
  1772. `body.Explore ${Selectors.DESKTOP_TIMELINE_HEADER} nav`,
  1773. // Content
  1774. `body.Explore ${Selectors.TIMELINE}`,
  1775. )
  1776. }
  1777. if (config.hideKeyboardShortcutsNav) {
  1778. hideCssSelectors.push(`${menuRole} a[href$="/i/keyboard_shortcuts"]`)
  1779. }
  1780. if (config.hideSidebarContent) {
  1781. // Only show the first sidebar item by default
  1782. // Re-show subsequent non-algorithmic sections on specific pages
  1783. cssRules.push(`
  1784. ${Selectors.SIDEBAR_WRAPPERS} > div:not(:first-of-type) {
  1785. display: none;
  1786. }
  1787. body.Profile:not(.Blocked, .NoMedia) ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  1788. display: block;
  1789. }
  1790. `)
  1791. if (config.showRelevantPeople) {
  1792. cssRules.push(`
  1793. body.Tweet ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  1794. display: block;
  1795. }
  1796. `)
  1797. }
  1798. hideCssSelectors.push(`body.HideSidebar ${Selectors.SIDEBAR}`)
  1799. }
  1800. if (config.hideExploreNav) {
  1801. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/explore"]`)
  1802. }
  1803. if (config.hideBookmarksNav) {
  1804. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/i/bookmarks"]`)
  1805. }
  1806. if (config.hideMessagesDrawer) {
  1807. cssRules.push(`${Selectors.MESSAGES_DRAWER} { visibility: hidden; }`)
  1808. }
  1809. if (config.retweets != 'separate' && config.quoteTweets != 'separate') {
  1810. hideCssSelectors.push('#tnt_separated_tweets')
  1811. }
  1812. }
  1813.  
  1814. if (mobile) {
  1815. if (config.disableHomeTimeline) {
  1816. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/home"]`)
  1817. }
  1818. if (config.hideAppNags) {
  1819. cssRules.push(`
  1820. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_OLD} div:nth-of-type(3) > div > [role="button"],
  1821. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_NEW} div:nth-of-type(3) > div > [role="button"] {
  1822. visibility: hidden;
  1823. }
  1824. `)
  1825. hideCssSelectors.push('.HideAppNags #layers > div')
  1826. }
  1827. if (config.hideExplorePageContents) {
  1828. // Hide explore page contents so we don't get a brief flash of them
  1829. // before automatically switching the page to search mode.
  1830. hideCssSelectors.push(
  1831. // Tabs
  1832. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div:nth-of-type(2)`,
  1833. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div:nth-of-type(2)`,
  1834. // Content
  1835. `body.Explore ${Selectors.TIMELINE}`,
  1836. )
  1837. }
  1838. if (config.hideCommunitiesNav) {
  1839. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href$="/communities"]`)
  1840. }
  1841. if (config.hideMessagesBottomNavItem) {
  1842. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/messages"]`)
  1843. }
  1844. if (config.retweets == 'separate' || config.quoteTweets == 'separate') {
  1845. // Use CSS to tweak layout of mobile header elements on pages where it's
  1846. // needed, as changes made directly to them can persist across pages.
  1847. cssRules.push(`
  1848. body.Home .tnt_mobile_header,
  1849. body.LatestTweets .tnt_mobile_header,
  1850. body.SeparatedTweets .tnt_mobile_header {
  1851. flex-direction: row;
  1852. align-items: center;
  1853. justify-content: space-between;
  1854. }
  1855. `)
  1856. hideCssSelectors.push('body.SeparatedTweets .tnt_home_timeline_title')
  1857. cssRules.push(`
  1858. #tnt_switch_timeline span {
  1859. cursor: pointer;
  1860. }
  1861. body.TimelineTabs #tnt_switch_timeline {
  1862. align-items: end;
  1863. align-self: stretch;
  1864. display: flex;
  1865. flex-basis: 50%;
  1866. flex-direction: column;
  1867. justify-content: center;
  1868. }
  1869. `)
  1870. }
  1871. }
  1872.  
  1873. if (hideCssSelectors.length > 0) {
  1874. cssRules.push(`
  1875. ${hideCssSelectors.join(',\n')} {
  1876. display: none !important;
  1877. }
  1878. `)
  1879. }
  1880.  
  1881. $style.textContent = cssRules.map(dedent).join('\n')
  1882. }
  1883. })()
  1884.  
  1885. function configureFont() {
  1886. if (!fontFamilyRule) {
  1887. warn('no fontFamilyRule found for configureFont to use')
  1888. return
  1889. }
  1890.  
  1891. if (config.dontUseChirpFont) {
  1892. if (fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  1893. fontFamilyRule.style.fontFamily = fontFamilyRule.style.fontFamily.replace(/"?TwitterChirp"?, ?/, '')
  1894. log('disabled Chirp font')
  1895. }
  1896. } else if (!fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  1897. fontFamilyRule.style.fontFamily = `"TwitterChirp", ${fontFamilyRule.style.fontFamily}`
  1898. log(`enabled Chirp font`)
  1899. }
  1900. }
  1901.  
  1902. /**
  1903. * @param {string[]} cssRules
  1904. * @param {string[]} hideCssSelectors
  1905. */
  1906. function configureHideMetricsCss(cssRules, hideCssSelectors) {
  1907. if (config.hideFollowingMetrics) {
  1908. // User profile hover card and page metrics
  1909. hideCssSelectors.push(
  1910. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) > :first-child'
  1911. )
  1912. // Fix display of whitespace after hidden metrics
  1913. cssRules.push(
  1914. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) { white-space: pre-line; }'
  1915. )
  1916. }
  1917.  
  1918. if (config.hideTotalTweetsMetrics) {
  1919. // Tweet count under username header on profile pages
  1920. hideCssSelectors.push(
  1921. mobile ? `
  1922. body.Profile header > div > div:first-of-type h2 + div[dir="auto"],
  1923. body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:first-of-type h2 + div[dir="auto"]
  1924. ` : `body.Profile Selectors.PRIMARY_COLUMN > div > div:first-of-type h2 + div[dir="auto"]`
  1925. )
  1926. }
  1927.  
  1928. let individualTweetMetricSelectors = [
  1929. config.hideRetweetMetrics && '[href$="/retweets"]',
  1930. config.hideLikeMetrics && '[href$="/likes"]',
  1931. config.hideQuoteTweetMetrics && '[href$="/retweets/with_comments"]',
  1932. ].filter(Boolean).join(', ')
  1933.  
  1934. if (individualTweetMetricSelectors) {
  1935. // Individual tweet metrics
  1936. hideCssSelectors.push(
  1937. `body.Tweet a:is(${individualTweetMetricSelectors}) > :first-child`,
  1938. `[aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) > :first-child`
  1939. )
  1940. // Fix display of whitespace after hidden metrics
  1941. cssRules.push(
  1942. `body.Tweet a:is(${individualTweetMetricSelectors}), [aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) { white-space: pre-line; }`
  1943. )
  1944. }
  1945.  
  1946. let timelineMetricSelectors = [
  1947. config.hideReplyMetrics && ':nth-of-type(1)',
  1948. config.hideRetweetMetrics && ':nth-of-type(2)',
  1949. config.hideLikeMetrics && ':nth-of-type(3)',
  1950. ].filter(Boolean).join(', ')
  1951.  
  1952. if (timelineMetricSelectors) {
  1953. cssRules.push(
  1954. // Metrics under timeline-style tweets
  1955. `[data-testid="tweet"] [role="group"] > div:is(${timelineMetricSelectors}) div > span { visibility: hidden; }`,
  1956. // Metrics in media modal
  1957. `[aria-modal="true"] [role="group"] > div:is(${timelineMetricSelectors}) [data-testid="app-text-transition-container"] { visibility: hidden; }`,
  1958. )
  1959. }
  1960. }
  1961.  
  1962. const configureNavFontSizeCss = (() => {
  1963. let $style = addStyle('nav-font-size')
  1964.  
  1965. return function configureNavFontSizeCss() {
  1966. let cssRules = []
  1967.  
  1968. if (fontSize != null && config.navBaseFontSize) {
  1969. cssRules.push(`
  1970. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir="auto"] span { font-size: ${fontSize}; font-weight: normal; }
  1971. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir="auto"] { margin-top: -4px; }
  1972. `)
  1973. }
  1974.  
  1975. $style.textContent = cssRules.map(dedent).join('\n')
  1976. }
  1977. })()
  1978.  
  1979. /**
  1980. * Configures – or re-configures – the separated tweets timeline title.
  1981. *
  1982. * If we're currently on the separated tweets timeline and…
  1983. * - …its title has changed, the page title will be changed to "navigate" to it.
  1984. * - …the separated tweets timeline is no longer needed, we'll change the page
  1985. * title to "navigate" back to the main timeline.
  1986. *
  1987. * @returns {boolean} `true` if "navigation" was triggered by this call
  1988. */
  1989. function configureSeparatedTweetsTimelineTitle() {
  1990. let wasOnSeparatedTweetsTimeline = isOnSeparatedTweetsTimeline()
  1991. let previousTitle = separatedTweetsTimelineTitle
  1992.  
  1993. if (config.retweets == 'separate' && config.quoteTweets == 'separate') {
  1994. separatedTweetsTimelineTitle = getString('SHARED_TWEETS')
  1995. } else if (config.retweets == 'separate') {
  1996. separatedTweetsTimelineTitle = getString('RETWEETS')
  1997. } else if (config.quoteTweets == 'separate') {
  1998. separatedTweetsTimelineTitle = getString('QUOTE_TWEETS')
  1999. } else {
  2000. separatedTweetsTimelineTitle = null
  2001. }
  2002.  
  2003. let titleChanged = previousTitle != separatedTweetsTimelineTitle
  2004. if (wasOnSeparatedTweetsTimeline) {
  2005. if (separatedTweetsTimelineTitle == null) {
  2006. log('moving from separated tweets timeline to main timeline after config change')
  2007. setTitle(currentMainTimelineType)
  2008. return true
  2009. }
  2010. if (titleChanged) {
  2011. log('applying new separated tweets timeline title after config change')
  2012. setTitle(separatedTweetsTimelineTitle)
  2013. return true
  2014. }
  2015. } else {
  2016. if (titleChanged && previousTitle != null && lastMainTimelineTitle == previousTitle) {
  2017. log('updating lastMainTimelineTitle with new separated tweets timeline title')
  2018. lastMainTimelineTitle = separatedTweetsTimelineTitle
  2019. }
  2020. }
  2021. }
  2022.  
  2023. const configureThemeCss = (() => {
  2024. let $style = addStyle('theme')
  2025.  
  2026. return function configureThemeCss() {
  2027. let cssRules = []
  2028.  
  2029. if (debug) {
  2030. cssRules.push(`
  2031. [data-item-type]::after {
  2032. position: absolute;
  2033. top: 0;
  2034. right: 50px;
  2035. content: attr(data-item-type);
  2036. font-family: ${fontFamilyRule?.style.fontFamily || '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial'};
  2037. background-color: rgb(242, 29, 29);
  2038. color: white;
  2039. font-size: 11px;
  2040. font-weight: bold;
  2041. padding: 4px 6px;
  2042. border-bottom-left-radius: 1em;
  2043. border-bottom-right-radius: 1em;
  2044. }
  2045. `)
  2046. }
  2047.  
  2048. if (themeColor != null && desktop && (config.retweets == 'separate' || config.quoteTweets == 'separate')) {
  2049. cssRules.push(`
  2050. body.Home main h2:not(#tnt_separated_tweets),
  2051. body.LatestTweets main h2:not(#tnt_separated_tweets),
  2052. body.SeparatedTweets #tnt_separated_tweets {
  2053. color: ${themeColor};
  2054. }
  2055. `)
  2056. }
  2057.  
  2058. if (config.uninvertFollowButtons) {
  2059. // Shared styles for Following and Follow buttons
  2060. cssRules.push(`
  2061. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2062. border-color: rgba(0, 0, 0, 0) !important;
  2063. }
  2064. [role="button"][data-testid$="-follow"] {
  2065. background-color: rgba(0, 0, 0, 0) !important;
  2066. }
  2067. `)
  2068. if (config.followButtonStyle == 'monochrome' || themeColor == null) {
  2069. cssRules.push(`
  2070. /* Following button */
  2071. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2072. background-color: rgb(15, 20, 25) !important;
  2073. }
  2074. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) > * {
  2075. color: rgb(255, 255, 255) !important;
  2076. }
  2077. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2078. background-color: rgb(255, 255, 255) !important;
  2079. }
  2080. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) > * {
  2081. color: rgb(15, 20, 25) !important;
  2082. }
  2083. /* Follow button */
  2084. body.Default [role="button"][data-testid$="-follow"] {
  2085. border-color: rgb(207, 217, 222) !important;
  2086. }
  2087. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] {
  2088. border-color: rgb(83, 100, 113) !important;
  2089. }
  2090. body.Default [role="button"][data-testid$="-follow"] > * {
  2091. color: rgb(15, 20, 25) !important;
  2092. }
  2093. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] > * {
  2094. color: rgb(255, 255, 255) !important;
  2095. }
  2096. body.Default [role="button"][data-testid$="-follow"]:hover {
  2097. background-color: rgba(15, 20, 25, 0.1) !important;
  2098. }
  2099. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"]:hover {
  2100. background-color: rgba(255, 255, 255, 0.1) !important;
  2101. }
  2102. `)
  2103. }
  2104. if (config.followButtonStyle == 'themed' && themeColor != null) {
  2105. cssRules.push(`
  2106. /* Following button */
  2107. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2108. background-color: ${themeColor} !important;
  2109. }
  2110. [role="button"][data-testid$="-unfollow"]:not(:hover) > * {
  2111. color: rgb(255, 255, 255) !important;
  2112. }
  2113. /* Follow button */
  2114. [role="button"][data-testid$="-follow"] {
  2115. border-color: ${themeColor} !important;
  2116. }
  2117. [role="button"][data-testid$="-follow"] > * {
  2118. color: ${themeColor} !important;
  2119. }
  2120. [role="button"][data-testid$="-follow"]:hover {
  2121. background-color: ${themeColor} !important;
  2122. }
  2123. [role="button"][data-testid$="-follow"]:hover > * {
  2124. color: rgb(255, 255, 255) !important;
  2125. }
  2126. `)
  2127. }
  2128. }
  2129.  
  2130. $style.textContent = cssRules.map(dedent).join('\n')
  2131. }
  2132. })()
  2133.  
  2134. /**
  2135. * @param {HTMLElement} $tweet
  2136. * @returns {import("./types").QuotedTweet}
  2137. */
  2138. function getQuotedTweetDetails($tweet) {
  2139. let $quotedTweet = $tweet.querySelector('div[id^="id__"] > div[dir="auto"] > span').parentElement.nextElementSibling
  2140. let $heading = $quotedTweet?.querySelector(':scope > div > div:first-child')
  2141. let user = $heading?.querySelector('div:last-child > span')?.textContent
  2142. let time = $heading?.querySelector('time')?.dateTime
  2143. let text = $heading?.nextElementSibling?.querySelector('[lang]')?.textContent
  2144. return {user, time, text}
  2145. }
  2146.  
  2147. /**
  2148. * Attempts to determine the type of a timeline Tweet given the element with
  2149. * data-testid="tweet" on it, falling back to TWEET if it doesn't appear to be
  2150. * one of the particular types we care about.
  2151. * @param {HTMLElement} $tweet
  2152. * @returns {import("./types").TimelineItemType}
  2153. */
  2154. function getTweetType($tweet) {
  2155. if ($tweet.closest(Selectors.PROMOTED_TWEET_CONTAINER)) {
  2156. return 'PROMOTED_TWEET'
  2157. }
  2158. if ($tweet.querySelector('[data-testid="socialContext"]')) {
  2159. if (!config.alwaysUseLatestTweets && currentMainTimelineType == getString('HOME')) {
  2160. let svgPath = $tweet.querySelector('svg path')?.getAttribute('d') ?? ''
  2161. if (svgPath.startsWith('M7.471 21H.472l.029-1.027c.')) return 'COMMUNITY_TWEET'
  2162. if (svgPath.startsWith('M17.863 13.44c1.477 1.58 2.')) return 'FOLLOWEES_FOLLOWS'
  2163. if (svgPath.startsWith('M20.884 13.19c-1.351 2.48-4')) return 'LIKED'
  2164. if (svgPath.startsWith('M1.751 10c0-4.42 3.584-8 8.')) return 'REPLIED'
  2165. if (svgPath.startsWith('M12 1.75c-5.11 0-9.25 4.14-')) return 'SUGGESTED_TOPIC_TWEET'
  2166. // This is the start of the SVG path for the Retweet icon
  2167. if (!svgPath.startsWith('M4.75 3.79l4.603 4.3-1.706 1')) {
  2168. warn('unhandled socialContext tweet type - falling back to RETWEET', $tweet)
  2169. }
  2170. }
  2171. // Quoted tweets from accounts you blocked or muted are displayed as an
  2172. // <article> with "This Tweet is unavailable."
  2173. if ($tweet.querySelector('article')) {
  2174. return 'UNAVAILABLE_RETWEET'
  2175. }
  2176. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2177. if ($tweet.querySelector('div[id^="id__"] > div[dir="auto"] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2178. return 'RETWEETED_QUOTE_TWEET'
  2179. }
  2180. return 'RETWEET'
  2181. }
  2182. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2183. if ($tweet.querySelector('div[id^="id__"] > div[dir="auto"] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2184. return 'QUOTE_TWEET'
  2185. }
  2186. // Quoted tweets from accounts you blocked or muted are displayed as an
  2187. // <article> with "This Tweet is unavailable."
  2188. if ($tweet.querySelector('article')) {
  2189. return 'UNAVAILABLE_QUOTE_TWEET'
  2190. }
  2191. return 'TWEET'
  2192. }
  2193.  
  2194. // Add 1 every time this gets broken: 2
  2195. function getVerifiedProps($svg) {
  2196. let $parent = $svg.parentElement
  2197. // Verified badge button on the profile screen
  2198. if ($parent.getAttribute('role') == 'button') {
  2199. $parent = $parent.closest('span')
  2200. }
  2201. if ($parent.wrappedJSObject) {
  2202. $parent = $parent.wrappedJSObject
  2203. }
  2204. let reactPropsKey = Object.keys($parent).find(key => key.startsWith('__reactProps$'))
  2205. let props = $parent[reactPropsKey]?.children?.props?.children?.[0]?.[0]?.props
  2206. if (!props) {
  2207. warn('verified props not found for', $svg, {reactPropsKey})
  2208. }
  2209. return props
  2210. }
  2211.  
  2212. /**
  2213. * @param {HTMLElement} $popup
  2214. * @returns {{tookAction: boolean, onPopupClosed?: () => void}}
  2215. */
  2216. function handlePopup($popup) {
  2217. let result = {tookAction: false, onPopupClosed: null}
  2218.  
  2219. if (config.mutableQuoteTweets) {
  2220. if (quotedTweet) {
  2221. let $blockMenuItem = /** @type {HTMLElement} */ ($popup.querySelector(Selectors.BLOCK_MENU_ITEM))
  2222. if ($blockMenuItem) {
  2223. addMuteQuotesMenuItem($blockMenuItem)
  2224. result.tookAction = true
  2225. // Clear the quoted tweet when the popup closes
  2226. result.onPopupClosed = () => {
  2227. quotedTweet = null
  2228. }
  2229. } else {
  2230. quotedTweet = null
  2231. }
  2232. }
  2233. }
  2234.  
  2235. if (config.fastBlock) {
  2236. if (blockMenuItemSeen && $popup.querySelector('[data-testid="confirmationSheetConfirm"]')) {
  2237. log('fast blocking')
  2238. ;/** @type {HTMLElement} */ ($popup.querySelector('[data-testid="confirmationSheetConfirm"]')).click()
  2239. result.tookAction = true
  2240. }
  2241. else if ($popup.querySelector(Selectors.BLOCK_MENU_ITEM)) {
  2242. log('preparing for fast blocking')
  2243. blockMenuItemSeen = true
  2244. // Create a nested observer for mobile, as it reuses the popup element
  2245. result.tookAction = !mobile
  2246. } else {
  2247. blockMenuItemSeen = false
  2248. }
  2249. }
  2250.  
  2251. if (config.addAddMutedWordMenuItem) {
  2252. let $circleLink = /** @type {HTMLElement} */ ($popup.querySelector('a[href$="/i/circles"]'))
  2253. if ($circleLink) {
  2254. addAddMutedWordMenuItem($circleLink)
  2255. result.tookAction = true
  2256. }
  2257. }
  2258.  
  2259. if (config.twitterBlueChecks != 'ignore') {
  2260. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  2261. if ($hoverCard) {
  2262. result.tookAction = true
  2263. getElement('div[data-testid^="UserAvatar-Container"]', {
  2264. context: $hoverCard,
  2265. name: 'hovercard contents',
  2266. timeout: 250,
  2267. }).then(($contents) => {
  2268. if ($contents) tagTwitterBlueCheckmarks($popup)
  2269. })
  2270. }
  2271. }
  2272.  
  2273. return result
  2274. }
  2275.  
  2276. /**
  2277. * Checks if a tweet is preceded by an element creating a vertical reply line.
  2278. * @param {HTMLElement} $tweet
  2279. * @returns {boolean}
  2280. */
  2281. function isReplyToPreviousTweet($tweet) {
  2282. let $replyLine = $tweet.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild
  2283. if ($replyLine) {
  2284. return getComputedStyle($replyLine).width == '2px'
  2285. }
  2286. }
  2287.  
  2288. /**
  2289. * @returns {{disconnect()}}
  2290. */
  2291. function onPopup($popup) {
  2292. log('popup appeared', $popup)
  2293.  
  2294. // If handlePopup did something, we don't need to observe nested popups
  2295. let {tookAction, onPopupClosed} = handlePopup($popup)
  2296. if (tookAction) {
  2297. return onPopupClosed ? {disconnect: onPopupClosed} : null
  2298. }
  2299.  
  2300. /** @type {HTMLElement} */
  2301. let $nestedPopup
  2302.  
  2303. let nestedObserver = observeElement($popup, (mutations) => {
  2304. mutations.forEach((mutation) => {
  2305. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  2306. log('nested popup appeared', $el)
  2307. $nestedPopup = $el
  2308. ;({onPopupClosed} = handlePopup($el))
  2309. })
  2310. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  2311. if ($el !== $nestedPopup) return
  2312. if (onPopupClosed) {
  2313. log('cleaning up after nested popup removed')
  2314. onPopupClosed()
  2315. }
  2316. })
  2317. })
  2318. })
  2319.  
  2320. let disconnect = nestedObserver.disconnect.bind(nestedObserver)
  2321. nestedObserver.disconnect = () => {
  2322. if (onPopupClosed) {
  2323. log('cleaning up after nested popup observer disconnected')
  2324. onPopupClosed()
  2325. }
  2326. disconnect()
  2327. }
  2328.  
  2329. return nestedObserver
  2330. }
  2331.  
  2332. function onTimelineChange($timeline, page) {
  2333. log(`processing ${$timeline.children.length} timeline item${s($timeline.children.length)}`)
  2334.  
  2335. /** @type {HTMLElement} */
  2336. let $previousItem = null
  2337. /** @type {?import("./types").TimelineItemType} */
  2338. let previousItemType = null
  2339. /** @type {?boolean} */
  2340. let hidPreviousItem = null
  2341.  
  2342. for (let $item of $timeline.children) {
  2343. /** @type {?import("./types").TimelineItemType} */
  2344. let itemType = null
  2345. /** @type {?boolean} */
  2346. let hideItem = null
  2347. /** @type {?boolean} */
  2348. let highlightItem = null
  2349. /** @type {?HTMLElement} */
  2350. let $tweet = $item.querySelector(Selectors.TWEET)
  2351.  
  2352. if ($tweet != null) {
  2353. itemType = getTweetType($tweet)
  2354. // Only deal with retweets, quote tweets and algorithmic tweets on the
  2355. // main timeline.
  2356. if (isOnMainTimelinePage()) {
  2357. let isReply = isReplyToPreviousTweet($tweet)
  2358. if (isReply && hidPreviousItem != null) {
  2359. hideItem = hidPreviousItem
  2360. } else {
  2361. hideItem = shouldHideMainTimelineItem(itemType, page)
  2362. }
  2363.  
  2364. if (!hideItem && (itemType == 'QUOTE_TWEET' || itemType == 'RETWEETED_QUOTE_TWEET') && config.mutableQuoteTweets) {
  2365. if (config.mutedQuotes.length > 0) {
  2366. let quotedTweet = getQuotedTweetDetails($tweet)
  2367. hideItem = config.mutedQuotes.some(muted => muted.user == quotedTweet.user && muted.time == quotedTweet.time)
  2368. }
  2369. if (!hideItem) {
  2370. addCaretMenuListenerForQuoteTweet($tweet)
  2371. }
  2372. }
  2373.  
  2374. let checkType
  2375. if (config.twitterBlueChecks != 'ignore' || config.verifiedAccounts != 'ignore') {
  2376. for (let $svgPath of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  2377. let verifiedProps = getVerifiedProps($svgPath.closest('svg'))
  2378. if (!verifiedProps) continue
  2379.  
  2380. let isUserCheck = $svgPath.closest('div[data-testid="User-Names"]')
  2381. if (verifiedProps.isVerified) {
  2382. if (isUserCheck) {
  2383. checkType = 'VERIFIED'
  2384. }
  2385. if (hideItem !== true) {
  2386. hideItem = config.verifiedAccounts == 'hide'
  2387. }
  2388. highlightItem = config.verifiedAccounts == 'highlight'
  2389. }
  2390. else if (verifiedProps.isBlueVerified) {
  2391. if (isUserCheck) {
  2392. checkType = 'BLUE'
  2393. }
  2394. $svgPath.closest('div').classList.add('tnt_blue_check')
  2395. }
  2396. }
  2397. }
  2398.  
  2399. if (debug) {
  2400. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${checkType ? ` / ${checkType}` : ''}`
  2401. }
  2402. }
  2403. }
  2404. else if (!isOnMainTimelinePage()) {
  2405. if ($item.querySelector(':scope > div > div > div > article')) {
  2406. itemType = 'UNAVAILABLE'
  2407. }
  2408. }
  2409.  
  2410. if (!isOnMainTimelinePage()) {
  2411. if (itemType != null && debug) {
  2412. $item.firstElementChild.dataset.itemType = `${itemType}`
  2413. }
  2414. }
  2415.  
  2416. if (itemType == null && config.hideWhoToFollowEtc) {
  2417. // "Who to follow", "Follow some Topics" etc. headings
  2418. if ($item.querySelector(Selectors.TIMELINE_HEADING)) {
  2419. itemType = 'HEADING'
  2420. hideItem = true
  2421. // Also hide the divider above the heading
  2422. if ($previousItem?.innerText == '' && $previousItem.firstElementChild) {
  2423. /** @type {HTMLElement} */ ($previousItem.firstElementChild).style.display = 'none'
  2424. }
  2425. }
  2426. }
  2427.  
  2428. if (itemType == null) {
  2429. // Assume a non-identified item following an identified item is related.
  2430. // "Who to follow" users and "Follow some Topics" topics appear in
  2431. // subsequent items, as do "Show this thread" and "Show more" links.
  2432. if (previousItemType != null) {
  2433. hideItem = hidPreviousItem
  2434. itemType = previousItemType
  2435. }
  2436. // The first item in the timeline is sometimes an empty placeholder <div>
  2437. else if ($item !== $timeline.firstElementChild && hideItem == null) {
  2438. // We're probably also missing some spacer / divider nodes
  2439. warn('unhandled timeline item', $item)
  2440. }
  2441. }
  2442.  
  2443. if (hideItem != null) {
  2444. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  2445. /** @type {HTMLElement} */ ($item.firstElementChild).style.display = hideItem ? 'none' : ''
  2446. // Log these out as they can't be reliably triggered for testing
  2447. if (itemType == 'HEADING' || previousItemType == 'HEADING') {
  2448. log(`hid a ${previousItemType == 'HEADING' ? 'post-' : ''}heading item`, $item)
  2449. }
  2450. }
  2451. }
  2452.  
  2453. if (highlightItem != null) {
  2454. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.backgroundColor != (highlightItem ? 'rgba(29, 161, 242, 0.25)' : '')) {
  2455. /** @type {HTMLElement} */ ($item.firstElementChild).style.backgroundColor = highlightItem ? 'rgba(29, 161, 242, 0.25)' : ''
  2456. }
  2457. }
  2458.  
  2459. $previousItem = $item
  2460. hidPreviousItem = hideItem
  2461. // If we hid a heading, keep hiding everything after it until we hit a tweet
  2462. if (!(previousItemType == 'HEADING' && itemType == null)) {
  2463. previousItemType = itemType
  2464. }
  2465. }
  2466.  
  2467. if (config.twitterBlueChecks != 'ignore' && !isOnMainTimelinePage()) {
  2468. tagTwitterBlueCheckmarks($timeline)
  2469. }
  2470. }
  2471.  
  2472. function onTitleChange(title) {
  2473. log('title changed', {title: title.split(ltr ? ' / ' : ' \\ ')[ltr ? 0 : 1], path: location.pathname})
  2474.  
  2475. if (checkforDisabledHomeTimeline()) return
  2476.  
  2477. // Ignore leading notification counts in titles, e.g. '(1) Latest Tweets'
  2478. let notificationCount = ''
  2479. if (TITLE_NOTIFICATION_RE.test(title)) {
  2480. notificationCount = TITLE_NOTIFICATION_RE.exec(title)[0]
  2481. title = title.replace(TITLE_NOTIFICATION_RE, '')
  2482. }
  2483.  
  2484. let homeNavigationWasUsed = homeNavigationIsBeingUsed
  2485. homeNavigationIsBeingUsed = false
  2486.  
  2487. if (title == getString('TWITTER')) {
  2488. // Mobile uses "Twitter" when viewing a photo - we need to let these process
  2489. // so the next page will be re-processed when the photo is closed.
  2490. if (mobile && URL_PHOTO_RE.test(location.pathname)) {
  2491. log('viewing a photo on mobile')
  2492. }
  2493. // Ignore Flash of Uninitialised Title when navigating to a page for the
  2494. // first time.
  2495. else {
  2496. log('ignoring Flash of Uninitialised Title')
  2497. return
  2498. }
  2499. }
  2500.  
  2501. let newPage = title.split(ltr ? ' / ' : ' \\ ')[ltr ? 0 : 1]
  2502.  
  2503. // Only allow the same page to re-process after a title change on desktop if
  2504. // the "Customize your view" dialog is currently open.
  2505. if (newPage == currentPage && !(desktop && location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW)) {
  2506. log('ignoring duplicate title change')
  2507. currentNotificationCount = notificationCount
  2508. return
  2509. }
  2510.  
  2511. // On desktop, stay on the separated tweets timeline when…
  2512. if (desktop && currentPage == separatedTweetsTimelineTitle &&
  2513. // …the title has changed back to the main timeline…
  2514. (newPage == getString('LATEST_TWEETS') || newPage == getString('HOME')) &&
  2515. // …the Home nav link or Latest Tweets / Home header _wasn't_ clicked and…
  2516. !homeNavigationWasUsed &&
  2517. (
  2518. // …the user viewed a photo.
  2519. URL_PHOTO_RE.test(location.pathname) ||
  2520. // …the user stopped viewing a photo.
  2521. URL_PHOTO_RE.test(currentPath) ||
  2522. // …the user opened or used the "Customize your view" dialog.
  2523. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  2524. // …the user closed the "Customize your view" dialog.
  2525. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  2526. // …the user opened the "Send via Direct Message" dialog.
  2527. location.pathname == PagePaths.COMPOSE_MESSAGE ||
  2528. // …the user closed the "Send via Direct Message" dialog.
  2529. currentPath == PagePaths.COMPOSE_MESSAGE ||
  2530. // …the user opened the compose Tweet dialog.
  2531. location.pathname == PagePaths.COMPOSE_TWEET ||
  2532. // …the user closed the compose Tweet dialog.
  2533. currentPath == PagePaths.COMPOSE_TWEET ||
  2534. // …the notification count in the title changed.
  2535. notificationCount != currentNotificationCount
  2536. )) {
  2537. log('ignoring title change on separated tweets timeline')
  2538. currentNotificationCount = notificationCount
  2539. currentPath = location.pathname
  2540. setTitle(separatedTweetsTimelineTitle)
  2541. return
  2542. }
  2543.  
  2544. // Restore display of the separated tweets timelne if it's the last one we
  2545. // saw, and the user navigated back home without using the Home navigation
  2546. // item.
  2547. if (location.pathname == PagePaths.HOME &&
  2548. currentPath != PagePaths.HOME &&
  2549. !homeNavigationWasUsed &&
  2550. lastMainTimelineTitle != null &&
  2551. separatedTweetsTimelineTitle != null &&
  2552. lastMainTimelineTitle == separatedTweetsTimelineTitle) {
  2553. log('restoring display of the separated tweets timeline')
  2554. currentNotificationCount = notificationCount
  2555. currentPath = location.pathname
  2556. setTitle(separatedTweetsTimelineTitle)
  2557. return
  2558. }
  2559.  
  2560. // Assumption: all non-FOUT, non-duplicate title changes are navigation, which
  2561. // need the page to be re-processed.
  2562.  
  2563. currentPage = newPage
  2564. currentNotificationCount = notificationCount
  2565. currentPath = location.pathname
  2566.  
  2567. if (isOnLatestTweetsTimeline() || isOnHomeTimeline()) {
  2568. currentMainTimelineType = currentPage
  2569. }
  2570. if (isOnMainTimelinePage()) {
  2571. lastMainTimelineTitle = currentPage
  2572. }
  2573.  
  2574. log('processing new page')
  2575.  
  2576. processCurrentPage()
  2577. }
  2578.  
  2579. function processCurrentPage() {
  2580. if (pageObservers.length > 0) {
  2581. log(
  2582. `disconnecting ${pageObservers.length} page observer${s(pageObservers.length)}`,
  2583. pageObservers.map(observer => observer['name'])
  2584. )
  2585. pageObservers.forEach(observer => observer.disconnect())
  2586. pageObservers = []
  2587. }
  2588.  
  2589. if (config.alwaysUseLatestTweets && currentPage == getString('HOME')) {
  2590. switchToLatestTweets(currentPage)
  2591. return
  2592. }
  2593.  
  2594. // Hooks for styling pages
  2595. $body.classList.toggle('Explore', isOnExplorePage())
  2596. $body.classList.toggle('HideAppNags', (
  2597. mobile && config.hideAppNags && MOBILE_LOGGED_OUT_URLS.includes(currentPath))
  2598. )
  2599. $body.classList.toggle('HideSidebar', shouldHideSidebar())
  2600. $body.classList.toggle('List', isOnListPage())
  2601. $body.classList.toggle('MainTimeline', isOnMainTimelinePage())
  2602. $body.classList.toggle('Notifications', isOnNotificationsPage())
  2603. $body.classList.toggle('Profile', isOnProfilePage())
  2604. if (!isOnProfilePage()) {
  2605. $body.classList.remove('Blocked', 'NoMedia')
  2606. }
  2607. $body.classList.toggle('QuoteTweets', isOnQuoteTweetsPage())
  2608. $body.classList.toggle('Tweet', isOnIndividualTweetPage())
  2609. $body.classList.toggle('Search', isOnSearchPage())
  2610.  
  2611. // "Which version of the main timeline are we on?" hooks for styling
  2612. $body.classList.toggle('Home', isOnHomeTimeline())
  2613. $body.classList.toggle('LatestTweets', isOnLatestTweetsTimeline())
  2614. $body.classList.toggle('SeparatedTweets', isOnSeparatedTweetsTimeline())
  2615. $body.classList.toggle('TimelineTabs', isOnTabbedTimeline())
  2616.  
  2617. if (desktop) {
  2618. if (config.twitterBlueChecks != 'ignore' || config.fullWidthContent && (isOnMainTimelinePage() || isOnListPage())) {
  2619. observeSidebar()
  2620. } else {
  2621. $body.classList.remove('Sidebar')
  2622. }
  2623.  
  2624. if (config.twitterBlueChecks != 'ignore' && (isOnSearchPage() || isOnExplorePage())) {
  2625. observeSearchForm()
  2626. }
  2627. }
  2628.  
  2629. if (isOnMainTimelinePage()) {
  2630. if (config.retweets == 'separate' || config.quoteTweets == 'separate') {
  2631. addSeparatedTweetsTimelineControl(currentPage)
  2632. } else if (mobile) {
  2633. removeMobileTimelineHeaderElements()
  2634. }
  2635. observeTimeline(currentPage)
  2636. } else {
  2637. if (mobile) {
  2638. removeMobileTimelineHeaderElements()
  2639. }
  2640. }
  2641.  
  2642. if (isOnProfilePage()) {
  2643. tweakProfilePage()
  2644. }
  2645.  
  2646. if (isOnIndividualTweetPage()) {
  2647. tweakIndividualTweetPage()
  2648. }
  2649.  
  2650. if (mobile && config.hideExplorePageContents && isOnExplorePage()) {
  2651. tweakExplorePage(currentPage)
  2652. }
  2653. }
  2654.  
  2655. /**
  2656. * The mobile version of Twitter reuses heading elements between screens, so we
  2657. * always remove any elements which could be there from the previous page and
  2658. * re-add them later when needed.
  2659. */
  2660. function removeMobileTimelineHeaderElements() {
  2661. if (mobile) {
  2662. document.querySelector('#tnt_shared_tweets_timeline_title')?.remove()
  2663. document.querySelector('#tnt_switch_timeline')?.remove()
  2664. }
  2665. }
  2666.  
  2667. /**
  2668. * Sets the page name in <title>, retaining any current notification count.
  2669. * @param {string} page
  2670. */
  2671. function setTitle(page) {
  2672. document.title = ltr ? (
  2673. `${currentNotificationCount}${page} / ${getString('TWITTER')}`
  2674. ) : (
  2675. `${currentNotificationCount}${getString('TWITTER')} \\ ${page}`
  2676. )
  2677. }
  2678.  
  2679. /**
  2680. * @param {import("./types").AlgorithmicTweetsConfig} config
  2681. * @param {string} page
  2682. * @returns {boolean}
  2683. */
  2684. function shouldHideAlgorithmicTweet(config, page) {
  2685. switch (config) {
  2686. case 'hide': return true
  2687. case 'ignore': return page == separatedTweetsTimelineTitle
  2688. }
  2689. }
  2690.  
  2691. /**
  2692. * @param {import("./types").TimelineItemType} type
  2693. * @param {string} page
  2694. * @returns {boolean}
  2695. */
  2696. function shouldHideMainTimelineItem(type, page) {
  2697. switch (type) {
  2698. case 'COMMUNITY_TWEET':
  2699. return shouldHideAlgorithmicTweet(config.communityTweets, page)
  2700. case 'FOLLOWEES_FOLLOWS':
  2701. return shouldHideAlgorithmicTweet(config.followeesFollows, page)
  2702. case 'LIKED':
  2703. return shouldHideAlgorithmicTweet(config.likedTweets, page)
  2704. case 'QUOTE_TWEET':
  2705. return shouldHideSharedTweet(config.quoteTweets, page)
  2706. case 'REPLIED':
  2707. return shouldHideAlgorithmicTweet(config.repliedToTweets, page)
  2708. case 'RETWEET':
  2709. case 'RETWEETED_QUOTE_TWEET':
  2710. return shouldHideSharedTweet(config.retweets, page)
  2711. case 'SUGGESTED_TOPIC_TWEET':
  2712. return shouldHideAlgorithmicTweet(config.suggestedTopicTweets, page)
  2713. case 'TWEET':
  2714. return page == separatedTweetsTimelineTitle
  2715. case 'UNAVAILABLE_QUOTE_TWEET':
  2716. return config.hideUnavailableQuoteTweets || shouldHideSharedTweet(config.quoteTweets, page)
  2717. case 'UNAVAILABLE_RETWEET':
  2718. return config.hideUnavailableQuoteTweets || shouldHideSharedTweet(config.retweets, page)
  2719. default:
  2720. return true
  2721. }
  2722. }
  2723.  
  2724. /**
  2725. * @param {import("./types").SharedTweetsConfig} config
  2726. * @param {string} page
  2727. * @returns {boolean}
  2728. */
  2729. function shouldHideSharedTweet(config, page) {
  2730. switch (config) {
  2731. case 'hide': return true
  2732. case 'ignore': return page == separatedTweetsTimelineTitle
  2733. case 'separate': return page != separatedTweetsTimelineTitle
  2734. }
  2735. }
  2736.  
  2737. async function switchToLatestTweets(page) {
  2738. log('switching to Latest Tweets timeline')
  2739.  
  2740. let sparkleSelector = mobile ? `
  2741. ${Selectors.MOBILE_TIMELINE_HEADER_OLD} div:nth-of-type(3) [role="button"],
  2742. ${Selectors.MOBILE_TIMELINE_HEADER_NEW} div:nth-of-type(3) [role="button"]
  2743. ` : `${Selectors.PRIMARY_COLUMN} [role="button"]`
  2744. let $sparkleButton = await getElement(sparkleSelector, {
  2745. name: 'sparkle button',
  2746. stopIf: pageIsNot(page),
  2747. })
  2748. if ($sparkleButton == null) return
  2749.  
  2750. if ($sparkleButton.getAttribute('aria-label') == getString('TIMELINE_OPTIONS')) {
  2751. log('tabbed timeline is being used')
  2752.  
  2753. let $timelineHeader = document.querySelector(desktop ? Selectors.DESKTOP_TIMELINE_HEADER : Selectors.MOBILE_TIMELINE_HEADER_OLD)
  2754. if ($timelineHeader == null) {
  2755. warn('could not find timeline header')
  2756. return
  2757. }
  2758.  
  2759. if ($timelineHeader.childElementCount != (desktop ? 3 : 2)) {
  2760. log('timeline tabs not showing - clicking sparkle button')
  2761. $sparkleButton.click()
  2762.  
  2763. let $pinYourLatestTimeline = await getElement('div[role="menu"] div[role="menuitem"]', {
  2764. name: '"Pin your Latest timeline" menu item',
  2765. stopIf: pageIsNot(page),
  2766. })
  2767. if ($pinYourLatestTimeline == null) return
  2768.  
  2769. log('clicking "Pin your Latest timeline" menu item')
  2770. $pinYourLatestTimeline.click()
  2771. }
  2772.  
  2773. let $latestTweetsTab = /** @type {HTMLElement} */ ($timelineHeader.querySelector('[data-testid="ScrollSnap-List"] [role="presentation"]:nth-child(2) a'))
  2774. if ($latestTweetsTab == null) {
  2775. warn('could not find "Latest Tweets" tab')
  2776. return
  2777. }
  2778.  
  2779. log('clicking "Latest Tweets" tab')
  2780. $latestTweetsTab.click()
  2781. }
  2782. else {
  2783. log('non-tabbed timeline is being used')
  2784. log('clicking sparkle button')
  2785. $sparkleButton.click()
  2786.  
  2787. let $seeLatestTweetsInstead = await getElement('div[role="menu"] div[role="menuitem"]', {
  2788. name: '"See latest Tweets instead" menu item',
  2789. stopIf: pageIsNot(page),
  2790. })
  2791. if ($seeLatestTweetsInstead == null) return
  2792.  
  2793. log('clicking "See latest Tweets" instead menu item')
  2794. $seeLatestTweetsInstead.click()
  2795. }
  2796. }
  2797.  
  2798. /**
  2799. * Add a tnt_blue_check class to any Twitter Blue checkmarks inside an element.
  2800. * @param {HTMLElement} $el
  2801. */
  2802. function tagTwitterBlueCheckmarks($el) {
  2803. for (let $svgPath of $el.querySelectorAll(Selectors.VERIFIED_TICK)) {
  2804. let verifiedProps = getVerifiedProps($svgPath.closest('svg'))
  2805. if (!verifiedProps) continue
  2806.  
  2807. if (verifiedProps.isBlueVerified && !verifiedProps.isVerified) {
  2808. $svgPath.closest(':is(div, span):not([role="button"]').classList.add('tnt_blue_check')
  2809. }
  2810. }
  2811. }
  2812.  
  2813. async function tweakExplorePage(page) {
  2814. let $searchInput = await getElement('input[data-testid="SearchBox_Search_Input"]', {
  2815. name: 'search input',
  2816. stopIf: pageIsNot(page),
  2817. })
  2818. if (!$searchInput) return
  2819.  
  2820. log('focusing search input')
  2821. $searchInput.focus()
  2822.  
  2823. let $backButton = await getElement('div[data-testid="app-bar-back"]', {
  2824. name: 'back button',
  2825. stopIf: pageIsNot(page),
  2826. })
  2827. if (!$backButton) return
  2828.  
  2829. // The back button appears after the search input is focused. When you tap it
  2830. // or go back manually, it's replaced with the slide-out menu button and the
  2831. // Explore page contents are shown - we want to skip that.
  2832. pageObservers.push(
  2833. observeElement($backButton.parentElement, (mutations) => {
  2834. mutations.forEach((mutation) => {
  2835. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  2836. if ($el.querySelector('[data-testid="DashButton_ProfileIcon_Link"]')) {
  2837. log('slide-out menu button appeared, going back to skip Explore page')
  2838. history.go(-2)
  2839. }
  2840. })
  2841. })
  2842. }, 'back button parent')
  2843. )
  2844. }
  2845.  
  2846. /**
  2847. * Re-navigates to a tweet to get rid of the "More Tweets" section.
  2848. */
  2849. function tweakIndividualTweetPage() {
  2850. if (config.hideMoreTweets && location.search) {
  2851. log('re-navigating to get rid of More Tweets')
  2852. location.replace(location.origin + location.pathname)
  2853. return
  2854. }
  2855. if (config.twitterBlueChecks != 'ignore') {
  2856. observeTimeline(currentPage)
  2857. }
  2858. }
  2859.  
  2860. function tweakProfilePage() {
  2861. if (config.twitterBlueChecks != 'ignore') {
  2862. tagTwitterBlueCheckmarks(document.querySelector(Selectors.PRIMARY_COLUMN))
  2863. }
  2864. observeTimeline(currentPage)
  2865. if (desktop && config.hideSidebarContent) {
  2866. observeProfileBlockedStatus(currentPage)
  2867. observeProfileSidebar(currentPage)
  2868. }
  2869. }
  2870. //#endregion
  2871.  
  2872. //#region Main
  2873. function main() {
  2874. let $settings = /** @type {HTMLScriptElement} */ (document.querySelector('script#tnt_settings'))
  2875. if ($settings) {
  2876. try {
  2877. Object.assign(config, JSON.parse($settings.innerText))
  2878. } catch(e) {
  2879. warn('error getting initial settings', e)
  2880. }
  2881.  
  2882. let settingsObserver = new MutationObserver(() => {
  2883. try {
  2884. onSettingsChanged(JSON.parse($settings.innerText))
  2885. } catch(e) {
  2886. warn('error changing settings', e)
  2887. }
  2888. })
  2889. settingsObserver.observe($settings, {childList: true})
  2890. }
  2891.  
  2892. if (config.debug) {
  2893. debug = true
  2894. }
  2895.  
  2896. log({config, lang, platform: mobile ? 'mobile' : 'desktop'})
  2897.  
  2898. configureSeparatedTweetsTimelineTitle()
  2899. configureCss()
  2900. checkReactNativeStylesheet()
  2901. observeHtmlFontSize()
  2902. observeBodyBackgroundColor()
  2903. observeColor()
  2904. observePopups()
  2905.  
  2906. observeTitle()
  2907. }
  2908.  
  2909. /**
  2910. * @param {Partial<import("./types").Config>} changes
  2911. */
  2912. function configChanged(changes) {
  2913. log('config changed', changes)
  2914.  
  2915. configureCss()
  2916. configureFont()
  2917. configureNavFontSizeCss()
  2918. configureThemeCss()
  2919. observePopups()
  2920.  
  2921. // Only re-process the current page if navigation wasn't already triggered
  2922. // while applying the following config changes (if there were any).
  2923. let navigationTriggered = (
  2924. configureSeparatedTweetsTimelineTitle() ||
  2925. checkforDisabledHomeTimeline()
  2926. )
  2927. if (!navigationTriggered) {
  2928. processCurrentPage()
  2929. }
  2930. }
  2931.  
  2932. main()
  2933. //#endregion