Control Panel for Twitter

Gives you more control over Twitter and adds missing features and UI improvements

当前为 2023-04-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Control Panel for Twitter
  3. // @description Gives you more control over Twitter and adds missing features and UI improvements
  4. // @icon https://raw.githubusercontent.com/insin/control-panel-for-twitter/master/icons/icon32.png
  5. // @namespace https://github.com/insin/control-panel-for-twitter/
  6. // @match https://twitter.com/*
  7. // @match https://mobile.twitter.com/*
  8. // @run-at document-start
  9. // @version 104
  10. // ==/UserScript==
  11. void function() {
  12.  
  13. let debug = false
  14.  
  15. /** @type {boolean} */
  16. let desktop
  17. /** @type {boolean} */
  18. let mobile
  19. let isSafari = navigator.userAgent.includes('Safari/') && !/Chrom(e|ium)\//.test(navigator.userAgent)
  20.  
  21. /** @type {HTMLHtmlElement} */
  22. let $html
  23. /** @type {HTMLBodyElement} */
  24. let $body
  25. /** @type {string} */
  26. let lang
  27. /** @type {string} */
  28. let dir
  29. /** @type {boolean} */
  30. let ltr
  31.  
  32. //#region Default config
  33. /**
  34. * @type {import("./types").Config}
  35. */
  36. const config = {
  37. debug: false,
  38. // Shared
  39. addAddMutedWordMenuItem: true,
  40. alwaysUseLatestTweets: true,
  41. defaultToLatestSearch: false,
  42. disableHomeTimeline: false,
  43. disabledHomeTimelineRedirect: 'notifications',
  44. dontUseChirpFont: false,
  45. dropdownMenuFontWeight: true,
  46. fastBlock: true,
  47. followButtonStyle: 'monochrome',
  48. hideAnalyticsNav: true,
  49. hideBookmarkButton: false,
  50. hideBookmarkMetrics: false,
  51. hideBookmarksNav: false,
  52. hideCommunitiesNav: true,
  53. hideExplorePageContents: true,
  54. hideFollowingMetrics: true,
  55. hideForYouTimeline: true,
  56. hideHelpCenterNav: true,
  57. hideHomeHeading: true,
  58. hideKeyboardShortcutsNav: false,
  59. hideLikeMetrics: true,
  60. hideListsNav: false,
  61. hideMetrics: false,
  62. // hideMomentsNav: true,
  63. hideMonetizationNav: true,
  64. hideMoreTweets: true,
  65. // hideNewslettersNav: true,
  66. hideQuoteTweetMetrics: true,
  67. hideReplyMetrics: true,
  68. hideRetweetMetrics: true,
  69. hideShareTweetButton: false,
  70. hideTopicsNav: true,
  71. hideTotalTweetsMetrics: true,
  72. hideTweetAnalyticsLinks: false,
  73. hideTwitterAdsNav: true,
  74. hideTwitterBlueNav: true,
  75. hideTwitterCircleNav: false,
  76. hideTwitterForProfessionalsNav: true,
  77. hideUnavailableQuoteTweets: true,
  78. hideVerifiedNotificationsTab: true,
  79. hideViews: true,
  80. hideWhoToFollowEtc: true,
  81. listRetweets: 'ignore',
  82. mutableQuoteTweets: true,
  83. mutedQuotes: [],
  84. quoteTweets: 'ignore',
  85. reducedInteractionMode: false,
  86. retweets: 'separate',
  87. tweakQuoteTweetsPage: true,
  88. twitterBlueChecks: 'replace',
  89. uninvertFollowButtons: true,
  90. // Experiments
  91. verifiedAccounts: 'ignore',
  92. // Desktop only
  93. fullWidthContent: false,
  94. fullWidthMedia: true,
  95. hideAccountSwitcher: true,
  96. hideExploreNav: true,
  97. hideMessagesDrawer: true,
  98. hideSidebarContent: true,
  99. navBaseFontSize: true,
  100. showRelevantPeople: false,
  101. // Mobile only
  102. hideAppNags: true,
  103. hideMessagesBottomNavItem: false,
  104. }
  105. //#endregion
  106.  
  107. //#region Locales
  108. /**
  109. * @type {{[key: string]: import("./types").Locale}}
  110. */
  111. const locales = {
  112. 'ar-x-fm': {
  113. ADD_MUTED_WORD: 'اضافة كلمة مكتومة',
  114. DISCOVER_MORE: 'اكتشاف المزيد',
  115. HOME: 'الرئيسيّة',
  116. MUTE_THIS_CONVERSATION: 'كتم هذه المحادثه',
  117. QUOTE_TWEET: 'اقتباس التغريدة',
  118. QUOTE_TWEETS: 'تغريدات اقتباس',
  119. RETWEETS: 'إعادات التغريد',
  120. SHARED_TWEETS: 'التغريدات المشتركة',
  121. TURN_OFF_RETWEETS: 'تعطيل إعادة التغريد',
  122. TURN_ON_RETWEETS: 'تفعيل إعادة التغريد',
  123. TWITTER: 'تويتر',
  124. },
  125. ar: {
  126. ADD_MUTED_WORD: 'اضافة كلمة مكتومة',
  127. DISCOVER_MORE: 'اكتشاف المزيد',
  128. HOME: 'الرئيسيّة',
  129. MUTE_THIS_CONVERSATION: 'كتم هذه المحادثه',
  130. QUOTE_TWEET: 'اقتباس التغريدة',
  131. QUOTE_TWEETS: 'تغريدات اقتباس',
  132. RETWEETS: 'إعادات التغريد',
  133. SHARED_TWEETS: 'التغريدات المشتركة',
  134. TURN_OFF_RETWEETS: 'تعطيل إعادة التغريد',
  135. TURN_ON_RETWEETS: 'تفعيل إعادة التغريد',
  136. },
  137. bg: {
  138. ADD_MUTED_WORD: 'Добавяне на заглушена дума',
  139. DISCOVER_MORE: 'Откриване на още',
  140. HOME: 'Начало',
  141. MUTE_THIS_CONVERSATION: 'Заглушаване на разговора',
  142. QUOTE_TWEET: 'Цитиране на туита',
  143. QUOTE_TWEETS: 'Туитове с цитат',
  144. RETWEETS: 'Ретуитове',
  145. SHARED_TWEETS: 'Споделени туитове',
  146. TURN_OFF_RETWEETS: 'Изключване на ретуитовете',
  147. TURN_ON_RETWEETS: 'Включване на ретуитовете',
  148. },
  149. bn: {
  150. ADD_MUTED_WORD: 'নীরব করা শব্দ যোগ করুন',
  151. DISCOVER_MORE: 'আরও খুঁজুন',
  152. HOME: 'হোম',
  153. MUTE_THIS_CONVERSATION: 'এই কথা-বার্তা নীরব করুন',
  154. QUOTE_TWEET: 'টুইট উদ্ধৃত করুন',
  155. QUOTE_TWEETS: 'টুইট উদ্ধৃতিগুলো',
  156. RETWEETS: 'পুনঃটুইটগুলো',
  157. SHARED_TWEETS: 'ভাগ করা টুইটগুলি',
  158. TURN_OFF_RETWEETS: 'পুনঃ টুইটগুলি বন্ধ করুন',
  159. TURN_ON_RETWEETS: 'পুনঃ টুইটগুলি চালু করুন',
  160. TWITTER: 'টুইটার',
  161. },
  162. ca: {
  163. ADD_MUTED_WORD: 'Afegeix una paraula silenciada',
  164. DISCOVER_MORE: 'Descobreix-ne més',
  165. HOME: 'Inici',
  166. MUTE_THIS_CONVERSATION: 'Silencia la conversa',
  167. QUOTE_TWEET: 'Cita el tuit',
  168. QUOTE_TWEETS: 'Tuits amb cita',
  169. RETWEETS: 'Retuits',
  170. SHARED_TWEETS: 'Tuits compartits',
  171. TURN_OFF_RETWEETS: 'Desactiva els retuits',
  172. TURN_ON_RETWEETS: 'Activa els retuits',
  173. },
  174. cs: {
  175. ADD_MUTED_WORD: 'Přidat slovo na seznam skrytých slov',
  176. DISCOVER_MORE: 'Objevte víc',
  177. HOME: 'Hlavní stránka',
  178. MUTE_THIS_CONVERSATION: 'Skrýt tuto konverzaci',
  179. QUOTE_TWEET: 'Citovat Tweet',
  180. QUOTE_TWEETS: 'Tweety s citací',
  181. RETWEETS: 'Retweety',
  182. SHARED_TWEETS: 'Sdílené tweety',
  183. TURN_OFF_RETWEETS: 'Vypnout retweety',
  184. TURN_ON_RETWEETS: 'Zapnout retweety',
  185. },
  186. da: {
  187. ADD_MUTED_WORD: 'Tilføj skjult ord',
  188. DISCOVER_MORE: 'Opdag mere',
  189. HOME: 'Forside',
  190. MUTE_THIS_CONVERSATION: 'Skjul denne samtale',
  191. QUOTE_TWEET: 'Citér Tweet',
  192. QUOTE_TWEETS: 'Citat-Tweets',
  193. SHARED_TWEETS: 'Delte tweets',
  194. TURN_OFF_RETWEETS: 'Slå Retweets fra',
  195. TURN_ON_RETWEETS: 'Slå Retweets til',
  196. },
  197. de: {
  198. ADD_MUTED_WORD: 'Stummgeschaltetes Wort hinzufügen',
  199. DISCOVER_MORE: 'Mehr entdecken',
  200. HOME: 'Startseite',
  201. MUTE_THIS_CONVERSATION: 'Diese Konversation stummschalten',
  202. QUOTE_TWEET: 'Tweet zitieren',
  203. QUOTE_TWEETS: 'Zitierte Tweets',
  204. SHARED_TWEETS: 'Geteilte Tweets',
  205. TURN_OFF_RETWEETS: 'Retweets ausschalten',
  206. TURN_ON_RETWEETS: 'Retweets einschalten',
  207. },
  208. el: {
  209. ADD_MUTED_WORD: 'Προσθήκη λέξης σε σίγαση',
  210. DISCOVER_MORE: 'Ανακαλύψτε περισσότερα',
  211. HOME: 'Αρχική σελίδα',
  212. MUTE_THIS_CONVERSATION: 'Σίγαση αυτής της συζήτησης',
  213. QUOTE_TWEET: 'Παράθεση Tweet',
  214. QUOTE_TWEETS: 'Tweet με παράθεση',
  215. RETWEETS: 'Retweet',
  216. SHARED_TWEETS: 'Κοινόχρηστα Tweets',
  217. TURN_OFF_RETWEETS: 'Απενεργοποίηση των Retweet',
  218. TURN_ON_RETWEETS: 'Ενεργοποίηση των Retweet',
  219. },
  220. en: {
  221. ADD_MUTED_WORD: 'Add muted word',
  222. DISCOVER_MORE: 'Discover more',
  223. HOME: 'Home',
  224. MUTE_THIS_CONVERSATION: 'Mute this conversation',
  225. QUOTE_TWEET: 'Quote Tweet',
  226. QUOTE_TWEETS: 'Quote Tweets',
  227. RETWEETS: 'Retweets',
  228. SHARED_TWEETS: 'Shared Tweets',
  229. TURN_OFF_RETWEETS: 'Turn off Retweets',
  230. TURN_ON_RETWEETS: 'Turn on Retweets',
  231. TWITTER: 'Twitter',
  232. },
  233. es: {
  234. ADD_MUTED_WORD: 'Añadir palabra silenciada',
  235. DISCOVER_MORE: 'Descubrir más',
  236. HOME: 'Inicio',
  237. MUTE_THIS_CONVERSATION: 'Silenciar esta conversación',
  238. QUOTE_TWEET: 'Citar Tweet',
  239. QUOTE_TWEETS: 'Tweets citados',
  240. SHARED_TWEETS: 'Tweets compartidos',
  241. TURN_OFF_RETWEETS: 'Desactivar Retweets',
  242. TURN_ON_RETWEETS: 'Activar Retweets',
  243. },
  244. eu: {
  245. ADD_MUTED_WORD: 'Gehitu isilarazitako hitza',
  246. HOME: 'Hasiera',
  247. MUTE_THIS_CONVERSATION: 'Isilarazi elkarrizketa hau',
  248. QUOTE_TWEET: 'Txioa apaitu',
  249. QUOTE_TWEETS: 'Aipatu txioak',
  250. RETWEETS: 'Bertxioak',
  251. SHARED_TWEETS: 'Partekatutako',
  252. TURN_OFF_RETWEETS: 'Desaktibatu birtxioak',
  253. TURN_ON_RETWEETS: 'Aktibatu birtxioak',
  254. },
  255. fa: {
  256. ADD_MUTED_WORD: 'افزودن واژه خموش‌سازی شده',
  257. DISCOVER_MORE: 'کاوش بیشتر',
  258. HOME: 'خانه',
  259. MUTE_THIS_CONVERSATION: 'خموش‌سازی این گفتگو',
  260. QUOTE_TWEET: 'نقل‌توییت',
  261. QUOTE_TWEETS: 'نقل‌توییت‌ها',
  262. RETWEETS: 'بازتوییت‌ها',
  263. SHARED_TWEETS: 'توییتهای مشترک',
  264. TURN_OFF_RETWEETS: 'غیرفعال‌سازی بازتوییت‌ها',
  265. TURN_ON_RETWEETS: 'فعال سازی بازتوییت‌ها',
  266. TWITTER: 'توییتر',
  267. },
  268. fi: {
  269. ADD_MUTED_WORD: 'Lisää hiljennetty sana',
  270. DISCOVER_MORE: 'Löydä uutta',
  271. HOME: 'Etusivu',
  272. MUTE_THIS_CONVERSATION: 'Hiljennä tämä keskustelu',
  273. QUOTE_TWEET: 'Twiitin lainaus',
  274. QUOTE_TWEETS: 'Twiitin lainaukset',
  275. RETWEETS: 'Uudelleentwiittaukset',
  276. SHARED_TWEETS: 'Jaetut twiitit',
  277. TURN_OFF_RETWEETS: 'Poista uudelleentwiittaukset käytöstä',
  278. TURN_ON_RETWEETS: 'Ota uudelleentwiittaukset käyttöön',
  279. },
  280. fil: {
  281. ADD_MUTED_WORD: 'Idagdag ang naka-mute na salita',
  282. DISCOVER_MORE: 'Tuklasin ang higit pa',
  283. HOME: 'Home',
  284. MUTE_THIS_CONVERSATION: 'I-mute ang usapang ito',
  285. QUOTE_TWEET: 'Quote na Tweet',
  286. QUOTE_TWEETS: 'Mga Quote na Tweet',
  287. RETWEETS: 'Mga Retweet',
  288. SHARED_TWEETS: 'Mga Ibinahaging Tweet',
  289. TURN_OFF_RETWEETS: 'I-off ang Retweets',
  290. TURN_ON_RETWEETS: 'I-on ang Retweets',
  291. },
  292. fr: {
  293. ADD_MUTED_WORD: 'Ajouter un mot masqué',
  294. DISCOVER_MORE: 'Découvrez plus',
  295. HOME: 'Accueil',
  296. MUTE_THIS_CONVERSATION: 'Masquer cette conversation',
  297. QUOTE_TWEET: 'Citer le Tweet',
  298. QUOTE_TWEETS: 'Tweets cités',
  299. SHARED_TWEETS: 'Tweets partagés',
  300. TURN_OFF_RETWEETS: 'Désactiver les Retweets',
  301. TURN_ON_RETWEETS: 'Activer les Retweets',
  302. },
  303. ga: {
  304. ADD_MUTED_WORD: 'Cuir focal balbhaithe leis',
  305. HOME: 'Baile',
  306. MUTE_THIS_CONVERSATION: 'Balbhaigh an comhrá seo',
  307. QUOTE_TWEET: 'Cuir Ráiteas Leis',
  308. QUOTE_TWEETS: 'Luaigh Tvuíteanna',
  309. RETWEETS: 'Atweetanna',
  310. SHARED_TWEETS: 'Tweetanna Roinnte',
  311. TURN_OFF_RETWEETS: 'Cas as Atweetanna',
  312. TURN_ON_RETWEETS: 'Cas Atweetanna air',
  313. },
  314. gl: {
  315. ADD_MUTED_WORD: 'Engadir palabra silenciada',
  316. HOME: 'Inicio',
  317. MUTE_THIS_CONVERSATION: 'Silenciar esta conversa',
  318. QUOTE_TWEET: 'Citar chío',
  319. QUOTE_TWEETS: 'Chíos citados',
  320. RETWEETS: 'Rechouchíos',
  321. SHARED_TWEETS: 'Chíos compartidos',
  322. TURN_OFF_RETWEETS: 'Desactivar os rechouchíos',
  323. TURN_ON_RETWEETS: 'Activar os rechouchíos',
  324. },
  325. gu: {
  326. ADD_MUTED_WORD: 'જોડાણ અટકાવેલો શબ્દ ઉમેરો',
  327. DISCOVER_MORE: 'વધુ શોધો',
  328. HOME: 'હોમ',
  329. MUTE_THIS_CONVERSATION: 'આ વાર્તાલાપનું જોડાણ અટકાવો',
  330. QUOTE_TWEET: 'અવતરણની સાથે ટ્વીટ કરો',
  331. QUOTE_TWEETS: 'અવતરણની સાથે ટ્વીટ્સ',
  332. RETWEETS: 'પુનટ્વીટ્સ',
  333. SHARED_TWEETS: 'શેર કરેલી ટ્વીટ્સ',
  334. TURN_OFF_RETWEETS: 'પુનટ્વીટ્સ બંધ કરો',
  335. TURN_ON_RETWEETS: 'પુનટ્વીટ્સ ચાલુ કરો',
  336. },
  337. he: {
  338. ADD_MUTED_WORD: 'הוסף מילה מושתקת',
  339. DISCOVER_MORE: 'גלה עוד',
  340. HOME: 'דף הבית',
  341. MUTE_THIS_CONVERSATION: 'להשתיק את השיחה הזאת',
  342. QUOTE_TWEET: 'ציטוט ציוץ',
  343. QUOTE_TWEETS: 'ציוצי ציטוט',
  344. RETWEETS: 'ציוצים מחדש',
  345. SHARED_TWEETS: 'ציוצים משותפים',
  346. TURN_OFF_RETWEETS: 'כבה ציוצים מחדש',
  347. TURN_ON_RETWEETS: 'הפעל ציוצים מחדש',
  348. TWITTER: 'טוויטר',
  349. },
  350. hi: {
  351. ADD_MUTED_WORD: 'म्यूट किया गया शब्द जोड़ें',
  352. DISCOVER_MORE: 'और अधिक जानें',
  353. HOME: 'होम',
  354. MUTE_THIS_CONVERSATION: 'इस बातचीत को म्यूट करें',
  355. QUOTE_TWEET: 'ट्वीट क्वोट करें',
  356. QUOTE_TWEETS: 'कोट ट्वीट्स',
  357. RETWEETS: 'रीट्वीट्स',
  358. SHARED_TWEETS: 'साझा किए गए ट्वीट',
  359. TURN_OFF_RETWEETS: 'रीट्वीट बंद करें',
  360. TURN_ON_RETWEETS: 'रीट्वीट चालू करें',
  361. },
  362. hr: {
  363. ADD_MUTED_WORD: 'Dodaj onemogućenu riječ',
  364. DISCOVER_MORE: 'Otkrijte više',
  365. HOME: 'Naslovnica',
  366. MUTE_THIS_CONVERSATION: 'Isključi zvuk ovog razgovora',
  367. QUOTE_TWEET: 'Citiraj Tweet',
  368. QUOTE_TWEETS: 'Citirani tweetovi',
  369. RETWEETS: 'Proslijeđeni tweetovi',
  370. SHARED_TWEETS: 'Dijeljeni tweetovi',
  371. TURN_OFF_RETWEETS: 'Isključi proslijeđene tweetove',
  372. TURN_ON_RETWEETS: 'Uključi proslijeđene tweetove',
  373. },
  374. hu: {
  375. ADD_MUTED_WORD: 'Elnémított szó hozzáadása',
  376. DISCOVER_MORE: 'Továbbiak felfedezése',
  377. HOME: 'Kezdőlap',
  378. MUTE_THIS_CONVERSATION: 'Beszélgetés némítása',
  379. QUOTE_TWEET: 'Tweet idézése',
  380. QUOTE_TWEETS: 'Tweet-idézések',
  381. RETWEETS: 'Retweetek',
  382. SHARED_TWEETS: 'Megosztott tweetek',
  383. TURN_OFF_RETWEETS: 'Retweetek kikapcsolása',
  384. TURN_ON_RETWEETS: 'Retweetek bekapcsolása',
  385. },
  386. id: {
  387. ADD_MUTED_WORD: 'Tambahkan kata kunci yang dibisukan',
  388. DISCOVER_MORE: 'Temukan lebih banyak',
  389. HOME: 'Beranda',
  390. MUTE_THIS_CONVERSATION: 'Bisukan percakapan ini',
  391. QUOTE_TWEET: 'Kutip Tweet',
  392. QUOTE_TWEETS: 'Tweet Kutipan',
  393. RETWEETS: 'Retweet',
  394. SHARED_TWEETS: 'Tweet yang Dibagikan',
  395. TURN_OFF_RETWEETS: 'Matikan Retweet',
  396. TURN_ON_RETWEETS: 'Nyalakan Retweet',
  397. },
  398. it: {
  399. ADD_MUTED_WORD: 'Aggiungi parola o frase silenziata',
  400. DISCOVER_MORE: 'Continua con la scoperta',
  401. HOME: 'Home',
  402. MUTE_THIS_CONVERSATION: 'Silenzia questa conversazione',
  403. QUOTE_TWEET: 'Cita Tweet',
  404. QUOTE_TWEETS: 'Tweet di citazione',
  405. RETWEETS: 'Retweet',
  406. SHARED_TWEETS: 'Tweet condivisi',
  407. TURN_OFF_RETWEETS: 'Disattiva Retweet',
  408. TURN_ON_RETWEETS: 'Attiva Retweet',
  409. },
  410. ja: {
  411. ADD_MUTED_WORD: 'ミュートするキーワードを追加',
  412. DISCOVER_MORE: 'もっと見つける',
  413. HOME: 'ホーム',
  414. MUTE_THIS_CONVERSATION: 'この会話をミュート',
  415. QUOTE_TWEET: '引用ツイート',
  416. QUOTE_TWEETS: '引用ツイート',
  417. RETWEETS: 'リツイート',
  418. SHARED_TWEETS: '共有ツイート',
  419. TURN_OFF_RETWEETS: 'リツイートをオフにする',
  420. TURN_ON_RETWEETS: 'リツイートをオンにする',
  421. },
  422. kn: {
  423. ADD_MUTED_WORD: 'ಸದ್ದಡಗಿಸಿದ ಪದವನ್ನು ಸೇರಿಸಿ',
  424. DISCOVER_MORE: 'ಇನ್ನಷ್ಟನ್ನು ಕಂಡುಕೊಳ್ಳಿ',
  425. HOME: 'ಹೋಮ್',
  426. MUTE_THIS_CONVERSATION: 'ಈ ಸಂವಾದವನ್ನು ಸದ್ದಡಗಿಸಿ',
  427. QUOTE_TWEET: 'ಟ್ವೀಟ್ ಕೋಟ್ ಮಾಡಿ',
  428. QUOTE_TWEETS: 'ಕೋಟ್ ಟ್ವೀಟ್‌ಗಳು',
  429. RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳು',
  430. SHARED_TWEETS: 'ಹಂಚಿದ ಟ್ವೀಟ್‌ಗಳು',
  431. TURN_OFF_RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳನ್ನು ಆಫ್ ಮಾಡಿ',
  432. TURN_ON_RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳನ್ನು ಆನ್ ಮಾಡಿ',
  433. },
  434. ko: {
  435. ADD_MUTED_WORD: '뮤트할 단어 추가하기',
  436. DISCOVER_MORE: '더 찾아보기',
  437. HOME: '홈',
  438. MUTE_THIS_CONVERSATION: '이 대화 뮤트하기',
  439. QUOTE_TWEET: '트윗 인용하기',
  440. QUOTE_TWEETS: '트윗 인용하기',
  441. RETWEETS: '리트윗',
  442. SHARED_TWEETS: '공유 트윗',
  443. TURN_OFF_RETWEETS: '리트윗 끄기',
  444. TURN_ON_RETWEETS: '리트윗 켜기',
  445. TWITTER: '트위터',
  446. },
  447. mr: {
  448. ADD_MUTED_WORD: 'म्यूट केलेले शब्द सामील करा',
  449. DISCOVER_MORE: 'अधिक प्रमाणामध्ये शोधा',
  450. HOME: 'होम',
  451. MUTE_THIS_CONVERSATION: 'ही चर्चा म्यूट करा',
  452. QUOTE_TWEET: 'ट्विट वर भाष्य करा',
  453. QUOTE_TWEETS: 'भाष्य ट्विट्स',
  454. RETWEETS: 'पुनर्ट्विट्स',
  455. SHARED_TWEETS: 'सामायिक ट्विट',
  456. TURN_OFF_RETWEETS: 'पुनर्ट्विट्स बंद करा',
  457. TURN_ON_RETWEETS: 'पुनर्ट्विट्स चालू करा',
  458. },
  459. ms: {
  460. ADD_MUTED_WORD: 'Tambahkan perkataan yang disenyapkan',
  461. DISCOVER_MORE: 'Temui lagi',
  462. HOME: 'Laman Utama',
  463. MUTE_THIS_CONVERSATION: 'Senyapkan perbualan ini',
  464. QUOTE_TWEET: 'Petik Tweet',
  465. QUOTE_TWEETS: 'Tweet Petikan',
  466. RETWEETS: 'Tweet semula',
  467. SHARED_TWEETS: 'Tweet Berkongsi',
  468. TURN_OFF_RETWEETS: 'Matikan Tweet semula',
  469. TURN_ON_RETWEETS: 'Hidupkan Tweet semula',
  470. },
  471. nb: {
  472. ADD_MUTED_WORD: 'Skjul nytt ord',
  473. DISCOVER_MORE: 'Oppdag mer',
  474. HOME: 'Hjem',
  475. MUTE_THIS_CONVERSATION: 'Skjul denne samtalen',
  476. QUOTE_TWEET: 'Sitat-Tweet',
  477. QUOTE_TWEETS: 'Sitat-Tweets',
  478. SHARED_TWEETS: 'Delte tweets',
  479. TURN_OFF_RETWEETS: 'Slå av Retweets',
  480. TURN_ON_RETWEETS: 'Slå på Retweets',
  481. },
  482. nl: {
  483. ADD_MUTED_WORD: 'Genegeerd woord toevoegen',
  484. DISCOVER_MORE: 'Meer ontdekken',
  485. HOME: 'Startpagina',
  486. MUTE_THIS_CONVERSATION: 'Dit gesprek negeren',
  487. QUOTE_TWEET: 'Citeer Tweet',
  488. QUOTE_TWEETS: 'Geciteerde Tweets',
  489. SHARED_TWEETS: 'Gedeelde Tweets',
  490. TURN_OFF_RETWEETS: 'Retweets uitschakelen',
  491. TURN_ON_RETWEETS: 'Retweets inschakelen',
  492. },
  493. pl: {
  494. ADD_MUTED_WORD: 'Dodaj wyciszone słowo',
  495. DISCOVER_MORE: 'Odkryj więcej',
  496. HOME: 'Główna',
  497. MUTE_THIS_CONVERSATION: 'Wycisz tę rozmowę',
  498. QUOTE_TWEET: 'Cytuj Tweeta',
  499. QUOTE_TWEETS: 'Cytaty z Tweeta',
  500. RETWEETS: 'Tweety podane dalej',
  501. SHARED_TWEETS: 'Udostępnione Tweety',
  502. TURN_OFF_RETWEETS: 'Wyłącz Tweety podane dalej',
  503. TURN_ON_RETWEETS: 'Włącz Tweety podane dalej',
  504. },
  505. pt: {
  506. ADD_MUTED_WORD: 'Adicionar palavra silenciada',
  507. DISCOVER_MORE: 'Descubra mais',
  508. HOME: 'Página Inicial',
  509. MUTE_THIS_CONVERSATION: 'Silenciar esta conversa',
  510. QUOTE_TWEET: 'Comentar o Tweet',
  511. QUOTE_TWEETS: 'Tweets com comentário',
  512. SHARED_TWEETS: 'Tweets Compartilhados',
  513. TURN_OFF_RETWEETS: 'Desativar Retweets',
  514. TURN_ON_RETWEETS: 'Ativar Retweets',
  515. },
  516. ro: {
  517. ADD_MUTED_WORD: 'Adaugă cuvântul ignorat',
  518. DISCOVER_MORE: 'Descoperă mai mult',
  519. HOME: 'Pagina principală',
  520. MUTE_THIS_CONVERSATION: 'Ignoră această conversație',
  521. QUOTE_TWEET: 'Citează Tweetul',
  522. QUOTE_TWEETS: 'Tweeturi cu citat',
  523. RETWEETS: 'Retweeturi',
  524. SHARED_TWEETS: 'Tweeturi partajate',
  525. TURN_OFF_RETWEETS: 'Dezactivează Retweeturile',
  526. TURN_ON_RETWEETS: 'Activează Retweeturile',
  527. },
  528. ru: {
  529. ADD_MUTED_WORD: 'Добавить игнорируемое слово',
  530. DISCOVER_MORE: 'Узнать больше',
  531. HOME: 'Главная',
  532. MUTE_THIS_CONVERSATION: 'Игнорировать эту переписку',
  533. QUOTE_TWEET: 'Цитировать',
  534. QUOTE_TWEETS: 'Твиты с цитатами',
  535. RETWEETS: 'Ретвиты',
  536. SHARED_TWEETS: 'Общие твиты',
  537. TURN_OFF_RETWEETS: 'Отключить ретвиты',
  538. TURN_ON_RETWEETS: 'Включить ретвиты',
  539. TWITTER: 'Твиттер',
  540. },
  541. sk: {
  542. ADD_MUTED_WORD: 'Pridať stíšené slovo',
  543. DISCOVER_MORE: 'Objaviť viac',
  544. HOME: 'Domov',
  545. MUTE_THIS_CONVERSATION: 'Stíšiť túto konverzáciu',
  546. QUOTE_TWEET: 'Tweet s citátom',
  547. QUOTE_TWEETS: 'Tweety s citátom',
  548. RETWEETS: 'Retweety',
  549. SHARED_TWEETS: 'Zdieľané Tweety',
  550. TURN_OFF_RETWEETS: 'Vypnúť retweety',
  551. TURN_ON_RETWEETS: 'Zapnúť retweety',
  552. },
  553. sr: {
  554. ADD_MUTED_WORD: 'Додај игнорисану реч',
  555. DISCOVER_MORE: 'Откриј више',
  556. HOME: 'Почетна',
  557. MUTE_THIS_CONVERSATION: 'Игнориши овај разговор',
  558. QUOTE_TWEET: 'твит са цитатом',
  559. QUOTE_TWEETS: 'твит(ов)а са цитатом',
  560. RETWEETS: 'Ретвитови',
  561. SHARED_TWEETS: 'Дељени твитови',
  562. TURN_OFF_RETWEETS: 'Искључи ретвитове',
  563. TURN_ON_RETWEETS: 'Укључи ретвитове',
  564. TWITTER: 'Твитер',
  565. },
  566. sv: {
  567. ADD_MUTED_WORD: 'Lägg till ignorerat ord',
  568. DISCOVER_MORE: 'Upptäck mer',
  569. HOME: 'Hem',
  570. MUTE_THIS_CONVERSATION: 'Ignorera den här konversationen',
  571. QUOTE_TWEET: 'Citera Tweet',
  572. QUOTE_TWEETS: 'Citat-tweets',
  573. SHARED_TWEETS: 'Delade tweetsen',
  574. TURN_OFF_RETWEETS: 'Stäng av Retweets',
  575. TURN_ON_RETWEETS: 'Slå på Retweets',
  576. },
  577. ta: {
  578. ADD_MUTED_WORD: 'செயல்மறைத்த வார்த்தையைச் சேர்',
  579. DISCOVER_MORE: 'மேலும் கண்டறியவும்',
  580. HOME: 'முகப்பு',
  581. MUTE_THIS_CONVERSATION: 'இந்த உரையாடலை செயல்மறை',
  582. QUOTE_TWEET: 'ட்விட்டை மேற்கோள் காட்டு',
  583. QUOTE_TWEETS: 'மேற்கோள் கீச்சுகள்',
  584. RETWEETS: 'மறுகீச்சுகள்',
  585. SHARED_TWEETS: 'பகிரப்பட்ட ட்வீட்டுகள்',
  586. TURN_OFF_RETWEETS: 'மறுகீச்சுகளை அணை',
  587. TURN_ON_RETWEETS: 'மறுகீச்சுகளை இயக்கு',
  588. },
  589. th: {
  590. ADD_MUTED_WORD: 'เพิ่มคำที่ซ่อน',
  591. DISCOVER_MORE: 'ค้นหาเพิ่มเติม',
  592. HOME: 'หน้าแรก',
  593. MUTE_THIS_CONVERSATION: 'ซ่อนบทสนทนานี้',
  594. QUOTE_TWEET: 'อ้างอิงทวีต',
  595. QUOTE_TWEETS: 'ทวีตและคำพูด',
  596. RETWEETS: 'รีทวีต',
  597. SHARED_TWEETS: 'ทวีตที่แชร์',
  598. TURN_OFF_RETWEETS: 'ปิดรีทวีต',
  599. TURN_ON_RETWEETS: 'เปิดรีทวีต',
  600. TWITTER: 'ทวิตเตอร์',
  601. },
  602. tr: {
  603. ADD_MUTED_WORD: 'Sessize alınacak kelime ekle',
  604. DISCOVER_MORE: 'Daha fazlasını keşfet',
  605. HOME: 'Anasayfa',
  606. MUTE_THIS_CONVERSATION: 'Bu sohbeti sessize al',
  607. QUOTE_TWEET: 'Tweeti Alıntıla',
  608. QUOTE_TWEETS: 'Alıntı Tweetler',
  609. RETWEETS: 'Retweetler',
  610. SHARED_TWEETS: 'Paylaşılan Tweetler',
  611. TURN_OFF_RETWEETS: 'Retweetleri kapat',
  612. TURN_ON_RETWEETS: 'Retweetleri aç',
  613. },
  614. uk: {
  615. ADD_MUTED_WORD: 'Додати слово до списку ігнорування',
  616. DISCOVER_MORE: 'Дізнавайтеся більше',
  617. HOME: 'Головна',
  618. MUTE_THIS_CONVERSATION: 'Ігнорувати цю розмову',
  619. QUOTE_TWEET: 'Цитувати твіт',
  620. QUOTE_TWEETS: 'Цитовані твіти',
  621. RETWEETS: 'Ретвіти',
  622. SHARED_TWEETS: 'Спільні твіти',
  623. TURN_OFF_RETWEETS: 'Вимкнути ретвіти',
  624. TURN_ON_RETWEETS: 'Увімкнути ретвіти',
  625. TWITTER: 'Твіттер',
  626. },
  627. ur: {
  628. ADD_MUTED_WORD: 'میوٹ شدہ لفظ شامل کریں',
  629. DISCOVER_MORE: 'مزید دریافت کریں',
  630. HOME: 'ہوم',
  631. MUTE_THIS_CONVERSATION: 'اس گفتگو کو میوٹ کریں',
  632. QUOTE_TWEET: 'ٹویٹ کا حوالہ دیں',
  633. QUOTE_TWEETS: 'ٹویٹ کو نقل کرو',
  634. RETWEETS: 'ریٹویٹس',
  635. SHARED_TWEETS: 'مشترکہ ٹویٹس',
  636. TURN_OFF_RETWEETS: 'ری ٹویٹس غیر فعال کریں',
  637. TURN_ON_RETWEETS: 'ری ٹویٹس غیر فعال کریں',
  638. TWITTER: 'ٹوئٹر',
  639. },
  640. vi: {
  641. ADD_MUTED_WORD: 'Thêm từ tắt tiếng',
  642. DISCOVER_MORE: 'Khám phá thêm',
  643. HOME: 'Trang chủ',
  644. MUTE_THIS_CONVERSATION: 'Tắt tiếng cuộc trò chuyện này',
  645. QUOTE_TWEET: 'Trích dẫn Tweet',
  646. QUOTE_TWEETS: 'Tweet trích dẫn',
  647. RETWEETS: 'Các Tweet lại',
  648. SHARED_TWEETS: 'Tweet được chia sẻ',
  649. TURN_OFF_RETWEETS: 'Tắt Tweet lại',
  650. TURN_ON_RETWEETS: 'Bật Tweet lại',
  651. },
  652. 'zh-Hant': {
  653. ADD_MUTED_WORD: '加入靜音文字',
  654. DISCOVER_MORE: '探索更多',
  655. HOME: '首頁',
  656. MUTE_THIS_CONVERSATION: '將此對話靜音',
  657. QUOTE_TWEET: '引用推文',
  658. QUOTE_TWEETS: '引用的推文',
  659. RETWEETS: '轉推',
  660. SHARED_TWEETS: '分享的推文',
  661. TURN_OFF_RETWEETS: '關閉轉推',
  662. TURN_ON_RETWEETS: '開啟轉推',
  663. },
  664. zh: {
  665. ADD_MUTED_WORD: '添加要隐藏的字词',
  666. DISCOVER_MORE: '发现更多',
  667. HOME: '主页',
  668. MUTE_THIS_CONVERSATION: '隐藏此对话',
  669. QUOTE_TWEET: '引用推文',
  670. QUOTE_TWEETS: '引用推文',
  671. RETWEETS: '转推',
  672. SHARED_TWEETS: '分享的推文',
  673. TURN_OFF_RETWEETS: '关闭转推',
  674. TURN_ON_RETWEETS: '开启转推',
  675. },
  676. }
  677.  
  678. /**
  679. * @param {import("./types").LocaleKey} code
  680. * @returns {string}
  681. */
  682. function getString(code) {
  683. return (locales[lang] || locales['en'])[code] || locales['en'][code];
  684. }
  685. //#endregion
  686.  
  687. //#region Config & variables
  688. /** @enum {string} */
  689. const PagePaths = {
  690. ADD_MUTED_WORD: '/settings/add_muted_keyword',
  691. BOOKMARKS: '/i/bookmarks',
  692. COMPOSE_MESSAGE: '/messages/compose',
  693. COMPOSE_TWEET: '/compose/tweet',
  694. CONNECT: '/i/connect',
  695. CUSTOMIZE_YOUR_VIEW: '/i/display',
  696. HOME: '/home',
  697. NOTIFICATION_TIMELINE: '/i/timeline',
  698. PROFILE_SETTINGS: '/settings/profile',
  699. SEARCH: '/search',
  700. }
  701.  
  702. /** @enum {string} */
  703. const Selectors = {
  704. BLOCK_MENU_ITEM: '[data-testid="block"]',
  705. DESKTOP_TIMELINE_HEADER: 'div[data-testid="primaryColumn"] > div > div:first-of-type',
  706. DISPLAY_DONE_BUTTON_DESKTOP: '#layers div[role="button"]:not([aria-label])',
  707. DISPLAY_DONE_BUTTON_MOBILE: 'main div[role="button"]:not([aria-label])',
  708. DOGE_LOGO_PATH: 'svg pattern + path[fill]',
  709. MESSAGES_DRAWER: 'div[data-testid="DMDrawer"]',
  710. MODAL_TIMELINE: '#layers section > h1 + div[aria-label] > div',
  711. MOBILE_TIMELINE_HEADER_OLD: 'header > div:nth-of-type(2) > div:first-of-type',
  712. MOBILE_TIMELINE_HEADER_NEW: 'div[data-testid="TopNavBar"]',
  713. NAV_HOME_LINK: 'a[data-testid="AppTabBar_Home_Link"]',
  714. PRIMARY_COLUMN: 'div[data-testid="primaryColumn"]',
  715. PRIMARY_NAV_DESKTOP: 'header nav',
  716. PRIMARY_NAV_MOBILE: '#layers nav',
  717. PROMOTED_TWEET_CONTAINER: '[data-testid="placementTracking"]',
  718. SIDEBAR: 'div[data-testid="sidebarColumn"]',
  719. SIDEBAR_WRAPPERS: 'div[data-testid="sidebarColumn"] > div > div > div > div > div',
  720. TIMELINE: 'div[data-testid="primaryColumn"] section > h1 + div[aria-label] > div',
  721. TIMELINE_HEADING: 'h2[role="heading"]',
  722. TWEET: '[data-testid="tweet"]',
  723. VERIFIED_TICK: 'svg[data-testid="icon-verified"]',
  724. }
  725.  
  726. /** @enum {string} */
  727. const Svgs = {
  728. BLUE_LOGO_PATH: 'M16.5 3H2v18h15c3.038 0 5.5-2.46 5.5-5.5 0-1.4-.524-2.68-1.385-3.65-.08-.09-.089-.22-.023-.32.574-.87.908-1.91.908-3.03C22 5.46 19.538 3 16.5 3zm-.796 5.99c.457-.05.892-.17 1.296-.35-.302.45-.684.84-1.125 1.15.004.1.006.19.006.29 0 2.94-2.269 6.32-6.421 6.32-1.274 0-2.46-.37-3.459-1 .177.02.357.03.539.03 1.057 0 2.03-.35 2.803-.95-.988-.02-1.821-.66-2.109-1.54.138.03.28.04.425.04.206 0 .405-.03.595-.08-1.033-.2-1.811-1.1-1.811-2.18v-.03c.305.17.652.27 1.023.28-.606-.4-1.004-1.08-1.004-1.85 0-.4.111-.78.305-1.11 1.113 1.34 2.775 2.22 4.652 2.32-.038-.17-.058-.33-.058-.51 0-1.23 1.01-2.22 2.256-2.22.649 0 1.235.27 1.647.7.514-.1.997-.28 1.433-.54-.168.52-.526.96-.992 1.23z',
  729. HOME: '<g><path d="M12 9c-2.209 0-4 1.791-4 4s1.791 4 4 4 4-1.791 4-4-1.791-4-4-4zm0 6c-1.105 0-2-.895-2-2s.895-2 2-2 2 .895 2 2-.895 2-2 2zm0-13.304L.622 8.807l1.06 1.696L3 9.679V19.5C3 20.881 4.119 22 5.5 22h13c1.381 0 2.5-1.119 2.5-2.5V9.679l1.318.824 1.06-1.696L12 1.696zM19 19.5c0 .276-.224.5-.5.5h-13c-.276 0-.5-.224-.5-.5V8.429l7-4.375 7 4.375V19.5z"></path></g>',
  730. MUTE: '<g><path d="M18 6.59V1.2L8.71 7H5.5C4.12 7 3 8.12 3 9.5v5C3 15.88 4.12 17 5.5 17h2.09l-2.3 2.29 1.42 1.42 15.5-15.5-1.42-1.42L18 6.59zm-8 8V8.55l6-3.75v3.79l-6 6zM5 9.5c0-.28.22-.5.5-.5H8v6H5.5c-.28 0-.5-.22-.5-.5v-5zm6.5 9.24l1.45-1.45L16 19.2V14l2 .02v8.78l-6.5-4.06z"></path></g>',
  731. RETWEET: '<g><path d="M4.5 3.88l4.432 4.14-1.364 1.46L5.5 7.55V16c0 1.1.896 2 2 2H13v2H7.5c-2.209 0-4-1.79-4-4V7.55L1.432 9.48.068 8.02 4.5 3.88zM16.5 6H11V4h5.5c2.209 0 4 1.79 4 4v8.45l2.068-1.93 1.364 1.46-4.432 4.14-4.432-4.14 1.364-1.46 2.068 1.93V8c0-1.1-.896-2-2-2z"></path></g>',
  732. RETWEETS_OFF: '<g><path d="M3.707 21.707l18-18-1.414-1.414-2.088 2.088C17.688 4.137 17.11 4 16.5 4H11v2h5.5c.028 0 .056 0 .084.002l-10.88 10.88c-.131-.266-.204-.565-.204-.882V7.551l2.068 1.93 1.365-1.462L4.5 3.882.068 8.019l1.365 1.462 2.068-1.93V16c0 .871.278 1.677.751 2.334l-1.959 1.959 1.414 1.414zM18.5 9h2v7.449l2.068-1.93 1.365 1.462-4.433 4.137-4.432-4.137 1.365-1.462 2.067 1.93V9zm-8.964 9l-2 2H13v-2H9.536z"></path></g>',
  733. }
  734.  
  735. const THEME_COLORS = new Set([
  736. 'rgb(29, 155, 240)', // blue
  737. 'rgb(255, 212, 0)', // yellow
  738. 'rgb(244, 33, 46)', // pink
  739. 'rgb(120, 86, 255)', // purple
  740. 'rgb(255, 122, 0)', // orange
  741. 'rgb(0, 186, 124)', // green
  742. ])
  743. // Matches any notification count at the start of the title
  744. const TITLE_NOTIFICATION_RE = /^\(\d+\+?\) /
  745. // twitter.com/user and its sub-URLs put @user in the title
  746. const TITLE_PROFILE_USERNAME_RE_LTR = /@([a-zA-Z\d_]{1,20})/
  747. const TITLE_PROFILE_USERNAME_RE_RTL = /([a-zA-Z\d_]{1,20})@/
  748. // The initial URL when you open the Twitter Circle modal is i/circles
  749. const URL_CIRCLE_RE = /^\/i\/circles(?:\/\d+\/members(?:\/suggested)?)?\/?$/
  750. // The Communities nav item takes you to /yourusername/communities
  751. const URL_COMMUNITIES_RE = /^\/[a-zA-Z\d_]{1,20}\/communities\/?$/
  752. const URL_COMMUNITY_RE = /^\/i\/communities\/\d+(?:\/about)?\/?$/
  753. const URL_COMMUNITY_MEMBERS_RE = /^\/i\/communities\/\d+\/(?:members|moderators)\/?$/
  754. const URL_DISCOVER_COMMUNITIES_RE = /^\/i\/communities\/suggested\/?/
  755. const URL_LIST_RE = /\/i\/lists\/\d+\/?$/
  756. const URL_PHOTO_RE = /photo\/\d\/?$/
  757. // Matches URLs which show one of the tabs on a user profile page
  758. const URL_PROFILE_RE = /^\/([a-zA-Z\d_]{1,20})(?:\/(with_replies|media|likes)\/?|\/)?$/
  759. // Matches URLs which show a user's Followers you know / Followers / Following tab
  760. const URL_PROFILE_FOLLOWS_RE = /^\/[a-zA-Z\d_]{1,20}\/(follow(?:ing|ers|ers_you_follow))\/?$/
  761. const URL_TWEET_ID_RE = /\/status\/(\d+)\/?$/
  762.  
  763. /**
  764. * The quoted Tweet associated with a caret menu that's just been opened.
  765. * @type {import("./types").QuotedTweet}
  766. */
  767. let quotedTweet = null
  768.  
  769. /** `true` when a 'Block @${user}' menu item was seen in the last popup. */
  770. let blockMenuItemSeen = false
  771.  
  772. /** Notification count in the title (including trailing space), e.g. `'(1) '`. */
  773. let currentNotificationCount = ''
  774.  
  775. /** Title of the current page, without the `' / Twitter'` suffix. */
  776. let currentPage = ''
  777.  
  778. /** Current `location.pathname`. */
  779. let currentPath = ''
  780.  
  781. /**
  782. * CSS rule in the React Native stylesheet which defines the Chirp font-family
  783. * and fallbacks for the whole app.
  784. * @type {CSSStyleRule}
  785. */
  786. let fontFamilyRule = null
  787.  
  788. /** @type {string} */
  789. let fontSize = null
  790.  
  791. /** Set to `true` when a Home/Following heading or Home nav link is used. */
  792. let homeNavigationIsBeingUsed = false
  793.  
  794. /** Set to `true` when the Twitter Circle modal is open. */
  795. let isCircleModalOpen = false
  796.  
  797. /** Set to `true` when the media modal is open on desktop. */
  798. let isDesktopMediaModalOpen = false
  799.  
  800. /**
  801. * Cache for the last page title which was used for the main timeline.
  802. * @type {string}
  803. */
  804. let lastMainTimelineTitle = null
  805.  
  806. /**
  807. * MutationObservers active on the current modal.
  808. * @type {import("./types").Disconnectable[]}
  809. */
  810. let modalObservers = []
  811.  
  812. /**
  813. * MutationObservers active on the current page, or anything else we want to
  814. * clean up when the user moves off the current page.
  815. * @type {import("./types").Disconnectable[]}
  816. */
  817. let pageObservers = []
  818.  
  819. /**
  820. * Title for the fake timeline used to separate out retweets and quote tweets.
  821. * @type {string}
  822. */
  823. let separatedTweetsTimelineTitle = null
  824.  
  825. /**
  826. * The current "Color" setting, which can be changed in "Customize your view".
  827. * @type {string}
  828. */
  829. let themeColor = null
  830.  
  831. /**
  832. * `true` when "For you" was the last tab selected on the main timeline.
  833. */
  834. let wasForYouTabSelected = false
  835.  
  836. function isOnBookmarksPage() {
  837. return currentPath == PagePaths.BOOKMARKS
  838. }
  839.  
  840. function isOnCommunitiesPage() {
  841. return URL_COMMUNITIES_RE.test(currentPath)
  842. }
  843.  
  844. function isOnCommunityPage() {
  845. return URL_COMMUNITY_RE.test(currentPath)
  846. }
  847.  
  848. function isOnCommunityMembersPage() {
  849. return URL_COMMUNITY_MEMBERS_RE.test(currentPath)
  850. }
  851.  
  852. function isOnDiscoverCommunitiesPage() {
  853. return URL_DISCOVER_COMMUNITIES_RE.test(currentPath)
  854. }
  855.  
  856. function isOnExplorePage() {
  857. return currentPath.startsWith('/explore')
  858. }
  859.  
  860. function isOnFollowListPage() {
  861. return URL_PROFILE_FOLLOWS_RE.test(currentPath)
  862. }
  863.  
  864. function isOnHomeTimeline() {
  865. return currentPage == getString('HOME')
  866. }
  867.  
  868. function isOnIndividualTweetPage() {
  869. return URL_TWEET_ID_RE.test(currentPath)
  870. }
  871.  
  872. function isOnListPage() {
  873. return URL_LIST_RE.test(currentPath)
  874. }
  875.  
  876. function isOnMainTimelinePage() {
  877. return currentPath == PagePaths.HOME || (
  878. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW &&
  879. isOnHomeTimeline() ||
  880. isOnSeparatedTweetsTimeline()
  881. )
  882. }
  883.  
  884. function isOnNotificationsPage() {
  885. return currentPath.startsWith('/notifications')
  886. }
  887.  
  888. function isOnProfilePage() {
  889. let profilePathUsername = currentPath.match(URL_PROFILE_RE)?.[1]
  890. let titleUsername = currentPage.match(ltr ? TITLE_PROFILE_USERNAME_RE_LTR : TITLE_PROFILE_USERNAME_RE_RTL)?.[1]
  891. // @user in the title helps guard against false positives for twitter.com/user
  892. return titleUsername != null && profilePathUsername != null && titleUsername == profilePathUsername
  893. }
  894.  
  895. function isOnQuoteTweetsPage() {
  896. return currentPath.endsWith('/retweets/with_comments')
  897. }
  898.  
  899. function isOnSearchPage() {
  900. return currentPath.startsWith('/search') || currentPath.startsWith('/hashtag/')
  901. }
  902.  
  903. function isOnSeparatedTweetsTimeline() {
  904. return currentPage == separatedTweetsTimelineTitle
  905. }
  906.  
  907. function isOnTopicsPage() {
  908. return currentPath != '/topics' && Boolean(currentPath.match(/\/topics(\/|$)/))
  909. }
  910.  
  911. function shouldHideSidebar() {
  912. return isOnExplorePage() || isOnDiscoverCommunitiesPage()
  913. }
  914. //#endregion
  915.  
  916. //#region Utility functions
  917. /**
  918. * @param {string} role
  919. * @return {HTMLStyleElement}
  920. */
  921. function addStyle(role) {
  922. let $style = document.createElement('style')
  923. $style.dataset.insertedBy = 'control-panel-for-twitter'
  924. $style.dataset.role = role
  925. document.head.appendChild($style)
  926. return $style
  927. }
  928.  
  929. /**
  930. * @param {Element} $svg
  931. */
  932. function blueCheck($svg) {
  933. if (!$svg) {
  934. warn('blueCheck was given', $svg)
  935. return
  936. }
  937. $svg.classList.add('tnt_blue_check')
  938. // Safari doesn't support using `d: path(…)` to replace paths in an SVG, so
  939. // we have to manually patch the path in it.
  940. if (isSafari) {
  941. $svg.firstElementChild.firstElementChild.setAttribute('d', Svgs.BLUE_LOGO_PATH)
  942. }
  943. }
  944.  
  945. /**
  946. * @param {string} str
  947. * @return {string}
  948. */
  949. function dedent(str) {
  950. str = str.replace(/^[ \t]*\r?\n/, '')
  951. let indent = /^[ \t]+/m.exec(str)
  952. if (indent) str = str.replace(new RegExp('^' + indent[0], 'gm'), '')
  953. return str.replace(/(\r?\n)[ \t]+$/, '$1')
  954. }
  955.  
  956. /**
  957. * @param {string} name
  958. * @param {import("./types").Disconnectable[]} observers
  959. * @param {string?} type
  960. */
  961. function disconnectObserver(name, observers, type = 'observer') {
  962. for (let i = observers.length -1; i >= 0; i--) {
  963. let observer = observers[i]
  964. if ('name' in observer && observer.name == name) {
  965. observer.disconnect()
  966. observers.splice(i, 1)
  967. log(`disconnected ${name} ${type}`)
  968. }
  969. }
  970. }
  971.  
  972. function disconnectModalObserver(name) {
  973. disconnectObserver(name, modalObservers)
  974. }
  975.  
  976. function disconnectAllModalObservers() {
  977. if (modalObservers.length > 0) {
  978. log(
  979. `disconnecting ${modalObservers.length} modal observer${s(modalObservers.length)}`,
  980. modalObservers.map(observer => observer['name'])
  981. )
  982. modalObservers.forEach(observer => observer.disconnect())
  983. modalObservers = []
  984. }
  985. }
  986.  
  987. function disconnectPageObserver(name) {
  988. disconnectObserver(name, pageObservers, 'page observer')
  989. }
  990.  
  991. /**
  992. * @param {string} selector
  993. * @param {{
  994. * name?: string
  995. * stopIf?: () => boolean
  996. * timeout?: number
  997. * context?: Document | HTMLElement
  998. * }?} options
  999. * @returns {Promise<HTMLElement | null>}
  1000. */
  1001. function getElement(selector, {
  1002. name = null,
  1003. stopIf = null,
  1004. timeout = Infinity,
  1005. context = document,
  1006. } = {}) {
  1007. return new Promise((resolve) => {
  1008. let startTime = Date.now()
  1009. let rafId
  1010. let timeoutId
  1011.  
  1012. function stop($element, reason) {
  1013. if ($element == null) {
  1014. warn(`stopped waiting for ${name || selector} after ${reason}`)
  1015. }
  1016. else if (Date.now() > startTime) {
  1017. log(`${name || selector} appeared after ${Date.now() - startTime}ms`)
  1018. }
  1019. if (rafId) {
  1020. cancelAnimationFrame(rafId)
  1021. }
  1022. if (timeoutId) {
  1023. clearTimeout(timeoutId)
  1024. }
  1025. resolve($element)
  1026. }
  1027.  
  1028. if (timeout !== Infinity) {
  1029. timeoutId = setTimeout(stop, timeout, null, `${timeout}ms timeout`)
  1030. }
  1031.  
  1032. function queryElement() {
  1033. let $element = context.querySelector(selector)
  1034. if ($element) {
  1035. stop($element)
  1036. }
  1037. else if (stopIf?.() === true) {
  1038. stop(null, 'stopIf condition met')
  1039. }
  1040. else {
  1041. rafId = requestAnimationFrame(queryElement)
  1042. }
  1043. }
  1044.  
  1045. queryElement()
  1046. })
  1047. }
  1048.  
  1049. function log(...args) {
  1050. if (debug) {
  1051. console.log(`${currentPage ? `(${
  1052. currentPage.length < 70 ? currentPage : currentPage.slice(0, 70) + '…'
  1053. })` : ''}`, ...args)
  1054. }
  1055. }
  1056.  
  1057. function warn(...args) {
  1058. if (debug) {
  1059. console.log(`❗ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1060. }
  1061. }
  1062.  
  1063. function error(...args) {
  1064. console.log(`❌ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1065. }
  1066.  
  1067. /**
  1068. * @param {() => boolean} condition
  1069. * @returns {() => boolean}
  1070. */
  1071. function not(condition) {
  1072. return () => !condition()
  1073. }
  1074.  
  1075. /**
  1076. * Convenience wrapper for the MutationObserver API - the callback is called
  1077. * immediately to support using an observer and its options as a trigger for any
  1078. * change, without looking at MutationRecords.
  1079. * @param {Node} $element
  1080. * @param {MutationCallback} callback
  1081. * @param {string} name
  1082. * @param {MutationObserverInit} options
  1083. * @return {import("./types").NamedMutationObserver}
  1084. */
  1085. function observeElement($element, callback, name = '', options = {childList: true}) {
  1086. if (name) {
  1087. if (options.childList && callback.length > 0) {
  1088. log(`observing ${name}`, $element)
  1089. } else {
  1090. log (`observing ${name}`)
  1091. }
  1092. }
  1093.  
  1094. let observer = new MutationObserver(callback)
  1095. callback([], observer)
  1096. observer.observe($element, options)
  1097. observer['name'] = name
  1098. return observer
  1099. }
  1100.  
  1101. /**
  1102. * @param {string} page
  1103. * @returns {() => boolean}
  1104. */
  1105. function pageIsNot(page) {
  1106. return () => page != currentPage
  1107. }
  1108.  
  1109. /**
  1110. * @param {string} path
  1111. * @returns {() => boolean}
  1112. */
  1113. function pathIsNot(path) {
  1114. return () => path != currentPath
  1115. }
  1116.  
  1117. /**
  1118. * @param {number} n
  1119. * @returns {string}
  1120. */
  1121. function s(n) {
  1122. return n == 1 ? '' : 's'
  1123. }
  1124.  
  1125. function storeConfigChanges(changes) {
  1126. window.postMessage({type: 'tntConfigChange', changes})
  1127. }
  1128. //#endregion
  1129.  
  1130. //#region Global observers
  1131. const checkReactNativeStylesheet = (() => {
  1132. let startTime = Date.now()
  1133.  
  1134. return function checkReactNativeStylesheet() {
  1135. let $style = /** @type {HTMLStyleElement} */ (document.querySelector('style#react-native-stylesheet'))
  1136. if (!$style) {
  1137. warn('React Native stylesheet not found')
  1138. return
  1139. }
  1140.  
  1141. for (let rule of $style.sheet.cssRules) {
  1142. if (!(rule instanceof CSSStyleRule)) continue
  1143.  
  1144. if (fontFamilyRule == null &&
  1145. rule.style.fontFamily &&
  1146. rule.style.fontFamily.includes('TwitterChirp')) {
  1147. fontFamilyRule = rule
  1148. log('found Chirp fontFamily CSS rule in React Native stylesheet')
  1149. configureFont()
  1150. }
  1151.  
  1152. if (themeColor == null &&
  1153. rule.style.backgroundColor &&
  1154. THEME_COLORS.has(rule.style.backgroundColor)) {
  1155. themeColor = rule.style.backgroundColor
  1156. log(`found initial theme color in React Native stylesheet: ${themeColor}`)
  1157. configureThemeCss()
  1158. }
  1159. }
  1160.  
  1161. let elapsedTime = Date.now() - startTime
  1162. if (fontFamilyRule == null || themeColor == null) {
  1163. if (elapsedTime < 3000) {
  1164. setTimeout(checkReactNativeStylesheet, 100)
  1165. } else {
  1166. warn(`stopped checking React Native stylesheet after ${elapsedTime}ms`)
  1167. }
  1168. } else {
  1169. log(`finished checking React Native stylesheet in ${elapsedTime}ms`)
  1170. }
  1171. }
  1172. })()
  1173.  
  1174. /**
  1175. * When the "Background" setting is changed in "Customize your view", <body>'s
  1176. * backgroundColor is changed and the app is re-rendered, so we need to
  1177. * re-process the current page.
  1178. */
  1179. function observeBodyBackgroundColor() {
  1180. let lastBackgroundColor = null
  1181.  
  1182. observeElement($body, () => {
  1183. let backgroundColor = $body.style.backgroundColor
  1184. if (backgroundColor == lastBackgroundColor) return
  1185.  
  1186. $body.classList.toggle('Default', backgroundColor == 'rgb(255, 255, 255)')
  1187. $body.classList.toggle('Dim', backgroundColor == 'rgb(21, 32, 43)')
  1188. $body.classList.toggle('LightsOut', backgroundColor == 'rgb(0, 0, 0)')
  1189.  
  1190. if (lastBackgroundColor != null) {
  1191. log('Background setting changed - re-processing current page')
  1192. observePopups()
  1193. processCurrentPage()
  1194. }
  1195. lastBackgroundColor = backgroundColor
  1196. }, '<body> style attribute for background colour changes', {
  1197. attributes: true,
  1198. attributeFilter: ['style']
  1199. })
  1200. }
  1201.  
  1202. /**
  1203. * @param {Element} $tabContent
  1204. * @param {import("./types").Disconnectable[]} observers
  1205. * @param {(name: string) => void} disconnect
  1206. */
  1207. function observeTwitterCircleTabContent($tabContent, observers, disconnect) {
  1208. disconnect('circle tab content')
  1209. // The Recommended tab replaces its initial user list with a typeahead
  1210. // dropdown when you use the input, and reverts if you clear it.
  1211. observers.push(observeElement($tabContent, () => {
  1212. let $userList = /** @type {HTMLElement} */ ($tabContent.querySelector(':scope > div:last-child:not(:first-child), div[id^="typeaheadDropdown"]'))
  1213. if ($userList) {
  1214. disconnect('user list')
  1215. observers.push(observeElement($userList, () => {
  1216. processBlueChecks($userList)
  1217. }, 'user list'))
  1218. } else {
  1219. warn('could not find circle user list')
  1220. }
  1221. }, 'circle tab content'))
  1222. }
  1223.  
  1224. async function observeCircleModal() {
  1225. let $viewport = await getElement('div[data-viewportview="true"]', {
  1226. name: 'circle modal viewport',
  1227. stopIf: () => !isCircleModalOpen,
  1228. })
  1229.  
  1230. if ($viewport == null) return
  1231.  
  1232. modalObservers.push(observeElement($viewport, (mutations) => {
  1233. // Ignore loading indicators on initial load of each tab
  1234. if (!mutations.length || mutations.some(mutation => mutation.addedNodes[0]?.querySelector('svg circle'))) {
  1235. return
  1236. }
  1237. // The modal version doesn't have a separate container for tab content, it's
  1238. // a sibling of the tabs.
  1239. observeTwitterCircleTabContent($viewport.lastElementChild, modalObservers, disconnectModalObserver)
  1240. }, 'circle modal viewport'))
  1241. }
  1242.  
  1243. /**
  1244. * When the "Color" setting is changed in "Customize your view", the app
  1245. * re-renders from a certain point, so we need to re-process the current page.
  1246. */
  1247. async function observeColor() {
  1248. let $colorRerenderBoundary = await getElement('#react-root > div > div')
  1249.  
  1250. observeElement($colorRerenderBoundary, async () => {
  1251. if (location.pathname != PagePaths.CUSTOMIZE_YOUR_VIEW) return
  1252.  
  1253. let $doneButton = await getElement(desktop ? Selectors.DISPLAY_DONE_BUTTON_DESKTOP : Selectors.DISPLAY_DONE_BUTTON_MOBILE, {
  1254. name: 'Done button',
  1255. stopIf: not(() => location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW),
  1256. })
  1257. if (!$doneButton) return
  1258.  
  1259. let color = getComputedStyle($doneButton).backgroundColor
  1260. if (color == themeColor) return
  1261.  
  1262. log('Color setting changed - re-processing current page')
  1263. themeColor = color
  1264. configureThemeCss()
  1265. observePopups()
  1266. processCurrentPage()
  1267. }, 'Color change re-render boundary')
  1268. }
  1269.  
  1270. /**
  1271. * When the "Font size" setting is changed in "Customize your view" on desktop,
  1272. * `<html>`'s fontSize is changed and the app is re-rendered.
  1273. */
  1274. const observeHtmlFontSize = (() => {
  1275. /** @type {MutationObserver} */
  1276. let fontSizeObserver
  1277.  
  1278. return function observeHtmlFontSize() {
  1279. if (fontSizeObserver) {
  1280. fontSizeObserver.disconnect()
  1281. fontSizeObserver = null
  1282. }
  1283.  
  1284. if (mobile) return
  1285.  
  1286. let lastOverflow = ''
  1287.  
  1288. fontSizeObserver = observeElement($html, () => {
  1289. if (!$html.style.fontSize) return
  1290.  
  1291. let hasFontSizeChanged = fontSize != null && $html.style.fontSize != fontSize
  1292.  
  1293. if ($html.style.fontSize != fontSize) {
  1294. fontSize = $html.style.fontSize
  1295. log(`<html> fontSize has changed to ${fontSize}`)
  1296. configureNavFontSizeCss()
  1297. }
  1298.  
  1299. // Ignore overflow changes, which happen when a dialog is shown or hidden
  1300. let hasOverflowChanged = $html.style.overflow != lastOverflow
  1301. lastOverflow = $html.style.overflow
  1302. if (!hasFontSizeChanged && hasOverflowChanged) {
  1303. log('ignoring <html> style overflow change')
  1304. return
  1305. }
  1306.  
  1307. // When you switch between the smallest "Font size" options, <html>'s
  1308. // style is updated but the font size is kept the same - re-process just
  1309. // in case.
  1310. if (hasFontSizeChanged ||
  1311. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW && fontSize == '14px') {
  1312. log('<html> style attribute changed, re-processing current page')
  1313. observePopups()
  1314. processCurrentPage()
  1315. }
  1316. }, '<html> style attribute for font size changes', {
  1317. attributes: true,
  1318. attributeFilter: ['style']
  1319. })
  1320. }
  1321. })()
  1322.  
  1323. async function observeDesktopModalTimeline() {
  1324. // Media modals remember if they were previously collapsed, so we could be
  1325. // waiting for the initial timeline to be either rendered or expanded.
  1326. let $initialTimeline = await getElement(Selectors.MODAL_TIMELINE, {
  1327. name: 'initial modal timeline',
  1328. stopIf: () => !isDesktopMediaModalOpen,
  1329. })
  1330.  
  1331. if ($initialTimeline == null) return
  1332.  
  1333. /**
  1334. * @param {HTMLElement} $timeline
  1335. */
  1336. function observeModalTimelineItems($timeline) {
  1337. disconnectModalObserver('modal timeline')
  1338. modalObservers.push(
  1339. observeElement($timeline, () => onTimelineChange($timeline, 'Desktop Media Modal', {hideHeadings: false}), 'modal timeline')
  1340. )
  1341.  
  1342. // If other media in the modal is clicked, the timeline is replaced.
  1343. disconnectModalObserver('modal timeline parent')
  1344. modalObservers.push(
  1345. observeElement($timeline.parentElement, (mutations) => {
  1346. mutations.forEach((mutation) => {
  1347. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1348. log('modal timeline replaced')
  1349. disconnectModalObserver('modal timeline')
  1350. modalObservers.push(
  1351. observeElement($newTimeline, () => onTimelineChange($newTimeline, 'Desktop Media Modal', {hideHeadings: false}), 'modal timeline')
  1352. )
  1353. })
  1354. })
  1355. }, 'modal timeline parent')
  1356. )
  1357. }
  1358.  
  1359. /**
  1360. * @param {HTMLElement} $timeline
  1361. */
  1362. function observeModalTimeline($timeline) {
  1363. // If the inital timeline doesn't have a style attribute it's a placeholder
  1364. if ($timeline.hasAttribute('style')) {
  1365. observeModalTimelineItems($timeline)
  1366. }
  1367. else {
  1368. log('waiting for modal timeline')
  1369. let startTime = Date.now()
  1370. modalObservers.push(
  1371. observeElement($timeline.parentElement, (mutations) => {
  1372. mutations.forEach((mutation) => {
  1373. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  1374. disconnectModalObserver('modal timeline parent')
  1375. if (Date.now() > startTime) {
  1376. log(`modal timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  1377. }
  1378. observeModalTimelineItems($timeline)
  1379. })
  1380. })
  1381. }, 'modal timeline parent')
  1382. )
  1383. }
  1384. }
  1385.  
  1386. // The modal timeline can be expanded and collapsed
  1387. let $expandedContainer = $initialTimeline.closest('[aria-expanded="true"]')
  1388. modalObservers.push(
  1389. observeElement($expandedContainer.parentElement, async (mutations) => {
  1390. if (mutations.some(mutation => mutation.removedNodes.length > 0)) {
  1391. log('modal timeline collapsed')
  1392. disconnectModalObserver('modal timeline parent')
  1393. disconnectModalObserver('modal timeline')
  1394. }
  1395. else if (mutations.some(mutation => mutation.addedNodes.length > 0)) {
  1396. log('modal timeline expanded')
  1397. let $timeline = await getElement(Selectors.MODAL_TIMELINE, {
  1398. name: 'expanded modal timeline',
  1399. stopIf: () => !isDesktopMediaModalOpen,
  1400. })
  1401. if ($timeline == null) return
  1402. observeModalTimeline($timeline)
  1403. }
  1404. }, 'collapsible modal timeline container')
  1405. )
  1406.  
  1407. observeModalTimeline($initialTimeline)
  1408. }
  1409.  
  1410. /**
  1411. * Twitter displays popups in the #layers element. It also reuses open popups
  1412. * in certain cases rather than creating one from scratch, so we also need to
  1413. * deal with nested popups, e.g. if you hover over the caret menu in a Tweet, a
  1414. * popup will be created to display a "More" tootip and clicking to open the
  1415. * menu will create a nested element in the existing popup, whereas clicking the
  1416. * caret quickly without hovering over it will display the menu in new popup.
  1417. * Use of nested popups can also differ between desktop and mobile, so features
  1418. * need to be mindful of that.
  1419. */
  1420. const observePopups = (() => {
  1421. /** @type {MutationObserver} */
  1422. let popupObserver
  1423. /** @type {WeakMap<HTMLElement, {disconnect()}>} */
  1424. let nestedObservers = new WeakMap()
  1425.  
  1426. return async function observePopups() {
  1427. if (popupObserver) {
  1428. popupObserver.disconnect()
  1429. popupObserver = null
  1430. }
  1431.  
  1432. let $layers = await getElement('#layers', {
  1433. name: 'layers',
  1434. })
  1435.  
  1436. // There can be only one
  1437. if (popupObserver) {
  1438. popupObserver.disconnect()
  1439. }
  1440.  
  1441. popupObserver = observeElement($layers, (mutations) => {
  1442. mutations.forEach((mutation) => {
  1443. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1444. let nestedObserver = onPopup($el)
  1445. if (nestedObserver) {
  1446. nestedObservers.set($el, nestedObserver)
  1447. }
  1448. })
  1449. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1450. if (nestedObservers.has($el)) {
  1451. nestedObservers.get($el).disconnect()
  1452. nestedObservers.delete($el)
  1453. }
  1454. })
  1455. })
  1456. }, 'popup container')
  1457. }
  1458. })()
  1459.  
  1460. async function observeTitle() {
  1461. let $title = await getElement('title', {name: '<title>'})
  1462. observeElement($title, () => onTitleChange($title.textContent), '<title>')
  1463. }
  1464. //#endregion
  1465.  
  1466. //#region Page observers
  1467. /**
  1468. * If a profile is blocked its media box won't appear, add a `Blocked` class to
  1469. * `<body>` to hide sidebar content.
  1470. * @param {string} currentPage
  1471. */
  1472. async function observeProfileBlockedStatus(currentPage) {
  1473. let $buttonContainer = await getElement(`[data-testid="userActions"] ~ [data-testid="placementTracking"], a[href="${PagePaths.PROFILE_SETTINGS}"]`, {
  1474. name: 'Follow / Unblock button container or Edit profile button',
  1475. stopIf: pageIsNot(currentPage),
  1476. })
  1477. if ($buttonContainer == null) return
  1478.  
  1479. if ($buttonContainer.hasAttribute('href')) {
  1480. log('on own profile page')
  1481. $body.classList.remove('Blocked')
  1482. return
  1483. }
  1484.  
  1485. pageObservers.push(
  1486. observeElement($buttonContainer, () => {
  1487. let isBlocked = (/** @type {HTMLElement} */ ($buttonContainer.querySelector('[role="button"]'))?.dataset.testid ?? '').endsWith('unblock')
  1488. $body.classList.toggle('Blocked', isBlocked)
  1489. }, 'Follow / Unblock button container')
  1490. )
  1491. }
  1492.  
  1493. /**
  1494. * If an account has never tweeted any media, add a `NoMedia` class to `<body>`
  1495. * to hide the "You might like" section which will appear where the media box
  1496. * would have been.
  1497. * @param {string} currentPage
  1498. */
  1499. async function observeProfileSidebar(currentPage) {
  1500. let $sidebarContent = await getElement(Selectors.SIDEBAR_WRAPPERS, {
  1501. name: 'profile sidebar content container',
  1502. stopIf: pageIsNot(currentPage),
  1503. })
  1504. if ($sidebarContent == null) return
  1505.  
  1506. let sidebarContentObserver = observeElement($sidebarContent, () => {
  1507. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1508. }, 'profile sidebar content container')
  1509. pageObservers.push(sidebarContentObserver)
  1510.  
  1511. // On initial appearance, the sidebar is injected with static HTML with
  1512. // spinner placeholders, which gets replaced. When this happens we need to
  1513. // observe the new content container instead.
  1514. let $sidebarContentParent = $sidebarContent.parentElement
  1515. pageObservers.push(
  1516. observeElement($sidebarContentParent, (mutations) => {
  1517. let sidebarContentReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($sidebarContent))
  1518. if (sidebarContentReplaced) {
  1519. log('profile sidebar content container replaced, observing new container')
  1520. sidebarContentObserver.disconnect()
  1521. pageObservers.splice(pageObservers.indexOf(sidebarContentObserver), 1)
  1522. $sidebarContent = /** @type {HTMLElement} */ ($sidebarContentParent.firstElementChild)
  1523. pageObservers.push(
  1524. observeElement($sidebarContent, () => {
  1525. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1526. }, 'sidebar content container')
  1527. )
  1528. }
  1529. }, 'sidebar content container parent')
  1530. )
  1531. }
  1532.  
  1533. async function observeSidebar() {
  1534. let $primaryColumn = await getElement(Selectors.PRIMARY_COLUMN, {
  1535. name: 'primary column'
  1536. })
  1537. let $sidebarContainer = $primaryColumn.parentElement
  1538. pageObservers.push(
  1539. observeElement($sidebarContainer, () => {
  1540. let $sidebar = $sidebarContainer.querySelector(Selectors.SIDEBAR)
  1541. log(`sidebar ${$sidebar ? 'appeared' : 'disappeared'}`)
  1542. $body.classList.toggle('Sidebar', Boolean($sidebar))
  1543. if ($sidebar && config.twitterBlueChecks != 'ignore' && !isOnSearchPage() && !isOnExplorePage()) {
  1544. observeSearchForm()
  1545. }
  1546. }, 'sidebar container')
  1547. )
  1548. }
  1549.  
  1550. async function observeSearchForm() {
  1551. let $searchForm = await getElement('form[role="search"]', {
  1552. name: 'search form',
  1553. stopIf: pageIsNot(currentPage),
  1554. // The sidebar on Profile pages can be really slow
  1555. timeout: 2000,
  1556. })
  1557. if (!$searchForm) return
  1558. let $results = /** @type {HTMLElement} */ ($searchForm.lastElementChild)
  1559. pageObservers.push(
  1560. observeElement($results, () => {
  1561. processBlueChecks($results)
  1562. }, 'search results', {childList: true, subtree: true})
  1563. )
  1564. }
  1565.  
  1566. /**
  1567. * @param {string} page
  1568. * @param {import("./types").TimelineOptions?} options
  1569. */
  1570. async function observeTimeline(page, options = {}) {
  1571. let {
  1572. isTabbed = false,
  1573. onTabChanged = null,
  1574. onTimelineAppeared = null,
  1575. tabbedTimelineContainerSelector = null,
  1576. timelineSelector = Selectors.TIMELINE,
  1577. } = options
  1578.  
  1579. let $timeline = await getElement(timelineSelector, {
  1580. name: 'initial timeline',
  1581. stopIf: pageIsNot(page),
  1582. })
  1583.  
  1584. if ($timeline == null) return
  1585.  
  1586. /**
  1587. * @param {HTMLElement} $timeline
  1588. */
  1589. function observeTimelineItems($timeline) {
  1590. disconnectPageObserver('timeline')
  1591. pageObservers.push(
  1592. observeElement($timeline, () => onTimelineChange($timeline, page, options), 'timeline')
  1593. )
  1594. onTimelineAppeared?.()
  1595. if (isTabbed) {
  1596. // When a tab which has been viewed before is revisited, the timeline is
  1597. // replaced.
  1598. disconnectPageObserver('timeline parent')
  1599. pageObservers.push(
  1600. observeElement($timeline.parentElement, (mutations) => {
  1601. mutations.forEach((mutation) => {
  1602. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1603. disconnectPageObserver('timeline')
  1604. log('tab changed')
  1605. onTabChanged?.()
  1606. pageObservers.push(
  1607. observeElement($newTimeline, () => onTimelineChange($newTimeline, page, options), 'timeline')
  1608. )
  1609. })
  1610. })
  1611. }, 'timeline parent')
  1612. )
  1613. }
  1614. }
  1615.  
  1616. // If the inital timeline doesn't have a style attribute it's a placeholder
  1617. if ($timeline.hasAttribute('style')) {
  1618. observeTimelineItems($timeline)
  1619. }
  1620. else {
  1621. log('waiting for timeline')
  1622. let startTime = Date.now()
  1623. pageObservers.push(
  1624. observeElement($timeline.parentElement, (mutations) => {
  1625. mutations.forEach((mutation) => {
  1626. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  1627. disconnectPageObserver('timeline parent')
  1628. if (Date.now() > startTime) {
  1629. log(`timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  1630. }
  1631. observeTimelineItems($timeline)
  1632. })
  1633. })
  1634. }, 'timeline parent')
  1635. )
  1636. }
  1637.  
  1638. // On some tabbed timeline pages, the first time a new tab is navigated to,
  1639. // the element containing the timeline is replaced with a loading spinner.
  1640. if (isTabbed && tabbedTimelineContainerSelector) {
  1641. let $tabbedTimelineContainer = document.querySelector(tabbedTimelineContainerSelector)
  1642. if ($tabbedTimelineContainer) {
  1643. let waitingForNewTimeline = false
  1644. pageObservers.push(
  1645. observeElement($tabbedTimelineContainer, async (mutations) => {
  1646. // This is going to fire twice on a new tab, as the spinner is added
  1647. // then replaced with the new timeline element.
  1648. if (!mutations.some(mutation => mutation.addedNodes.length > 0) || waitingForNewTimeline) return
  1649.  
  1650. waitingForNewTimeline = true
  1651. let $newTimeline = await getElement(timelineSelector, {
  1652. name: 'new timeline',
  1653. stopIf: pageIsNot(page),
  1654. })
  1655. waitingForNewTimeline = false
  1656. if (!$newTimeline) return
  1657.  
  1658. log('tab changed')
  1659. onTabChanged?.()
  1660. observeTimelineItems($newTimeline)
  1661. }, 'tabbed timeline container')
  1662. )
  1663. } else {
  1664. warn('tabbed timeline container not found')
  1665. }
  1666. }
  1667. }
  1668. //#endregion
  1669.  
  1670. //#region Tweak functions
  1671. /**
  1672. * Add an "Add muted word" menu item after "Settings and privacy" which takes
  1673. * you straight to entering a new muted word (by clicking its way through all
  1674. * the individual screens!).
  1675. * @param {HTMLElement} $circleLink
  1676. */
  1677. async function addAddMutedWordMenuItem($circleLink) {
  1678. log('adding "Add muted word" menu item')
  1679.  
  1680. // Wait for the dropdown to appear on desktop
  1681. if (desktop) {
  1682. $circleLink = await getElement('#layers div[data-testid="Dropdown"] a[href$="/i/circles"]', {
  1683. name: 'rendered Twitter Circle menu item',
  1684. timeout: 100,
  1685. })
  1686. if (!$circleLink) return
  1687. }
  1688.  
  1689. let $addMutedWord = /** @type {HTMLElement} */ ($circleLink.parentElement.cloneNode(true))
  1690. $addMutedWord.classList.add('tnt_menu_item')
  1691. $addMutedWord.querySelector('a').href = PagePaths.ADD_MUTED_WORD
  1692. $addMutedWord.querySelector('span').textContent = getString('ADD_MUTED_WORD')
  1693. $addMutedWord.querySelector('svg').innerHTML = Svgs.MUTE
  1694. $addMutedWord.addEventListener('click', (e) => {
  1695. e.preventDefault()
  1696. addMutedWord()
  1697. })
  1698. $circleLink.parentElement.insertAdjacentElement('afterend', $addMutedWord)
  1699. }
  1700.  
  1701. function addCaretMenuListenerForQuoteTweet($tweet) {
  1702. let $caret = /** @type {HTMLElement} */ ($tweet.querySelector('[data-testid="caret"]'))
  1703. if ($caret && !$caret.dataset.tweakNewTwitterListener) {
  1704. $caret.addEventListener('click', () => {
  1705. quotedTweet = getQuotedTweetDetails($tweet)
  1706. })
  1707. $caret.dataset.tweakNewTwitterListener = 'true'
  1708. }
  1709. }
  1710.  
  1711. /**
  1712. * Add a "Mute this conversation" menu item to a Quote Tweet's menu.
  1713. * @param {HTMLElement} $blockMenuItem
  1714. */
  1715. async function addMuteQuotesMenuItem($blockMenuItem) {
  1716. log('adding "Mute this conversation" menu item')
  1717.  
  1718. // Wait for the menu to render properly on desktop
  1719. if (desktop) {
  1720. $blockMenuItem = await getElement(`:scope > div > div > div > ${Selectors.BLOCK_MENU_ITEM}`, {
  1721. context: $blockMenuItem.parentElement,
  1722. name: 'rendered block menu item',
  1723. timeout: 100,
  1724. })
  1725. if (!$blockMenuItem) return
  1726. }
  1727.  
  1728. let $muteQuotes = /** @type {HTMLElement} */ ($blockMenuItem.previousElementSibling.cloneNode(true))
  1729. $muteQuotes.classList.add('tnt_menu_item')
  1730. $muteQuotes.querySelector('span').textContent = getString('MUTE_THIS_CONVERSATION')
  1731. $muteQuotes.addEventListener('click', (e) => {
  1732. e.preventDefault()
  1733. log('muting quotes of a tweet', quotedTweet)
  1734. config.mutedQuotes = config.mutedQuotes.concat(quotedTweet)
  1735. storeConfigChanges({mutedQuotes: config.mutedQuotes})
  1736. processCurrentPage()
  1737. // Dismiss the menu
  1738. let $menuLayer = /** @type {HTMLElement} */ ($blockMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  1739. if (!$menuLayer) {
  1740. log('could not find menu layer to dismiss menu')
  1741. }
  1742. $menuLayer?.click()
  1743. })
  1744.  
  1745. $blockMenuItem.insertAdjacentElement('beforebegin', $muteQuotes)
  1746. }
  1747.  
  1748. async function addMutedWord() {
  1749. if (!document.querySelector('a[href="/settings')) {
  1750. let $settingsAndSupport = /** @type {HTMLElement} */ (document.querySelector('[data-testid="settingsAndSupport"]'))
  1751. $settingsAndSupport?.click()
  1752. }
  1753.  
  1754. for (let path of [
  1755. '/settings',
  1756. '/settings/privacy_and_safety',
  1757. '/settings/mute_and_block',
  1758. '/settings/muted_keywords',
  1759. '/settings/add_muted_keyword',
  1760. ]) {
  1761. let $link = await getElement(`a[href="${path}"]`, {timeout: 500})
  1762. if (!$link) return
  1763. $link.click()
  1764. }
  1765. let $input = await getElement('input[name="keyword"]')
  1766. setTimeout(() => $input.focus(), 100)
  1767. }
  1768.  
  1769. /**
  1770. * Add a "Turn on/off Retweets" menu item to a List's menu.
  1771. * @param {HTMLElement} $switchMenuItem
  1772. */
  1773. async function addToggleListRetweetsMenuItem($switchMenuItem) {
  1774. log('adding "Turn on/off Retweets" menu item')
  1775.  
  1776. // Wait for the menu to render properly on desktop
  1777. if (desktop) {
  1778. $switchMenuItem = await getElement(':scope > div > div > div > [role="menuitem"]', {
  1779. context: $switchMenuItem.parentElement,
  1780. name: 'rendered switch menu item',
  1781. timeout: 100,
  1782. })
  1783. if (!$switchMenuItem) return
  1784. }
  1785.  
  1786. let $toggleRetweets = /** @type {HTMLElement} */ ($switchMenuItem.cloneNode(true))
  1787. $toggleRetweets.classList.add('tnt_menu_item')
  1788. $toggleRetweets.querySelector('span').textContent = getString(`TURN_${config.listRetweets == 'ignore' ? 'OFF' : 'ON'}_RETWEETS`)
  1789. $toggleRetweets.querySelector('svg').innerHTML = config.listRetweets == 'ignore' ? Svgs.RETWEETS_OFF : Svgs.RETWEET
  1790. $toggleRetweets.querySelector(':scope > div:last-child > div:last-child')?.remove()
  1791. $toggleRetweets.addEventListener('click', (e) => {
  1792. e.preventDefault()
  1793. log('toggling list retweets')
  1794. config.listRetweets = config.listRetweets == 'ignore' ? 'hide' : 'ignore'
  1795. storeConfigChanges({listRetweets: config.listRetweets})
  1796. processCurrentPage()
  1797. // Dismiss the menu
  1798. let $menuLayer = /** @type {HTMLElement} */ ($switchMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  1799. if (!$menuLayer) {
  1800. log('could not find menu layer to dismiss menu')
  1801. }
  1802. $menuLayer?.click()
  1803. })
  1804.  
  1805. $switchMenuItem.insertAdjacentElement('beforebegin', $toggleRetweets)
  1806. }
  1807.  
  1808. /**
  1809. * Redirects away from the home timeline if we're on it and it's been disabled.
  1810. * @returns {boolean} `true` if redirected as a result of this call
  1811. */
  1812. function checkforDisabledHomeTimeline() {
  1813. if (config.disableHomeTimeline && location.pathname == '/home') {
  1814. log(`home timeline disabled, redirecting to /${config.disabledHomeTimelineRedirect}`)
  1815. let primaryNavSelector = desktop ? Selectors.PRIMARY_NAV_DESKTOP : Selectors.PRIMARY_NAV_MOBILE
  1816. ;/** @type {HTMLElement} */ (
  1817. document.querySelector(`${primaryNavSelector} a[href="/${config.disabledHomeTimelineRedirect}"]`)
  1818. ).click()
  1819. return true
  1820. }
  1821. }
  1822.  
  1823. const configureCss = (() => {
  1824. let $style
  1825.  
  1826. return function configureCss() {
  1827. if ($style == null) {
  1828. $style = addStyle('features')
  1829. }
  1830. let cssRules = []
  1831. let hideCssSelectors = []
  1832. let menuRole = `[role="${desktop ? 'menu' : 'dialog'}"]`
  1833.  
  1834. // Hover colours for custom menu items
  1835. cssRules.push(`
  1836. body.Default .tnt_menu_item:hover { background-color: rgb(247, 249, 249) !important; }
  1837. body.Dim .tnt_menu_item:hover { background-color: rgb(30, 39, 50) !important; }
  1838. body.LightsOut .tnt_menu_item:hover { background-color: rgb(22, 24, 28) !important; }
  1839. `)
  1840.  
  1841. if (config.alwaysUseLatestTweets && config.hideForYouTimeline) {
  1842. cssRules.push(`
  1843. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child {
  1844. flex: 0;
  1845. }
  1846. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child > a {
  1847. display: none;
  1848. }
  1849. `)
  1850. }
  1851. if (config.dropdownMenuFontWeight) {
  1852. cssRules.push(`
  1853. [data-testid="${desktop ? 'Dropdown' : 'sheetDialog'}"] [role="menuitem"] [dir] {
  1854. font-weight: normal;
  1855. }
  1856. `)
  1857. }
  1858. if (config.hideAnalyticsNav) {
  1859. hideCssSelectors.push(`${menuRole} a[href*="analytics.twitter.com"]`)
  1860. }
  1861. if (config.hideBookmarkButton) {
  1862. hideCssSelectors.push(
  1863. // Under individual tweets - only hide the 4th button if there are 5
  1864. '[data-testid="tweet"][tabindex="-1"] [role="group"][id^="id__"] > div:nth-child(4):nth-last-child(2)',
  1865. )
  1866. }
  1867. if (config.hideBookmarksNav) {
  1868. hideCssSelectors.push(`${menuRole} a[href$="/bookmarks"]`)
  1869. }
  1870. if (config.hideTwitterCircleNav) {
  1871. hideCssSelectors.push(`${menuRole} a[href$="/i/circles"]`)
  1872. }
  1873. if (config.hideShareTweetButton) {
  1874. hideCssSelectors.push(
  1875. // Under timeline tweets
  1876. `[data-testid="tweet"][tabindex="0"] [role="group"] > div[style]`,
  1877. // Under individual tweets
  1878. '[data-testid="tweet"][tabindex="-1"] [role="group"] > div[style]',
  1879. )
  1880. }
  1881. if (config.hideHelpCenterNav) {
  1882. hideCssSelectors.push(`${menuRole} a[href*="support.twitter.com"]`)
  1883. }
  1884. if (config.hideListsNav) {
  1885. hideCssSelectors.push(`${menuRole} a[href$="/lists"]`)
  1886. }
  1887. if (config.hideMetrics) {
  1888. configureHideMetricsCss(cssRules, hideCssSelectors)
  1889. }
  1890. // if (config.hideMomentsNav) {
  1891. // hideCssSelectors.push(`${menuRole} a[href$="/moment_maker"]`)
  1892. // }
  1893. if (config.hideMonetizationNav) {
  1894. hideCssSelectors.push(`${menuRole} a[href$="/settings/monetization"]`)
  1895. }
  1896. // if (config.hideNewslettersNav) {
  1897. // hideCssSelectors.push(`${menuRole} a[href$="/newsletters"]`)
  1898. // }
  1899. if (config.hideTopicsNav) {
  1900. hideCssSelectors.push(`${menuRole} a[href$="/topics"]`)
  1901. }
  1902. if (config.hideTweetAnalyticsLinks) {
  1903. hideCssSelectors.push('[data-testid="analyticsButton"]')
  1904. }
  1905. if (config.hideTwitterAdsNav) {
  1906. hideCssSelectors.push(`${menuRole} a[href*="ads.twitter.com"]`)
  1907. }
  1908. if (config.hideTwitterBlueNav) {
  1909. hideCssSelectors.push(`${menuRole} a[href$="/i/twitter_blue_sign_up"]`)
  1910. }
  1911. if (config.hideTwitterForProfessionalsNav) {
  1912. hideCssSelectors.push(`${menuRole} a[href$="/convert_to_professional"]`)
  1913. }
  1914. if (config.hideVerifiedNotificationsTab) {
  1915. hideCssSelectors.push('body.Notifications [data-testid="ScrollSnap-List"] > div:nth-child(2)')
  1916. }
  1917. if (config.hideViews) {
  1918. hideCssSelectors.push(
  1919. // "Views" under individual tweets
  1920. '[data-testid="tweet"][tabindex="-1"] div[aria-hidden="true"]:nth-child(2):nth-last-child(2)',
  1921. '[data-testid="tweet"][tabindex="-1"] div[aria-hidden="true"]:nth-child(2):nth-last-child(2) + div[dir]:last-child'
  1922. )
  1923. }
  1924. if (config.hideWhoToFollowEtc) {
  1925. hideCssSelectors.push(`body.Profile ${Selectors.PRIMARY_COLUMN} aside[role="complementary"]`)
  1926. }
  1927. if (config.reducedInteractionMode) {
  1928. hideCssSelectors.push(
  1929. '[data-testid="tweet"] [role="group"]',
  1930. 'body.Tweet a:is([href$="/retweets"], [href$="/likes"])',
  1931. 'body.Tweet [data-testid="tweet"] + div > div [role="group"]',
  1932. )
  1933. }
  1934. if (config.tweakQuoteTweetsPage) {
  1935. // Hide the quoted tweet, which is repeated in every quote tweet
  1936. hideCssSelectors.push('body.QuoteTweets [data-testid="tweet"] [aria-labelledby] > div:last-child')
  1937. }
  1938. if (config.twitterBlueChecks == 'hide') {
  1939. hideCssSelectors.push('.tnt_blue_check')
  1940. }
  1941. if (config.twitterBlueChecks == 'replace') {
  1942. cssRules.push(`
  1943. :is(${Selectors.VERIFIED_TICK}, svg[data-testid="verificationBadge"]).tnt_blue_check path {
  1944. d: path("${Svgs.BLUE_LOGO_PATH}");
  1945. }
  1946. `)
  1947. }
  1948.  
  1949. // Hide "Creator Studio" if all its contents are hidden
  1950. // if (config.hideMomentsNav && config.hideNewslettersNav && config.hideAnalyticsNav) {
  1951. if (config.hideAnalyticsNav) {
  1952. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(1)`)
  1953. }
  1954. // Hide "Professional Tools" if all its contents are hidden
  1955. if (config.hideTwitterForProfessionalsNav && config.hideTwitterAdsNav && config.hideMonetizationNav) {
  1956. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(2)`)
  1957. }
  1958.  
  1959. if (config.retweets == 'separate' || config.quoteTweets == 'separate') {
  1960. cssRules.push(`
  1961. body.Default {
  1962. --active-tab-text: rgb(15, 20, 25);
  1963. --inactive-tab-text: rgb(83, 100, 113);
  1964. --tab-border: rgb(239, 243, 244);
  1965. --tab-hover: rgba(15, 20, 25, 0.1);
  1966. }
  1967. body.Dim {
  1968. --active-tab-text: rgb(247, 249, 249);
  1969. --inactive-tab-text: rgb(139, 152, 165);
  1970. --tab-border: rgb(56, 68, 77);
  1971. --tab-hover: rgba(247, 249, 249, 0.1);
  1972. }
  1973. body.LightsOut {
  1974. --active-tab-text: rgb(247, 249, 249);
  1975. --inactive-tab-text: rgb(113, 118, 123);
  1976. --tab-border: rgb(47, 51, 54);
  1977. --tab-hover: rgba(231, 233, 234, 0.1);
  1978. }
  1979.  
  1980. /* Tabbed timeline */
  1981. body.Desktop #tnt_separated_tweets_tab:hover,
  1982. body.Mobile:not(.SeparatedTweets) #tnt_separated_tweets_tab:hover,
  1983. body.Mobile #tnt_separated_tweets_tab:active {
  1984. background-color: var(--tab-hover);
  1985. }
  1986. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div,
  1987. body.TabbedTimeline.SeparatedTweets ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:not(#tnt_separated_tweets_tab) > a > div > div {
  1988. font-weight: normal !important;
  1989. color: var(--inactive-tab-text) !important;
  1990. }
  1991. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div {
  1992. font-weight: bold;
  1993. color: var(--active-tab-text); !important;
  1994. }
  1995. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div > div,
  1996. body.TabbedTimeline.SeparatedTweets ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:not(#tnt_separated_tweets_tab) > a > div > div > div {
  1997. height: 0 !important;
  1998. }
  1999. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2000. height: 4px !important;
  2001. min-width: 56px;
  2002. width: 100%;
  2003. position: absolute;
  2004. bottom: 0;
  2005. border-radius: 9999px;
  2006. }
  2007. `)
  2008. }
  2009.  
  2010. if (desktop) {
  2011. if (config.hideHomeHeading) {
  2012. hideCssSelectors.push(`body.TabbedTimeline ${Selectors.DESKTOP_TIMELINE_HEADER} > div:first-child > div:first-child`)
  2013. }
  2014. if (config.disableHomeTimeline) {
  2015. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/home"]`)
  2016. }
  2017. if (config.fullWidthContent) {
  2018. // Pseudo-selector for pages full-width is enabled on
  2019. let pageSelector = ':is(.Community, .List, .MainTimeline)'
  2020. cssRules.push(`
  2021. /* Use full width when the sidebar is visible */
  2022. body.Sidebar${pageSelector} ${Selectors.PRIMARY_COLUMN},
  2023. body.Sidebar${pageSelector} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2024. max-width: 990px;
  2025. }
  2026. /* Make the "What's happening" input keep its original width */
  2027. body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div:first-child > div:nth-of-type(3) div[role="progressbar"] + div {
  2028. max-width: 598px;
  2029. }
  2030. /* Use full width when the sidebar is not visible */
  2031. body:not(.Sidebar)${pageSelector} header[role="banner"] {
  2032. flex-grow: 0;
  2033. }
  2034. body:not(.Sidebar)${pageSelector} main[role="main"] > div {
  2035. width: 100%;
  2036. }
  2037. body:not(.Sidebar)${pageSelector} ${Selectors.PRIMARY_COLUMN} {
  2038. max-width: unset;
  2039. width: 100%;
  2040. }
  2041. body:not(.Sidebar)${pageSelector} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:first-child div,
  2042. body:not(.Sidebar)${pageSelector} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2043. max-width: unset;
  2044. }
  2045. `)
  2046. if (!config.fullWidthMedia) {
  2047. // Make media & cards keep their original width
  2048. cssRules.push(`
  2049. body${pageSelector} ${Selectors.PRIMARY_COLUMN} ${Selectors.TWEET} > div > div > div > div:nth-of-type(2) > div:nth-of-type(2) > div:nth-of-type(2) > div[id][aria-labelledby]:not(:empty) {
  2050. max-width: 504px;
  2051. }
  2052. `)
  2053. }
  2054. // Hide the sidebar when present
  2055. hideCssSelectors.push(`body.Sidebar${pageSelector} ${Selectors.SIDEBAR}`)
  2056. }
  2057. if (config.hideAccountSwitcher) {
  2058. cssRules.push(`
  2059. header[role="banner"] > div > div > div > div:last-child {
  2060. flex-shrink: 1 !important;
  2061. align-items: flex-end !important;
  2062. }
  2063. `)
  2064. hideCssSelectors.push(
  2065. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child:not(:only-child)',
  2066. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child + div',
  2067. )
  2068. }
  2069. if (config.hideCommunitiesNav) {
  2070. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/communities"]`)
  2071. }
  2072. if (config.hideExplorePageContents) {
  2073. hideCssSelectors.push(
  2074. // Tabs
  2075. `body.Explore ${Selectors.DESKTOP_TIMELINE_HEADER} nav`,
  2076. // Content
  2077. `body.Explore ${Selectors.TIMELINE}`,
  2078. )
  2079. }
  2080. if (config.hideKeyboardShortcutsNav) {
  2081. hideCssSelectors.push(`${menuRole} a[href$="/i/keyboard_shortcuts"]`)
  2082. }
  2083. if (config.hideTwitterBlueNav) {
  2084. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/i/twitter_blue_sign_up"]`)
  2085. }
  2086. if (config.hideSidebarContent) {
  2087. // Only show the first sidebar item by default
  2088. // Re-show subsequent non-algorithmic sections on specific pages
  2089. cssRules.push(`
  2090. ${Selectors.SIDEBAR_WRAPPERS} > div:not(:first-of-type) {
  2091. display: none;
  2092. }
  2093. body.Profile:not(.Blocked, .NoMedia) ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2094. display: block;
  2095. }
  2096. `)
  2097. if (config.showRelevantPeople) {
  2098. cssRules.push(`
  2099. body.Tweet ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2100. display: block;
  2101. }
  2102. `)
  2103. }
  2104. hideCssSelectors.push(`body.HideSidebar ${Selectors.SIDEBAR}`)
  2105. }
  2106. if (config.hideShareTweetButton) {
  2107. hideCssSelectors.push(
  2108. // In media modal
  2109. `[aria-modal="true"] [role="group"] > div[style]:not([role])`,
  2110. )
  2111. }
  2112. if (config.hideExploreNav) {
  2113. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/explore"]`)
  2114. }
  2115. if (config.hideBookmarksNav) {
  2116. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/i/bookmarks"]`)
  2117. }
  2118. if (config.hideMessagesDrawer) {
  2119. cssRules.push(`${Selectors.MESSAGES_DRAWER} { visibility: hidden; }`)
  2120. }
  2121. if (config.hideViews) {
  2122. hideCssSelectors.push(
  2123. // Under timeline tweets
  2124. // The Buffer extension adds a new button in position 2 - use their added class to avoid
  2125. // hiding the wrong button (#209)
  2126. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-of-type(4)',
  2127. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-of-type(5)',
  2128. )
  2129. }
  2130. if (config.retweets != 'separate' && config.quoteTweets != 'separate') {
  2131. hideCssSelectors.push('#tnt_separated_tweets_tab')
  2132. }
  2133. }
  2134.  
  2135. if (mobile) {
  2136. if (config.disableHomeTimeline) {
  2137. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/home"]`)
  2138. }
  2139. if (config.hideAppNags) {
  2140. cssRules.push(`
  2141. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_OLD} div:nth-of-type(3) > div > [role="button"],
  2142. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_NEW} div:nth-of-type(3) > div > [role="button"] {
  2143. visibility: hidden;
  2144. }
  2145. `)
  2146. }
  2147. if (config.hideExplorePageContents) {
  2148. // Hide explore page contents so we don't get a brief flash of them
  2149. // before automatically switching the page to search mode.
  2150. hideCssSelectors.push(
  2151. // Tabs
  2152. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div:nth-of-type(2)`,
  2153. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:nth-of-type(2)`,
  2154. // Content
  2155. `body.Explore ${Selectors.TIMELINE}`,
  2156. )
  2157. }
  2158. if (config.hideCommunitiesNav) {
  2159. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href$="/communities"]`)
  2160. }
  2161. if (config.hideMessagesBottomNavItem) {
  2162. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/messages"]`)
  2163. }
  2164. if (config.hideShareTweetButton) {
  2165. hideCssSelectors.push(
  2166. // In media modal
  2167. `body.MobilePhoto [role="group"] > div[style]`,
  2168. )
  2169. }
  2170. if (config.hideViews) {
  2171. hideCssSelectors.push(
  2172. // Under timeline tweets
  2173. // Views only display on mobile at larger widths - only hide the 4th button if there are 5
  2174. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-child(4):nth-last-child(2)',
  2175. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-child(4):nth-last-child(2)',
  2176. )
  2177. }
  2178. }
  2179.  
  2180. if (hideCssSelectors.length > 0) {
  2181. cssRules.push(`
  2182. ${hideCssSelectors.join(',\n')} {
  2183. display: none !important;
  2184. }
  2185. `)
  2186. }
  2187.  
  2188. $style.textContent = cssRules.map(dedent).join('\n')
  2189. }
  2190. })()
  2191.  
  2192. function configureFont() {
  2193. if (!fontFamilyRule) {
  2194. warn('no fontFamilyRule found for configureFont to use')
  2195. return
  2196. }
  2197.  
  2198. if (config.dontUseChirpFont) {
  2199. if (fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2200. fontFamilyRule.style.fontFamily = fontFamilyRule.style.fontFamily.replace(/"?TwitterChirp"?, ?/, '')
  2201. log('disabled Chirp font')
  2202. }
  2203. } else if (!fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2204. fontFamilyRule.style.fontFamily = `"TwitterChirp", ${fontFamilyRule.style.fontFamily}`
  2205. log(`enabled Chirp font`)
  2206. }
  2207. }
  2208.  
  2209. /**
  2210. * @param {string[]} cssRules
  2211. * @param {string[]} hideCssSelectors
  2212. */
  2213. function configureHideMetricsCss(cssRules, hideCssSelectors) {
  2214. if (config.hideFollowingMetrics) {
  2215. // User profile hover card and page metrics
  2216. hideCssSelectors.push(
  2217. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) > :first-child'
  2218. )
  2219. // Fix display of whitespace after hidden metrics
  2220. cssRules.push(
  2221. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) { white-space: pre-line; }'
  2222. )
  2223. }
  2224.  
  2225. if (config.hideTotalTweetsMetrics) {
  2226. // Tweet count under username header on profile pages
  2227. hideCssSelectors.push(
  2228. mobile ? `
  2229. body.Profile header > div > div:first-of-type h2 + div[dir],
  2230. body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:first-of-type h2 + div[dir]
  2231. ` : `body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 + div[dir]`
  2232. )
  2233. }
  2234.  
  2235. let individualTweetMetricSelectors = [
  2236. config.hideRetweetMetrics && '[href$="/retweets"]',
  2237. config.hideLikeMetrics && '[href$="/likes"]',
  2238. config.hideQuoteTweetMetrics && '[href$="/retweets/with_comments"]',
  2239. ].filter(Boolean).join(', ')
  2240.  
  2241. if (individualTweetMetricSelectors) {
  2242. // Individual tweet metrics
  2243. hideCssSelectors.push(
  2244. `body.Tweet a:is(${individualTweetMetricSelectors}) > :first-child`,
  2245. `[aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) > :first-child`
  2246. )
  2247. // Fix display of whitespace after hidden metrics
  2248. cssRules.push(
  2249. `body.Tweet a:is(${individualTweetMetricSelectors}), [aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) { white-space: pre-line; }`
  2250. )
  2251. }
  2252.  
  2253. if (config.hideBookmarkMetrics) {
  2254. // Bookmark metrics are the only one without a link
  2255. hideCssSelectors.push('[data-testid="tweet"][tabindex="-1"] [role="group"]:not([id]) > div > div')
  2256. }
  2257.  
  2258. let timelineMetricSelectors = [
  2259. config.hideReplyMetrics && '[data-testid="reply"]',
  2260. config.hideRetweetMetrics && '[data-testid$="retweet"]',
  2261. config.hideLikeMetrics && '[data-testid$="like"]',
  2262. ].filter(Boolean).join(', ')
  2263.  
  2264. if (timelineMetricSelectors) {
  2265. cssRules.push(
  2266. `[role="group"] div:is(${timelineMetricSelectors}) span { visibility: hidden; }`
  2267. )
  2268. }
  2269. }
  2270.  
  2271. const configureNavFontSizeCss = (() => {
  2272. let $style
  2273.  
  2274. return function configureNavFontSizeCss() {
  2275. if ($style == null) {
  2276. $style = addStyle('nav-font-size')
  2277. }
  2278. let cssRules = []
  2279.  
  2280. if (fontSize != null && config.navBaseFontSize) {
  2281. cssRules.push(`
  2282. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] span { font-size: ${fontSize}; font-weight: normal; }
  2283. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] { margin-top: -4px; }
  2284. `)
  2285. }
  2286.  
  2287. $style.textContent = cssRules.map(dedent).join('\n')
  2288. }
  2289. })()
  2290.  
  2291. /**
  2292. * Configures – or re-configures – the separated tweets timeline title.
  2293. *
  2294. * If we're currently on the separated tweets timeline and…
  2295. * - …its title has changed, the page title will be changed to "navigate" to it.
  2296. * - …the separated tweets timeline is no longer needed, we'll change the page
  2297. * title to "navigate" back to the main timeline.
  2298. *
  2299. * @returns {boolean} `true` if "navigation" was triggered by this call
  2300. */
  2301. function configureSeparatedTweetsTimelineTitle() {
  2302. let wasOnSeparatedTweetsTimeline = isOnSeparatedTweetsTimeline()
  2303. let previousTitle = separatedTweetsTimelineTitle
  2304.  
  2305. if (config.retweets == 'separate' && config.quoteTweets == 'separate') {
  2306. separatedTweetsTimelineTitle = getString('SHARED_TWEETS')
  2307. } else if (config.retweets == 'separate') {
  2308. separatedTweetsTimelineTitle = getString('RETWEETS')
  2309. } else if (config.quoteTweets == 'separate') {
  2310. separatedTweetsTimelineTitle = getString('QUOTE_TWEETS')
  2311. } else {
  2312. separatedTweetsTimelineTitle = null
  2313. }
  2314.  
  2315. let titleChanged = previousTitle != separatedTweetsTimelineTitle
  2316. if (wasOnSeparatedTweetsTimeline) {
  2317. if (separatedTweetsTimelineTitle == null) {
  2318. log('moving from separated tweets timeline to main timeline after config change')
  2319. setTitle(getString('HOME'))
  2320. return true
  2321. }
  2322. if (titleChanged) {
  2323. log('applying new separated tweets timeline title after config change')
  2324. setTitle(separatedTweetsTimelineTitle)
  2325. return true
  2326. }
  2327. } else {
  2328. if (titleChanged && previousTitle != null && lastMainTimelineTitle == previousTitle) {
  2329. log('updating lastMainTimelineTitle with new separated tweets timeline title')
  2330. lastMainTimelineTitle = separatedTweetsTimelineTitle
  2331. }
  2332. }
  2333. }
  2334.  
  2335. const configureThemeCss = (() => {
  2336. let $style
  2337.  
  2338. return function configureThemeCss() {
  2339. if ($style == null) {
  2340. $style = addStyle('theme')
  2341. }
  2342. let cssRules = []
  2343.  
  2344. if (debug) {
  2345. cssRules.push(`
  2346. [data-item-type]::after {
  2347. position: absolute;
  2348. top: 0;
  2349. ${ltr ? 'right': 'left'}: 50px;
  2350. content: attr(data-item-type);
  2351. font-family: ${fontFamilyRule?.style.fontFamily || '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial'};
  2352. background-color: rgb(242, 29, 29);
  2353. color: white;
  2354. font-size: 11px;
  2355. font-weight: bold;
  2356. padding: 4px 6px;
  2357. border-bottom-left-radius: 1em;
  2358. border-bottom-right-radius: 1em;
  2359. }
  2360. `)
  2361. }
  2362.  
  2363. // Active tab colour for custom tabs
  2364. if (themeColor != null && (config.retweets == 'separate' || config.quoteTweets == 'separate')) {
  2365. cssRules.push(`
  2366. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2367. background-color: ${themeColor} !important;
  2368. }
  2369. `)
  2370. }
  2371.  
  2372. if (config.uninvertFollowButtons) {
  2373. // Shared styles for Following and Follow buttons
  2374. cssRules.push(`
  2375. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2376. border-color: rgba(0, 0, 0, 0) !important;
  2377. }
  2378. [role="button"][data-testid$="-follow"] {
  2379. background-color: rgba(0, 0, 0, 0) !important;
  2380. }
  2381. `)
  2382. if (config.followButtonStyle == 'monochrome' || themeColor == null) {
  2383. cssRules.push(`
  2384. /* Following button */
  2385. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2386. background-color: rgb(15, 20, 25) !important;
  2387. }
  2388. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) > * {
  2389. color: rgb(255, 255, 255) !important;
  2390. }
  2391. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2392. background-color: rgb(255, 255, 255) !important;
  2393. }
  2394. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) > * {
  2395. color: rgb(15, 20, 25) !important;
  2396. }
  2397. /* Follow button */
  2398. body.Default [role="button"][data-testid$="-follow"] {
  2399. border-color: rgb(207, 217, 222) !important;
  2400. }
  2401. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] {
  2402. border-color: rgb(83, 100, 113) !important;
  2403. }
  2404. body.Default [role="button"][data-testid$="-follow"] > * {
  2405. color: rgb(15, 20, 25) !important;
  2406. }
  2407. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] > * {
  2408. color: rgb(255, 255, 255) !important;
  2409. }
  2410. body.Default [role="button"][data-testid$="-follow"]:hover {
  2411. background-color: rgba(15, 20, 25, 0.1) !important;
  2412. }
  2413. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"]:hover {
  2414. background-color: rgba(255, 255, 255, 0.1) !important;
  2415. }
  2416. `)
  2417. }
  2418. if (config.followButtonStyle == 'themed' && themeColor != null) {
  2419. cssRules.push(`
  2420. /* Following button */
  2421. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2422. background-color: ${themeColor} !important;
  2423. }
  2424. [role="button"][data-testid$="-unfollow"]:not(:hover) > * {
  2425. color: rgb(255, 255, 255) !important;
  2426. }
  2427. /* Follow button */
  2428. [role="button"][data-testid$="-follow"] {
  2429. border-color: ${themeColor} !important;
  2430. }
  2431. [role="button"][data-testid$="-follow"] > * {
  2432. color: ${themeColor} !important;
  2433. }
  2434. [role="button"][data-testid$="-follow"]:hover {
  2435. background-color: ${themeColor} !important;
  2436. }
  2437. [role="button"][data-testid$="-follow"]:hover > * {
  2438. color: rgb(255, 255, 255) !important;
  2439. }
  2440. `)
  2441. }
  2442. }
  2443.  
  2444. $style.textContent = cssRules.map(dedent).join('\n')
  2445. }
  2446. })()
  2447.  
  2448. /**
  2449. * @param {HTMLElement} $tweet
  2450. * @returns {import("./types").QuotedTweet}
  2451. */
  2452. function getQuotedTweetDetails($tweet) {
  2453. let $quotedTweet = $tweet.querySelector('div[id^="id__"] > div[dir] > span').parentElement.nextElementSibling
  2454. let $heading = $quotedTweet?.querySelector(':scope > div > div:first-child')
  2455. let user = $heading?.querySelector('div:last-child > span')?.textContent
  2456. let time = $heading?.querySelector('time')?.dateTime
  2457. let $qtText = $heading?.nextElementSibling?.querySelector('[lang]')
  2458. let text = $qtText && Array.from($qtText.childNodes, node => {
  2459. if (node.nodeType == 1) {
  2460. if (node.nodeName == 'IMG') return node.alt
  2461. return node.textContent
  2462. }
  2463. return node.nodeValue
  2464. }).join('')
  2465. return {user, time, text}
  2466. }
  2467.  
  2468. /**
  2469. * Attempts to determine the type of a timeline Tweet given the element with
  2470. * data-testid="tweet" on it, falling back to TWEET if it doesn't appear to be
  2471. * one of the particular types we care about.
  2472. * @param {HTMLElement} $tweet
  2473. * @returns {import("./types").TimelineItemType}
  2474. */
  2475. function getTweetType($tweet) {
  2476. if ($tweet.closest(Selectors.PROMOTED_TWEET_CONTAINER)) {
  2477. return 'PROMOTED_TWEET'
  2478. }
  2479. // Assume social context tweets are Retweets
  2480. if ($tweet.querySelector('[data-testid="socialContext"]')) {
  2481. // Quoted tweets from accounts you blocked or muted are displayed as an
  2482. // <article> with "This Tweet is unavailable."
  2483. if ($tweet.querySelector('article')) {
  2484. return 'UNAVAILABLE_RETWEET'
  2485. }
  2486. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2487. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2488. return 'RETWEETED_QUOTE_TWEET'
  2489. }
  2490. return 'RETWEET'
  2491. }
  2492. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2493. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2494. return 'QUOTE_TWEET'
  2495. }
  2496. // Quoted tweets from accounts you blocked or muted are displayed as an
  2497. // <article> with "This Tweet is unavailable."
  2498. if ($tweet.querySelector('article')) {
  2499. return 'UNAVAILABLE_QUOTE_TWEET'
  2500. }
  2501. return 'TWEET'
  2502. }
  2503.  
  2504. // Add 1 every time this gets broken: 6
  2505. function getVerifiedProps($svg) {
  2506. let propsGetter = (props) => props?.children?.props?.children?.[0]?.[0]?.props
  2507. let $parent = $svg.parentElement.parentElement
  2508. // Verified badge button on the profile screen
  2509. if (isOnProfilePage() && $svg.parentElement.getAttribute('role') == 'button') {
  2510. $parent = $svg.closest('span').parentElement
  2511. }
  2512. // Link variant in "user followed/liked/retweeted" notifications
  2513. else if (isOnNotificationsPage() && $parent.getAttribute('role') == 'link') {
  2514. propsGetter = (props) => {
  2515. let linkChildren = props?.children?.props?.children?.[0]
  2516. return linkChildren?.[linkChildren.length - 1]?.props
  2517. }
  2518. }
  2519. if ($parent.wrappedJSObject) {
  2520. $parent = $parent.wrappedJSObject
  2521. }
  2522. let reactPropsKey = Object.keys($parent).find(key => key.startsWith('__reactProps$'))
  2523. let props = propsGetter($parent[reactPropsKey])
  2524. if (!props) {
  2525. warn('React props not found for', $svg)
  2526. }
  2527. else if (!('isVerified' in props)) {
  2528. warn('isVerified not in React props for', $svg, {props})
  2529. }
  2530. return props
  2531. }
  2532.  
  2533. /**
  2534. * @param {HTMLElement} $popup
  2535. * @returns {{tookAction: boolean, onPopupClosed?: () => void}}
  2536. */
  2537. function handlePopup($popup) {
  2538. let result = {tookAction: false, onPopupClosed: null}
  2539.  
  2540. if (desktop && !isDesktopMediaModalOpen && URL_PHOTO_RE.test(location.pathname) && currentPath != location.pathname) {
  2541. log('media modal opened')
  2542. isDesktopMediaModalOpen = true
  2543. observeDesktopModalTimeline()
  2544. return {
  2545. tookAction: true,
  2546. onPopupClosed() {
  2547. log('media modal closed')
  2548. isDesktopMediaModalOpen = false
  2549. disconnectAllModalObservers()
  2550. }
  2551. }
  2552. }
  2553.  
  2554. if (desktop && !isCircleModalOpen && URL_CIRCLE_RE.test(location.pathname) && currentPath != location.pathname) {
  2555. log('circle modal opened')
  2556. isCircleModalOpen = true
  2557. observeCircleModal()
  2558. return {
  2559. tookAction: true,
  2560. onPopupClosed() {
  2561. log('circle modal closed')
  2562. isCircleModalOpen = false
  2563. disconnectAllModalObservers()
  2564. }
  2565. }
  2566. }
  2567.  
  2568. if (isOnListPage()) {
  2569. let $switchSvg = $popup.querySelector(`svg path[d^="M15.96 1.54L21.41 7l-5.45 5.46-1.42-1"]`)
  2570. if ($switchSvg) {
  2571. addToggleListRetweetsMenuItem($popup.querySelector(`[role="menuitem"]`))
  2572. return {tookAction: true}
  2573. }
  2574. }
  2575.  
  2576. if (config.mutableQuoteTweets) {
  2577. if (quotedTweet) {
  2578. let $blockMenuItem = /** @type {HTMLElement} */ ($popup.querySelector(Selectors.BLOCK_MENU_ITEM))
  2579. if ($blockMenuItem) {
  2580. addMuteQuotesMenuItem($blockMenuItem)
  2581. result.tookAction = true
  2582. // Clear the quoted tweet when the popup closes
  2583. result.onPopupClosed = () => {
  2584. quotedTweet = null
  2585. }
  2586. } else {
  2587. quotedTweet = null
  2588. }
  2589. }
  2590. }
  2591.  
  2592. if (config.fastBlock) {
  2593. if (blockMenuItemSeen && $popup.querySelector('[data-testid="confirmationSheetConfirm"]')) {
  2594. log('fast blocking')
  2595. ;/** @type {HTMLElement} */ ($popup.querySelector('[data-testid="confirmationSheetConfirm"]')).click()
  2596. result.tookAction = true
  2597. }
  2598. else if ($popup.querySelector(Selectors.BLOCK_MENU_ITEM)) {
  2599. log('preparing for fast blocking')
  2600. blockMenuItemSeen = true
  2601. // Create a nested observer for mobile, as it reuses the popup element
  2602. result.tookAction = !mobile
  2603. } else {
  2604. blockMenuItemSeen = false
  2605. }
  2606. }
  2607.  
  2608. if (config.addAddMutedWordMenuItem) {
  2609. let $circleLink = /** @type {HTMLElement} */ ($popup.querySelector('a[href$="/i/circles"]'))
  2610. if ($circleLink) {
  2611. addAddMutedWordMenuItem($circleLink)
  2612. result.tookAction = true
  2613. }
  2614. }
  2615.  
  2616. if (config.twitterBlueChecks != 'ignore') {
  2617. // User typeahead dropdown
  2618. let $typeaheadDropdown = /** @type {HTMLElement} */ ($popup.querySelector('div[id^="typeaheadDropdown"]'))
  2619. if ($typeaheadDropdown) {
  2620. log('typeahead dropdown appeared')
  2621. let observer = observeElement($typeaheadDropdown, () => {
  2622. processBlueChecks($typeaheadDropdown)
  2623. }, 'popup typeahead dropdown')
  2624. return {
  2625. tookAction: true,
  2626. onPopupClosed() {
  2627. log('typeahead dropdown closed')
  2628. observer.disconnect()
  2629. }
  2630. }
  2631. }
  2632.  
  2633. // User hovercard popup
  2634. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  2635. if ($hoverCard) {
  2636. result.tookAction = true
  2637. getElement('div[data-testid^="UserAvatar-Container"]', {
  2638. context: $hoverCard,
  2639. name: 'user hovercard contents',
  2640. timeout: 500,
  2641. }).then(($contents) => {
  2642. if ($contents) processBlueChecks($popup)
  2643. })
  2644. }
  2645. }
  2646.  
  2647. // Verified account popup when you press the check button on a profile page
  2648. if (config.twitterBlueChecks == 'replace' && isOnProfilePage()) {
  2649. if (mobile) {
  2650. let $verificationBadge = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="sheetDialog"] [data-testid="verificationBadge"]'))
  2651. if ($verificationBadge) {
  2652. result.tookAction = true
  2653. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} .tnt_blue_check`)
  2654. if ($headerBlueCheck) {
  2655. blueCheck($verificationBadge)
  2656. }
  2657. }
  2658. } else {
  2659. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  2660. if ($hoverCard) {
  2661. result.tookAction = true
  2662. getElement(':scope > div > div > svg[data-testid="verificationBadge"]', {
  2663. context: $hoverCard,
  2664. name: 'verified account hovercard verification badge',
  2665. timeout: 500,
  2666. }).then(($verificationBadge) => {
  2667. if (!$verificationBadge) return
  2668.  
  2669. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 .tnt_blue_check`)
  2670. if (!$headerBlueCheck) return
  2671.  
  2672. // Wait for the hovercard to render its contents
  2673. let popupRenderObserver = observeElement($popup, (mutations) => {
  2674. if (!mutations.length) return
  2675. blueCheck($popup.querySelector('svg[data-testid="verificationBadge"]'))
  2676. popupRenderObserver.disconnect()
  2677. }, 'verified popup render', {childList: true, subtree: true})
  2678. })
  2679. }
  2680. }
  2681. }
  2682.  
  2683. return result
  2684. }
  2685.  
  2686. function isBlueVerified($svg) {
  2687. let props = getVerifiedProps($svg)
  2688. return Boolean(props && props.isBlueVerified && !props.isVerified && !props.verifiedType && !props.affiliateBadgeInfo)
  2689. }
  2690.  
  2691. /**
  2692. * Checks if a tweet is preceded by an element creating a vertical reply line.
  2693. * @param {HTMLElement} $tweet
  2694. * @returns {boolean}
  2695. */
  2696. function isReplyToPreviousTweet($tweet) {
  2697. let $replyLine = $tweet.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild
  2698. if ($replyLine) {
  2699. return getComputedStyle($replyLine).width == '2px'
  2700. }
  2701. }
  2702.  
  2703. /**
  2704. * @returns {{disconnect()}}
  2705. */
  2706. function onPopup($popup) {
  2707. log('popup appeared', $popup)
  2708.  
  2709. // If handlePopup did something, we don't need to observe nested popups
  2710. let {tookAction, onPopupClosed} = handlePopup($popup)
  2711. if (tookAction) {
  2712. return onPopupClosed ? {disconnect: onPopupClosed} : null
  2713. }
  2714.  
  2715. /** @type {HTMLElement} */
  2716. let $nestedPopup
  2717.  
  2718. let nestedObserver = observeElement($popup, (mutations) => {
  2719. mutations.forEach((mutation) => {
  2720. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  2721. log('nested popup appeared', $el)
  2722. $nestedPopup = $el
  2723. ;({onPopupClosed} = handlePopup($el))
  2724. })
  2725. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  2726. if ($el !== $nestedPopup) return
  2727. if (onPopupClosed) {
  2728. log('cleaning up after nested popup removed')
  2729. onPopupClosed()
  2730. }
  2731. })
  2732. })
  2733. })
  2734.  
  2735. let disconnect = nestedObserver.disconnect.bind(nestedObserver)
  2736. nestedObserver.disconnect = () => {
  2737. if (onPopupClosed) {
  2738. log('cleaning up after nested popup observer disconnected')
  2739. onPopupClosed()
  2740. }
  2741. disconnect()
  2742. }
  2743.  
  2744. return nestedObserver
  2745. }
  2746.  
  2747. /**
  2748. * @param {HTMLElement} $timeline
  2749. * @param {string} page
  2750. * @param {import("./types").TimelineOptions?} options
  2751. */
  2752. function onTimelineChange($timeline, page, options = {}) {
  2753. let startTime = Date.now()
  2754. let {classifyTweets = true, hideHeadings = true} = options
  2755.  
  2756. let isOnMainTimeline = isOnMainTimelinePage()
  2757. let isOnListTimeline = isOnListPage()
  2758.  
  2759. if (config.twitterBlueChecks != 'ignore' && !isOnMainTimeline && !isOnListTimeline) {
  2760. processBlueChecks($timeline)
  2761. }
  2762.  
  2763. if (!classifyTweets) return
  2764.  
  2765. let itemTypes = {}
  2766. let hiddenItemCount = 0
  2767. let hiddenItemTypes = {}
  2768.  
  2769. /** @type {HTMLElement} */
  2770. let $previousItem = null
  2771. /** @type {?import("./types").TimelineItemType} */
  2772. let previousItemType = null
  2773. /** @type {?boolean} */
  2774. let hidPreviousItem = null
  2775. let hideAllSubsequentItems = false
  2776.  
  2777. for (let $item of $timeline.children) {
  2778. /** @type {?import("./types").TimelineItemType} */
  2779. let itemType = null
  2780. /** @type {?boolean} */
  2781. let hideItem = null
  2782. /** @type {?boolean} */
  2783. let highlightItem = null
  2784. /** @type {?HTMLElement} */
  2785. let $tweet = $item.querySelector(Selectors.TWEET)
  2786.  
  2787. if (hideAllSubsequentItems) {
  2788. hideItem = true
  2789. itemType = previousItemType
  2790. }
  2791. else if ($tweet != null) {
  2792. itemType = getTweetType($tweet)
  2793. if (isOnMainTimeline || isOnListTimeline) {
  2794. let isReply = isReplyToPreviousTweet($tweet)
  2795. if (isReply && hidPreviousItem != null) {
  2796. hideItem = hidPreviousItem
  2797. } else {
  2798. if (isOnMainTimeline) {
  2799. hideItem = shouldHideMainTimelineItem(itemType, page)
  2800. }
  2801. else if (isOnListTimeline) {
  2802. hideItem = shouldHideListTimelineItem(itemType)
  2803. }
  2804. }
  2805.  
  2806. if (!hideItem && config.mutableQuoteTweets && (itemType == 'QUOTE_TWEET' || itemType == 'RETWEETED_QUOTE_TWEET')) {
  2807. if (config.mutedQuotes.length > 0) {
  2808. let quotedTweet = getQuotedTweetDetails($tweet)
  2809. hideItem = config.mutedQuotes.some(muted => muted.user == quotedTweet.user && muted.time == quotedTweet.time)
  2810. }
  2811. if (!hideItem) {
  2812. addCaretMenuListenerForQuoteTweet($tweet)
  2813. }
  2814. }
  2815.  
  2816. let checkType
  2817. if (config.twitterBlueChecks != 'ignore' || config.verifiedAccounts != 'ignore') {
  2818. for (let $svg of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  2819. let verifiedProps = getVerifiedProps($svg)
  2820. if (!verifiedProps) continue
  2821.  
  2822. let isUserCheck = $svg.closest('div[data-testid="User-Names"]')
  2823. if (verifiedProps.isVerified) {
  2824. if (isUserCheck) {
  2825. checkType = 'VERIFIED'
  2826. }
  2827. if (hideItem !== true) {
  2828. hideItem = config.verifiedAccounts == 'hide'
  2829. }
  2830. highlightItem = config.verifiedAccounts == 'highlight'
  2831. }
  2832. else if (verifiedProps.isBlueVerified) {
  2833. if (isUserCheck) {
  2834. checkType = 'BLUE'
  2835. }
  2836. blueCheck($svg)
  2837. }
  2838. }
  2839. }
  2840.  
  2841. if (debug) {
  2842. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${checkType ? ` / ${checkType}` : ''}`
  2843. }
  2844. }
  2845. }
  2846. else if (!isOnMainTimeline && !isOnListTimeline) {
  2847. if ($item.querySelector(':scope > div > div > div > article')) {
  2848. itemType = 'UNAVAILABLE'
  2849. }
  2850. }
  2851.  
  2852. if (!isOnMainTimeline && !isOnListTimeline) {
  2853. if (itemType != null) {
  2854. hideItem = shouldHideOtherTimelineItem(itemType)
  2855. if (debug) {
  2856. $item.firstElementChild.dataset.itemType = itemType
  2857. }
  2858. }
  2859. }
  2860.  
  2861. if (itemType == null) {
  2862. if ($item.querySelector(Selectors.TIMELINE_HEADING)) {
  2863. itemType = 'HEADING'
  2864. // "Discover more" heading and subsequent algorithmic tweets
  2865. if (isOnIndividualTweetPage()) {
  2866. if ($item.querySelector('[dir]')?.innerText == getString('DISCOVER_MORE')) {
  2867. itemType = 'DISCOVER_MORE_HEADING'
  2868. hideItem = config.hideMoreTweets
  2869. hideAllSubsequentItems = config.hideMoreTweets
  2870. }
  2871. }
  2872. // "Who to follow", "Follow some Topics" etc. headings
  2873. else if (hideHeadings) {
  2874. hideItem = config.hideWhoToFollowEtc
  2875. }
  2876. if (debug) {
  2877. $item.firstElementChild.dataset.itemType = itemType
  2878. }
  2879. }
  2880. }
  2881.  
  2882. itemTypes[itemType] ||= 0
  2883. itemTypes[itemType]++
  2884.  
  2885. if (itemType == null) {
  2886. // Assume a non-identified item following an identified item is related.
  2887. // "Who to follow" users and "Follow some Topics" topics appear in
  2888. // subsequent items, as do "Show this thread" and "Show more" links.
  2889. if (previousItemType != null) {
  2890. hideItem = hidPreviousItem
  2891. itemType = previousItemType
  2892. }
  2893. }
  2894.  
  2895. if (hideItem != null) {
  2896. if (hideItem) {
  2897. hiddenItemCount++
  2898. hiddenItemTypes[itemType] ||= 0
  2899. hiddenItemTypes[itemType]++
  2900. }
  2901. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  2902. /** @type {HTMLElement} */ ($item.firstElementChild).style.display = hideItem ? 'none' : ''
  2903. // Log these out as they can't be reliably triggered for testing
  2904. if (hideItem && itemType == 'HEADING' || previousItemType == 'HEADING') {
  2905. log(`hid a ${previousItemType == 'HEADING' ? 'post-' : ''}heading item`, $item)
  2906. }
  2907. }
  2908. }
  2909.  
  2910. if (highlightItem != null) {
  2911. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.backgroundColor != (highlightItem ? 'rgba(29, 161, 242, 0.25)' : '')) {
  2912. /** @type {HTMLElement} */ ($item.firstElementChild).style.backgroundColor = highlightItem ? 'rgba(29, 161, 242, 0.25)' : ''
  2913. }
  2914. }
  2915.  
  2916. $previousItem = $item
  2917. hidPreviousItem = hideItem
  2918. // If we hid a heading, keep hiding everything after it until we hit a tweet
  2919. if (!(previousItemType == 'HEADING' && itemType == null)) {
  2920. previousItemType = itemType
  2921. }
  2922. }
  2923.  
  2924. log(`processed ${$timeline.children.length} timeline item${s($timeline.children.length)} in ${Date.now() - startTime}ms`, itemTypes, `hid ${hiddenItemCount}`, hiddenItemTypes)
  2925. }
  2926.  
  2927. function onTitleChange(title) {
  2928. log('title changed', {title: title.split(ltr ? ' / ' : ' \\ ')[ltr ? 0 : 1], path: location.pathname})
  2929.  
  2930. if (checkforDisabledHomeTimeline()) return
  2931.  
  2932. // Ignore leading notification counts in titles, e.g. '(1) Following'
  2933. let notificationCount = ''
  2934. if (TITLE_NOTIFICATION_RE.test(title)) {
  2935. notificationCount = TITLE_NOTIFICATION_RE.exec(title)[0]
  2936. title = title.replace(TITLE_NOTIFICATION_RE, '')
  2937. }
  2938.  
  2939. let homeNavigationWasUsed = homeNavigationIsBeingUsed
  2940. homeNavigationIsBeingUsed = false
  2941.  
  2942. if (title == getString('TWITTER')) {
  2943. // Mobile uses "Twitter" when viewing a photo - we need to let these process
  2944. // so the next page will be re-processed when the photo is closed.
  2945. if (mobile && URL_PHOTO_RE.test(location.pathname)) {
  2946. log('viewing a photo on mobile')
  2947. }
  2948. // Ignore Flash of Uninitialised Title when navigating to a page for the
  2949. // first time.
  2950. else {
  2951. log('ignoring Flash of Uninitialised Title')
  2952. return
  2953. }
  2954. }
  2955.  
  2956. let newPage = title.split(ltr ? ' / ' : ' \\ ')[ltr ? 0 : 1]
  2957.  
  2958. // Only allow the same page to re-process after a title change on desktop if
  2959. // the "Customize your view" dialog is currently open.
  2960. if (newPage == currentPage && !(desktop && location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW)) {
  2961. log('ignoring duplicate title change')
  2962. currentNotificationCount = notificationCount
  2963. return
  2964. }
  2965.  
  2966. // Search terms are shown in the title
  2967. if (currentPath == PagePaths.SEARCH && location.pathname == PagePaths.SEARCH) {
  2968. log('ignoring title change on Search page')
  2969. currentNotificationCount = notificationCount
  2970. return
  2971. }
  2972.  
  2973. // On desktop, stay on the separated tweets timeline when…
  2974. if (desktop && currentPage == separatedTweetsTimelineTitle &&
  2975. // …the title has changed back to the main timeline…
  2976. (newPage == getString('HOME')) &&
  2977. // …the Home nav link or Following / Home header _wasn't_ clicked and…
  2978. !homeNavigationWasUsed &&
  2979. (
  2980. // …the user viewed a photo.
  2981. URL_PHOTO_RE.test(location.pathname) ||
  2982. // …the user stopped viewing a photo.
  2983. URL_PHOTO_RE.test(currentPath) ||
  2984. // …the user opened or used the "Customize your view" dialog.
  2985. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  2986. // …the user closed the "Customize your view" dialog.
  2987. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  2988. // …the user opened the "Send via Direct Message" dialog.
  2989. location.pathname == PagePaths.COMPOSE_MESSAGE ||
  2990. // …the user closed the "Send via Direct Message" dialog.
  2991. currentPath == PagePaths.COMPOSE_MESSAGE ||
  2992. // …the user opened the compose Tweet dialog.
  2993. location.pathname == PagePaths.COMPOSE_TWEET ||
  2994. // …the user closed the compose Tweet dialog.
  2995. currentPath == PagePaths.COMPOSE_TWEET ||
  2996. // …the notification count in the title changed.
  2997. notificationCount != currentNotificationCount
  2998. )) {
  2999. log('ignoring title change on separated tweets timeline')
  3000. currentNotificationCount = notificationCount
  3001. currentPath = location.pathname
  3002. setTitle(separatedTweetsTimelineTitle)
  3003. return
  3004. }
  3005.  
  3006. // Restore display of the separated tweets timelne if it's the last one we
  3007. // saw, and the user navigated back home without using the Home navigation
  3008. // item.
  3009. if (location.pathname == PagePaths.HOME &&
  3010. currentPath != PagePaths.HOME &&
  3011. !homeNavigationWasUsed &&
  3012. lastMainTimelineTitle != null &&
  3013. separatedTweetsTimelineTitle != null &&
  3014. lastMainTimelineTitle == separatedTweetsTimelineTitle) {
  3015. log('restoring display of the separated tweets timeline')
  3016. currentNotificationCount = notificationCount
  3017. currentPath = location.pathname
  3018. setTitle(separatedTweetsTimelineTitle)
  3019. return
  3020. }
  3021.  
  3022. // Assumption: all non-FOUT, non-duplicate title changes are navigation, which
  3023. // need the page to be re-processed.
  3024.  
  3025. currentPage = newPage
  3026. currentNotificationCount = notificationCount
  3027. currentPath = location.pathname
  3028.  
  3029. if (isOnMainTimelinePage()) {
  3030. lastMainTimelineTitle = currentPage
  3031. }
  3032.  
  3033. log('processing new page')
  3034.  
  3035. processCurrentPage()
  3036. }
  3037.  
  3038. /**
  3039. * Processes all Twitter Blue checks inside an element.
  3040. * @param {HTMLElement} $el
  3041. */
  3042. function processBlueChecks($el) {
  3043. for (let $svg of $el.querySelectorAll(`${Selectors.VERIFIED_TICK}:not(.tnt_blue_check)`)) {
  3044. if (isBlueVerified($svg)) {
  3045. blueCheck($svg)
  3046. }
  3047. }
  3048. }
  3049.  
  3050. function processCurrentPage() {
  3051. if (pageObservers.length > 0) {
  3052. log(
  3053. `disconnecting ${pageObservers.length} page observer${s(pageObservers.length)}`,
  3054. pageObservers.map(observer => observer['name'])
  3055. )
  3056. pageObservers.forEach(observer => observer.disconnect())
  3057. pageObservers = []
  3058. }
  3059.  
  3060. // Hooks for styling pages
  3061. $body.classList.toggle('Community', isOnCommunityPage())
  3062. $body.classList.toggle('Explore', isOnExplorePage())
  3063. $body.classList.toggle('HideSidebar', shouldHideSidebar())
  3064. $body.classList.toggle('List', isOnListPage())
  3065. $body.classList.toggle('MainTimeline', isOnMainTimelinePage())
  3066. $body.classList.toggle('Notifications', isOnNotificationsPage())
  3067. $body.classList.toggle('Profile', isOnProfilePage())
  3068. if (!isOnProfilePage()) {
  3069. $body.classList.remove('Blocked', 'NoMedia')
  3070. }
  3071. $body.classList.toggle('QuoteTweets', isOnQuoteTweetsPage())
  3072. $body.classList.toggle('Tweet', isOnIndividualTweetPage())
  3073. $body.classList.toggle('Search', isOnSearchPage())
  3074. $body.classList.toggle('MobilePhoto', mobile && URL_PHOTO_RE.test(location.pathname))
  3075. $body.classList.remove('TabbedTimeline')
  3076. $body.classList.remove('SeparatedTweets')
  3077.  
  3078. if (desktop) {
  3079. if (config.twitterBlueChecks != 'ignore' || config.fullWidthContent && (isOnMainTimelinePage() || isOnListPage())) {
  3080. observeSidebar()
  3081. } else {
  3082. $body.classList.remove('Sidebar')
  3083. }
  3084. }
  3085.  
  3086. if (config.twitterBlueChecks != 'ignore' && (isOnSearchPage() || isOnExplorePage())) {
  3087. observeSearchForm()
  3088. }
  3089.  
  3090. if (isOnMainTimelinePage()) {
  3091. tweakMainTimelinePage()
  3092. }
  3093. else {
  3094. removeMobileTimelineHeaderElements()
  3095. }
  3096.  
  3097. if (isOnProfilePage()) {
  3098. tweakProfilePage()
  3099. }
  3100. else if (isOnFollowListPage()) {
  3101. tweakFollowListPage()
  3102. }
  3103. else if (isOnIndividualTweetPage()) {
  3104. tweakIndividualTweetPage()
  3105. }
  3106. else if (isOnNotificationsPage()) {
  3107. tweakNotificationsPage()
  3108. }
  3109. else if (isOnSearchPage()) {
  3110. tweakSearchPage()
  3111. }
  3112. else if (isOnQuoteTweetsPage()) {
  3113. tweakQuoteTweetsPage()
  3114. }
  3115. else if (isOnListPage()) {
  3116. tweakListPage()
  3117. }
  3118. else if (isOnExplorePage()) {
  3119. tweakExplorePage()
  3120. }
  3121. else if (isOnBookmarksPage()) {
  3122. tweakBookmarksPage()
  3123. }
  3124. else if (isOnCommunitiesPage()) {
  3125. tweakCommunitiesPage()
  3126. }
  3127. else if (isOnCommunityPage()) {
  3128. tweakCommunityPage()
  3129. }
  3130. else if (isOnCommunityMembersPage()) {
  3131. tweakCommunityMembersPage()
  3132. }
  3133.  
  3134. // Om mobile, these are pages instead of modals
  3135. if (mobile) {
  3136. if (URL_CIRCLE_RE.test(currentPath)) {
  3137. tweakMobileTwitterCirclePage()
  3138. }
  3139. else if (currentPath == PagePaths.COMPOSE_TWEET) {
  3140. tweakMobileComposeTweetPage()
  3141. }
  3142. }
  3143. }
  3144.  
  3145. /**
  3146. * The mobile version of Twitter reuses heading elements between screens, so we
  3147. * always remove any elements which could be there from the previous page and
  3148. * re-add them later when needed.
  3149. */
  3150. function removeMobileTimelineHeaderElements() {
  3151. if (mobile) {
  3152. document.querySelector('#tnt_separated_tweets_tab')?.remove()
  3153. }
  3154. }
  3155.  
  3156. /**
  3157. * Sets the page name in <title>, retaining any current notification count.
  3158. * @param {string} page
  3159. */
  3160. function setTitle(page) {
  3161. document.title = ltr ? (
  3162. `${currentNotificationCount}${page} / ${getString('TWITTER')}`
  3163. ) : (
  3164. `${currentNotificationCount}${getString('TWITTER')} \\ ${page}`
  3165. )
  3166. }
  3167.  
  3168. /**
  3169. * @param {import("./types").TimelineItemType} type
  3170. * @returns {boolean}
  3171. */
  3172. function shouldHideListTimelineItem(type) {
  3173. switch (type) {
  3174. case 'RETWEET':
  3175. case 'RETWEETED_QUOTE_TWEET':
  3176. return config.listRetweets == 'hide'
  3177. case 'UNAVAILABLE_QUOTE_TWEET':
  3178. return config.hideUnavailableQuoteTweets
  3179. case 'UNAVAILABLE_RETWEET':
  3180. return config.hideUnavailableQuoteTweets || config.listRetweets == 'hide'
  3181. default:
  3182. return false
  3183. }
  3184. }
  3185.  
  3186. /**
  3187. * @param {import("./types").TimelineItemType} type
  3188. * @param {string} page
  3189. * @returns {boolean}
  3190. */
  3191. function shouldHideMainTimelineItem(type, page) {
  3192. switch (type) {
  3193. case 'QUOTE_TWEET':
  3194. return shouldHideSharedTweet(config.quoteTweets, page)
  3195. case 'RETWEET':
  3196. return shouldHideSharedTweet(config.retweets, page)
  3197. case 'RETWEETED_QUOTE_TWEET':
  3198. return shouldHideSharedTweet(config.retweets, page) || shouldHideSharedTweet(config.quoteTweets, page)
  3199. case 'TWEET':
  3200. return page == separatedTweetsTimelineTitle
  3201. case 'UNAVAILABLE_QUOTE_TWEET':
  3202. return config.hideUnavailableQuoteTweets || shouldHideSharedTweet(config.quoteTweets, page)
  3203. case 'UNAVAILABLE_RETWEET':
  3204. return config.hideUnavailableQuoteTweets || shouldHideSharedTweet(config.retweets, page)
  3205. default:
  3206. return true
  3207. }
  3208. }
  3209.  
  3210. /**
  3211. * @param {import("./types").TimelineItemType} type
  3212. * @returns {boolean}
  3213. */
  3214. function shouldHideOtherTimelineItem(type) {
  3215. switch (type) {
  3216. case 'QUOTE_TWEET':
  3217. case 'RETWEET':
  3218. case 'RETWEETED_QUOTE_TWEET':
  3219. case 'TWEET':
  3220. case 'UNAVAILABLE':
  3221. case 'UNAVAILABLE_QUOTE_TWEET':
  3222. case 'UNAVAILABLE_RETWEET':
  3223. return false
  3224. default:
  3225. return true
  3226. }
  3227. }
  3228.  
  3229. /**
  3230. * @param {import("./types").SharedTweetsConfig} config
  3231. * @param {string} page
  3232. * @returns {boolean}
  3233. */
  3234. function shouldHideSharedTweet(config, page) {
  3235. switch (config) {
  3236. case 'hide': return true
  3237. case 'ignore': return page == separatedTweetsTimelineTitle
  3238. case 'separate': return page != separatedTweetsTimelineTitle
  3239. }
  3240. }
  3241.  
  3242. async function tweakBookmarksPage() {
  3243. if (config.twitterBlueChecks != 'ignore') {
  3244. observeTimeline(currentPage, {
  3245. classifyTweets: false,
  3246. })
  3247. }
  3248. }
  3249.  
  3250. async function tweakExplorePage() {
  3251. if (!config.hideExplorePageContents) return
  3252.  
  3253. let $searchInput = await getElement('input[data-testid="SearchBox_Search_Input"]', {
  3254. name: 'explore page search input',
  3255. stopIf: () => !isOnExplorePage(),
  3256. })
  3257. if (!$searchInput) return
  3258.  
  3259. log('focusing search input')
  3260. $searchInput.focus()
  3261.  
  3262. if (mobile) {
  3263. // The back button appears after the search input is focused on mobile. When
  3264. // you tap it or otherwise navigate back, it's replaced with the slide-out
  3265. // menu button and Explore page contents are shown - we want to skip that.
  3266. let $backButton = await getElement('div[data-testid="app-bar-back"]', {
  3267. name: 'back button',
  3268. stopIf: () => !isOnExplorePage(),
  3269. })
  3270. if (!$backButton) return
  3271.  
  3272. pageObservers.push(
  3273. observeElement($backButton.parentElement, (mutations) => {
  3274. mutations.forEach((mutation) => {
  3275. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3276. if ($el.querySelector('[data-testid="DashButton_ProfileIcon_Link"]')) {
  3277. log('slide-out menu button appeared, going back to skip Explore page')
  3278. history.go(-2)
  3279. }
  3280. })
  3281. })
  3282. }, 'back button parent')
  3283. )
  3284. }
  3285. }
  3286.  
  3287. function tweakCommunitiesPage() {
  3288. observeTimeline(currentPage)
  3289. }
  3290.  
  3291. function tweakCommunityPage() {
  3292. if (config.twitterBlueChecks != 'ignore') {
  3293. observeTimeline(currentPage, {
  3294. classifyTweets: false,
  3295. isTabbed: true,
  3296. tabbedTimelineContainerSelector: `${Selectors.PRIMARY_COLUMN} > div > div:last-child`,
  3297. onTimelineAppeared() {
  3298. // The About tab has static content at the top which can include a check
  3299. if (/\/about\/?$/.test(location.pathname)) {
  3300. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  3301. }
  3302. }
  3303. })
  3304. }
  3305. }
  3306.  
  3307. function tweakCommunityMembersPage() {
  3308. if (config.twitterBlueChecks != 'ignore') {
  3309. observeTimeline(currentPage, {
  3310. classifyTweets: false,
  3311. isTabbed: true,
  3312. timelineSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  3313. })
  3314. }
  3315. }
  3316.  
  3317. function tweakFollowListPage() {
  3318. if (config.twitterBlueChecks != 'ignore') {
  3319. observeTimeline(currentPage, {
  3320. classifyTweets: false,
  3321. })
  3322. }
  3323. }
  3324.  
  3325. function tweakIndividualTweetPage() {
  3326. observeTimeline(currentPage, {
  3327. hideHeadings: false,
  3328. })
  3329. }
  3330.  
  3331. function tweakListPage() {
  3332. observeTimeline(currentPage, {
  3333. hideHeadings: false,
  3334. })
  3335. }
  3336.  
  3337. async function tweakTweetBox() {
  3338. if (config.twitterBlueChecks == 'ignore') return
  3339.  
  3340. let $tweetTextarea = await getElement(`${desktop ? 'div[data-testid="primaryColumn"]': 'main'} label[data-testid^="tweetTextarea"]`, {
  3341. name: 'tweet textarea',
  3342. stopIf: pageIsNot(currentPage),
  3343. })
  3344. if (!$tweetTextarea) return
  3345.  
  3346. /** @type {HTMLElement} */
  3347. let $typeaheadDropdown
  3348.  
  3349. pageObservers.push(
  3350. observeElement($tweetTextarea.parentElement.parentElement.parentElement.parentElement, (mutations) => {
  3351. for (let mutation of mutations) {
  3352. if ($typeaheadDropdown && mutations.some(mutation => Array.from(mutation.removedNodes).includes($typeaheadDropdown))) {
  3353. disconnectPageObserver('tweet textarea typeahead dropdown')
  3354. $typeaheadDropdown = null
  3355. }
  3356. for (let $addedNode of mutation.addedNodes) {
  3357. if ($addedNode instanceof HTMLElement && $addedNode.getAttribute('id')?.startsWith('typeaheadDropdown')) {
  3358. $typeaheadDropdown = $addedNode
  3359. pageObservers.push(
  3360. observeElement($typeaheadDropdown, () => {
  3361. processBlueChecks($typeaheadDropdown)
  3362. }, 'tweet textarea typeahead dropdown')
  3363. )
  3364. }
  3365. }
  3366. }
  3367. }, 'tweet textarea typeahead dropdown container')
  3368. )
  3369. }
  3370.  
  3371. function tweakMainTimelinePage() {
  3372. if (desktop) {
  3373. tweakTweetBox()
  3374. }
  3375.  
  3376. let $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3377.  
  3378. // "Which version of the main timeline are we on?" hooks for styling
  3379. $body.classList.toggle('TabbedTimeline', $timelineTabs != null)
  3380. $body.classList.toggle('SeparatedTweets', isOnSeparatedTweetsTimeline())
  3381.  
  3382. if ($timelineTabs == null) {
  3383. warn('could not find timeline tabs')
  3384. return
  3385. }
  3386.  
  3387. tweakTimelineTabs($timelineTabs)
  3388.  
  3389. // If there are pinned lists, the timeline tabs <nav> will be replaced when they load
  3390. pageObservers.push(
  3391. observeElement($timelineTabs.parentElement, (mutations) => {
  3392. let timelineTabsReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($timelineTabs))
  3393. if (timelineTabsReplaced) {
  3394. log('timeline tabs replaced')
  3395. $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3396. tweakTimelineTabs($timelineTabs)
  3397. }
  3398. }, 'timeline tabs nav container')
  3399. )
  3400.  
  3401. observeTimeline(currentPage, {
  3402. isTabbed: true,
  3403. onTabChanged: () => {
  3404. wasForYouTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:first-child > a[aria-selected="true"]'))
  3405. },
  3406. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child > div',
  3407. })
  3408. }
  3409.  
  3410. function tweakMobileComposeTweetPage() {
  3411. tweakTweetBox()
  3412. }
  3413.  
  3414. async function tweakMobileTwitterCirclePage() {
  3415. let $tabContentContainer = await getElement('main > div > div > div:last-child:not(:first-child)', {
  3416. name: 'circle page tab content container',
  3417. stopIf: pageIsNot(currentPage),
  3418. })
  3419.  
  3420. if ($tabContentContainer == null) return
  3421.  
  3422. pageObservers.push(observeElement($tabContentContainer, (mutations) => {
  3423. // Ignore loading indicators on initial load of each tab
  3424. if (!mutations.length || mutations.some(mutation => mutation.addedNodes[0]?.querySelector('svg circle'))) {
  3425. return
  3426. }
  3427. observeTwitterCircleTabContent($tabContentContainer.firstElementChild, pageObservers, disconnectPageObserver)
  3428. }, 'circle page tab content container'))
  3429. }
  3430.  
  3431. async function tweakTimelineTabs($timelineTabs) {
  3432. let $followingTabLink = /** @type {HTMLElement} */ ($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a'))
  3433.  
  3434. if (config.alwaysUseLatestTweets && !document.title.startsWith(separatedTweetsTimelineTitle)) {
  3435. let isForYouTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:first-child > a[aria-selected="true"]'))
  3436. if (isForYouTabSelected && (!wasForYouTabSelected || config.hideForYouTimeline)) {
  3437. log('switching to Following timeline')
  3438. $followingTabLink.click()
  3439. wasForYouTabSelected = false
  3440. } else {
  3441. wasForYouTabSelected = isForYouTabSelected
  3442. }
  3443. }
  3444.  
  3445. if (config.retweets == 'separate' || config.quoteTweets == 'separate') {
  3446. let $newTab = /** @type {HTMLElement} */ ($timelineTabs.querySelector('#tnt_separated_tweets_tab'))
  3447. if ($newTab) {
  3448. log('separated tweets timeline tab already present')
  3449. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  3450. }
  3451. else {
  3452. log('inserting separated tweets tab')
  3453. $newTab = /** @type {HTMLElement} */ ($followingTabLink.parentElement.cloneNode(true))
  3454. $newTab.id = 'tnt_separated_tweets_tab'
  3455. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  3456.  
  3457. // This script assumes navigation has occurred when the document title
  3458. // changes, so by changing the title we fake navigation to a non-existent
  3459. // page representing the separated tweets timeline.
  3460. $newTab.querySelector('a').addEventListener('click', (e) => {
  3461. e.preventDefault()
  3462. e.stopPropagation()
  3463. if (!document.title.startsWith(separatedTweetsTimelineTitle)) {
  3464. // The sparated tweets tab belongs to the Following tab
  3465. let isFollowingTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  3466. if (!isFollowingTabSelected) {
  3467. log('switching to the Following tab for separated tweets')
  3468. $followingTabLink.click()
  3469. }
  3470. setTitle(separatedTweetsTimelineTitle)
  3471. }
  3472. window.scrollTo({top: 0})
  3473. })
  3474. $followingTabLink.parentElement.insertAdjacentElement('afterend', $newTab)
  3475.  
  3476. // Return to the main timeline view when any other tab is clicked
  3477. $followingTabLink.parentElement.parentElement.addEventListener('click', () => {
  3478. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  3479. log('setting title to Home')
  3480. homeNavigationIsBeingUsed = true
  3481. setTitle(getString('HOME'))
  3482. }
  3483. })
  3484.  
  3485. // Return to the main timeline when the Home nav link is clicked
  3486. let $homeNavLink = await getElement(Selectors.NAV_HOME_LINK, {
  3487. name: 'home nav link',
  3488. stopIf: pathIsNot(currentPath),
  3489. })
  3490. if ($homeNavLink && !$homeNavLink.dataset.tweakNewTwitterListener) {
  3491. $homeNavLink.addEventListener('click', () => {
  3492. homeNavigationIsBeingUsed = true
  3493. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  3494. setTitle(getString('HOME'))
  3495. }
  3496. })
  3497. $homeNavLink.dataset.tweakNewTwitterListener = 'true'
  3498. }
  3499. }
  3500. } else {
  3501. removeMobileTimelineHeaderElements()
  3502. }
  3503. }
  3504.  
  3505. function tweakNotificationsPage() {
  3506. let $navigationTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3507. if ($navigationTabs == null) {
  3508. warn('could not find Notifications tabs')
  3509. return
  3510. }
  3511.  
  3512. if (config.hideVerifiedNotificationsTab) {
  3513. let isVerifiedTabSelected = Boolean($navigationTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  3514. if (isVerifiedTabSelected) {
  3515. log('switching to All tab')
  3516. $navigationTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a')?.click()
  3517. }
  3518. }
  3519.  
  3520. if (config.twitterBlueChecks != 'ignore') {
  3521. observeTimeline(currentPage, {
  3522. classifyTweets: false,
  3523. isTabbed: true,
  3524. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  3525. })
  3526. }
  3527. }
  3528.  
  3529. function tweakProfilePage() {
  3530. if (config.twitterBlueChecks != 'ignore') {
  3531. if (mobile) {
  3532. processBlueChecks(document.querySelector(Selectors.MOBILE_TIMELINE_HEADER_NEW))
  3533. }
  3534. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  3535. }
  3536. observeTimeline(currentPage)
  3537. if (desktop && config.hideSidebarContent) {
  3538. observeProfileBlockedStatus(currentPage)
  3539. observeProfileSidebar(currentPage)
  3540. }
  3541. }
  3542.  
  3543. function tweakQuoteTweetsPage() {
  3544. if (config.twitterBlueChecks != 'ignore') {
  3545. observeTimeline(currentPage)
  3546. }
  3547. }
  3548.  
  3549. function tweakSearchPage() {
  3550. let $searchTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  3551. if ($searchTabs != null) {
  3552. if (config.defaultToLatestSearch) {
  3553. let isTopTabSelected = Boolean($searchTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a[aria-selected="true"]'))
  3554. if (isTopTabSelected) {
  3555. log('switching to Latest tab')
  3556. $searchTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a')?.click()
  3557. }
  3558. }
  3559. } else {
  3560. warn('could not find Search tabs')
  3561. }
  3562.  
  3563. observeTimeline(currentPage, {
  3564. hideHeadings: false,
  3565. isTabbed: true,
  3566. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child > div',
  3567. })
  3568. }
  3569. //#endregion
  3570.  
  3571. //#region Main
  3572. async function main() {
  3573. let $settings = /** @type {HTMLScriptElement} */ (document.querySelector('script#tnt_settings'))
  3574. if ($settings) {
  3575. try {
  3576. Object.assign(config, JSON.parse($settings.innerText))
  3577. } catch(e) {
  3578. error('error parsing initial settings', e)
  3579. }
  3580.  
  3581. let settingsChangeObserver = new MutationObserver(() => {
  3582. /** @type {Partial<import("./types").Config>} */
  3583. let configChanges
  3584. try {
  3585. configChanges = JSON.parse($settings.innerText)
  3586. } catch(e) {
  3587. error('error parsing incoming settings change', e)
  3588. return
  3589. }
  3590.  
  3591. if ('debug' in configChanges) {
  3592. log('disabling debug mode')
  3593. debug = configChanges.debug
  3594. log('enabled debug mode')
  3595. configureThemeCss()
  3596. return
  3597. }
  3598.  
  3599. Object.assign(config, configChanges)
  3600. configChanged(configChanges)
  3601. })
  3602. settingsChangeObserver.observe($settings, {childList: true})
  3603. }
  3604.  
  3605. if (config.debug) {
  3606. debug = true
  3607. }
  3608.  
  3609. let $appWrapper = await getElement('#layers + div', {name: 'app wrapper'})
  3610.  
  3611. $html = document.querySelector('html')
  3612. $body = document.body
  3613. lang = $html.lang
  3614. dir = $html.dir
  3615. ltr = dir == 'ltr'
  3616. let lastFlexDirection
  3617.  
  3618. observeElement($appWrapper, () => {
  3619. let flexDirection = getComputedStyle($appWrapper).flexDirection
  3620.  
  3621. mobile = flexDirection == 'column'
  3622. desktop = !mobile
  3623.  
  3624. /** @type {'mobile' | 'desktop'} */
  3625. let version = mobile ? 'mobile' : 'desktop'
  3626.  
  3627. if (version != config.version) {
  3628. log('setting version to', version)
  3629. config.version = version
  3630. // Let the options page know which version is being used
  3631. storeConfigChanges({version})
  3632. }
  3633.  
  3634. if (lastFlexDirection == null) {
  3635. log('initial config', {config, lang, version})
  3636.  
  3637. // One-time setup
  3638. checkReactNativeStylesheet()
  3639. observeBodyBackgroundColor()
  3640. observeColor()
  3641.  
  3642. // Repeatable configuration setup
  3643. configureSeparatedTweetsTimelineTitle()
  3644. configureCss()
  3645. observeHtmlFontSize()
  3646. observePopups()
  3647.  
  3648. // Start watching for page changes
  3649. observeTitle()
  3650. }
  3651. else if (flexDirection != lastFlexDirection) {
  3652. observeHtmlFontSize()
  3653. configChanged({version})
  3654. }
  3655.  
  3656. $body.classList.toggle('Mobile', mobile)
  3657. $body.classList.toggle('Desktop', desktop)
  3658.  
  3659. lastFlexDirection = flexDirection
  3660. }, 'app wrapper class attribute for version changes (mobile ↔ desktop)', {
  3661. attributes: true,
  3662. attributeFilter: ['class']
  3663. })
  3664. }
  3665.  
  3666. /**
  3667. * @param {Partial<import("./types").Config>} changes
  3668. */
  3669. function configChanged(changes) {
  3670. log('config changed', changes)
  3671.  
  3672. configureCss()
  3673. configureFont()
  3674. configureNavFontSizeCss()
  3675. configureThemeCss()
  3676. observePopups()
  3677.  
  3678. // Only re-process the current page if navigation wasn't already triggered
  3679. // while applying the following config changes (if there were any).
  3680. let navigationTriggered = (
  3681. configureSeparatedTweetsTimelineTitle() ||
  3682. checkforDisabledHomeTimeline()
  3683. )
  3684. if (!navigationTriggered) {
  3685. processCurrentPage()
  3686. }
  3687. }
  3688.  
  3689. main()
  3690. //#endregion
  3691.  
  3692. }()