Tweak New Twitter

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

当前为 2022-03-25 提交的版本,查看 最新版本

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