Tweak New Twitter

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

目前为 2022-08-27 提交的版本,查看 最新版本

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