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

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