Tweak New Twitter

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

当前为 2022-01-26 提交的版本,查看 最新版本

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