Control Panel for Twitter

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

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

  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 127
  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 {HTMLElement} */
  26. let $reactRoot
  27. /** @type {string} */
  28. let lang
  29. /** @type {string} */
  30. let dir
  31. /** @type {boolean} */
  32. let ltr
  33.  
  34. //#region Default config
  35. /**
  36. * @type {import("./types").Config}
  37. */
  38. const config = {
  39. debug: false,
  40. // Shared
  41. addAddMutedWordMenuItem: true,
  42. alwaysUseLatestTweets: true,
  43. defaultToLatestSearch: false,
  44. disableHomeTimeline: false,
  45. disabledHomeTimelineRedirect: 'notifications',
  46. disableTweetTextFormatting: false,
  47. dontUseChirpFont: false,
  48. dropdownMenuFontWeight: true,
  49. fastBlock: true,
  50. followButtonStyle: 'monochrome',
  51. hideAnalyticsNav: true,
  52. hideBlueReplyFollowedBy: false,
  53. hideBlueReplyFollowing: false,
  54. hideBookmarkButton: false,
  55. hideBookmarkMetrics: true,
  56. hideBookmarksNav: false,
  57. hideCommunitiesNav: false,
  58. hideConnectNav: true,
  59. hideExplorePageContents: true,
  60. hideFollowingMetrics: true,
  61. hideForYouTimeline: true,
  62. hideHelpCenterNav: true,
  63. hideHomeHeading: true,
  64. hideKeyboardShortcutsNav: false,
  65. hideLikeMetrics: true,
  66. hideListsNav: false,
  67. hideMetrics: false,
  68. hideMonetizationNav: true,
  69. hideMoreTweets: true,
  70. hideProfileRetweets: false,
  71. hideQuoteTweetMetrics: true,
  72. hideReplyMetrics: true,
  73. hideRetweetMetrics: true,
  74. hideSeeNewTweets: false,
  75. hideShareTweetButton: false,
  76. hideSubscriptions: true,
  77. hideTotalTweetsMetrics: true,
  78. hideTweetAnalyticsLinks: false,
  79. hideTwitterAdsNav: true,
  80. hideTwitterBlueReplies: false,
  81. hideTwitterBlueUpsells: true,
  82. hideUnavailableQuoteTweets: true,
  83. hideVerifiedNotificationsTab: true,
  84. hideViews: true,
  85. hideWhoToFollowEtc: true,
  86. listRetweets: 'ignore',
  87. mutableQuoteTweets: true,
  88. mutedQuotes: [],
  89. quoteTweets: 'ignore',
  90. reducedInteractionMode: false,
  91. replaceLogo: true,
  92. retweets: 'separate',
  93. showBlueReplyFollowersCount: true,
  94. tweakQuoteTweetsPage: true,
  95. twitterBlueChecks: 'replace',
  96. uninvertFollowButtons: true,
  97. // Experiments
  98. // none currently
  99. // Desktop only
  100. fullWidthContent: false,
  101. fullWidthMedia: true,
  102. hideAccountSwitcher: false,
  103. hideExploreNav: true,
  104. hideExploreNavWithSidebar: true,
  105. hideMessagesDrawer: true,
  106. hideSidebarContent: true,
  107. navBaseFontSize: true,
  108. navDensity: 'default',
  109. showRelevantPeople: false,
  110. // Mobile only
  111. hideAppNags: true,
  112. hideMessagesBottomNavItem: false,
  113. }
  114. //#endregion
  115.  
  116. //#region Locales
  117. /**
  118. * @type {{[key: string]: import("./types").Locale}}
  119. */
  120. const locales = {
  121. 'ar-x-fm': {
  122. ADD_MUTED_WORD: 'اضافة كلمة مكتومة',
  123. HOME: 'الرئيسيّة',
  124. MUTE_THIS_CONVERSATION: 'كتم هذه المحادثه',
  125. POST_ALL: 'نشر الكل',
  126. QUOTE_TWEET: 'اقتباس التغريدة',
  127. QUOTE_TWEETS: 'تغريدات اقتباس',
  128. RETWEETS: 'إعادات التغريد',
  129. SHARED_TWEETS: 'التغريدات المشتركة',
  130. SHOW: 'إظهار',
  131. SHOW_MORE_REPLIES: 'عرض المزيد من الردود',
  132. TURN_OFF_RETWEETS: 'تعطيل إعادة التغريد',
  133. TURN_ON_RETWEETS: 'تفعيل إعادة التغريد',
  134. TWEET: 'غرّدي',
  135. TWEET_ALL: 'تغريد الكل',
  136. TWITTER: 'تويتر',
  137. },
  138. ar: {
  139. ADD_MUTED_WORD: 'اضافة كلمة مكتومة',
  140. HOME: 'الرئيسيّة',
  141. MUTE_THIS_CONVERSATION: 'كتم هذه المحادثه',
  142. POST_ALL: 'نشر الكل',
  143. QUOTE_TWEET: 'اقتباس التغريدة',
  144. QUOTE_TWEETS: 'تغريدات اقتباس',
  145. RETWEETS: 'إعادات التغريد',
  146. SHARED_TWEETS: 'التغريدات المشتركة',
  147. SHOW: 'إظهار',
  148. SHOW_MORE_REPLIES: 'عرض المزيد من الردود',
  149. TURN_OFF_RETWEETS: 'تعطيل إعادة التغريد',
  150. TURN_ON_RETWEETS: 'تفعيل إعادة التغريد',
  151. TWEET: 'تغريد',
  152. TWEET_ALL: 'تغريد الكل',
  153. },
  154. bg: {
  155. ADD_MUTED_WORD: 'Добавяне на заглушена дума',
  156. HOME: 'Начало',
  157. MUTE_THIS_CONVERSATION: 'Заглушаване на разговора',
  158. POST_ALL: 'Публикуване на всичко',
  159. QUOTE_TWEET: 'Цитиране на туита',
  160. QUOTE_TWEETS: 'Туитове с цитат',
  161. RETWEETS: 'Ретуитове',
  162. SHARED_TWEETS: 'Споделени туитове',
  163. SHOW: 'Показване',
  164. SHOW_MORE_REPLIES: 'Показване на още отговори',
  165. TURN_OFF_RETWEETS: 'Изключване на ретуитовете',
  166. TURN_ON_RETWEETS: 'Включване на ретуитовете',
  167. TWEET: 'تغريد',
  168. TWEET_ALL: 'تغريد الكل',
  169. },
  170. bn: {
  171. ADD_MUTED_WORD: 'নীরব করা শব্দ যোগ করুন',
  172. HOME: 'হোম',
  173. MUTE_THIS_CONVERSATION: 'এই কথা-বার্তা নীরব করুন',
  174. POST_ALL: 'সবকটি পোস্ট করুন',
  175. QUOTE_TWEET: 'টুইট উদ্ধৃত করুন',
  176. QUOTE_TWEETS: 'টুইট উদ্ধৃতিগুলো',
  177. RETWEETS: 'পুনঃটুইটগুলো',
  178. SHARED_TWEETS: 'ভাগ করা টুইটগুলি',
  179. SHOW: 'দেখান',
  180. SHOW_MORE_REPLIES: 'আরও উত্তর দেখান',
  181. TURN_OFF_RETWEETS: 'পুনঃ টুইটগুলি বন্ধ করুন',
  182. TURN_ON_RETWEETS: 'পুনঃ টুইটগুলি চালু করুন',
  183. TWEET: 'টুইট',
  184. TWEET_ALL: 'সব টুইট করুন',
  185. TWITTER: 'টুইটার',
  186. },
  187. ca: {
  188. ADD_MUTED_WORD: 'Afegeix una paraula silenciada',
  189. HOME: 'Inici',
  190. MUTE_THIS_CONVERSATION: 'Silencia la conversa',
  191. POST_ALL: 'Publica-ho tot',
  192. QUOTE_TWEET: 'Cita el tuit',
  193. QUOTE_TWEETS: 'Tuits amb cita',
  194. RETWEETS: 'Retuits',
  195. SHARED_TWEETS: 'Tuits compartits',
  196. SHOW: 'Mostra',
  197. SHOW_MORE_REPLIES: 'Mostra més respostes',
  198. TURN_OFF_RETWEETS: 'Desactiva els retuits',
  199. TURN_ON_RETWEETS: 'Activa els retuits',
  200. TWEET: 'Tuita',
  201. TWEET_ALL: 'Tuita-ho tot',
  202. },
  203. cs: {
  204. ADD_MUTED_WORD: 'Přidat slovo na seznam skrytých slov',
  205. HOME: 'Hlavní stránka',
  206. MUTE_THIS_CONVERSATION: 'Skrýt tuto konverzaci',
  207. POST_ALL: 'Publikovat vše',
  208. QUOTE_TWEET: 'Citovat Tweet',
  209. QUOTE_TWEETS: 'Tweety s citací',
  210. RETWEETS: 'Retweety',
  211. SHARED_TWEETS: 'Sdílené tweety',
  212. SHOW: 'Zobrazit',
  213. SHOW_MORE_REPLIES: 'Zobrazit další odpovědi',
  214. TURN_OFF_RETWEETS: 'Vypnout retweety',
  215. TURN_ON_RETWEETS: 'Zapnout retweety',
  216. TWEET: 'Tweetovat',
  217. TWEET_ALL: 'Tweetnout vše',
  218. },
  219. da: {
  220. ADD_MUTED_WORD: 'Tilføj skjult ord',
  221. HOME: 'Forside',
  222. MUTE_THIS_CONVERSATION: 'Skjul denne samtale',
  223. POST_ALL: 'Post alle',
  224. QUOTE_TWEET: 'Citér Tweet',
  225. QUOTE_TWEETS: 'Citat-Tweets',
  226. SHARED_TWEETS: 'Delte tweets',
  227. SHOW: 'Vis',
  228. SHOW_MORE_REPLIES: 'Vis flere svar',
  229. TURN_OFF_RETWEETS: 'Slå Retweets fra',
  230. TURN_ON_RETWEETS: 'Slå Retweets til',
  231. TWEET_ALL: 'Tweet alt',
  232. },
  233. de: {
  234. ADD_MUTED_WORD: 'Stummgeschaltetes Wort hinzufügen',
  235. HOME: 'Startseite',
  236. MUTE_THIS_CONVERSATION: 'Diese Konversation stummschalten',
  237. POST_ALL: 'Alle posten',
  238. QUOTE_TWEET: 'Tweet zitieren',
  239. QUOTE_TWEETS: 'Zitierte Tweets',
  240. SHARED_TWEETS: 'Geteilte Tweets',
  241. SHOW: 'Anzeigen',
  242. SHOW_MORE_REPLIES: 'Mehr Antworten anzeigen',
  243. TURN_OFF_RETWEETS: 'Retweets ausschalten',
  244. TURN_ON_RETWEETS: 'Retweets einschalten',
  245. TWEET: 'Twittern',
  246. TWEET_ALL: 'Alle twittern',
  247. },
  248. el: {
  249. ADD_MUTED_WORD: 'Προσθήκη λέξης σε σίγαση',
  250. HOME: 'Αρχική σελίδα',
  251. MUTE_THIS_CONVERSATION: 'Σίγαση αυτής της συζήτησης',
  252. POST_ALL: 'Δημοσίευση όλων',
  253. QUOTE_TWEET: 'Παράθεση Tweet',
  254. QUOTE_TWEETS: 'Tweet με παράθεση',
  255. RETWEETS: 'Retweet',
  256. SHARED_TWEETS: 'Κοινόχρηστα Tweets',
  257. SHOW: 'Εμφάνιση',
  258. SHOW_MORE_REPLIES: 'Εμφάνιση περισσότερων απαντήσεων',
  259. TURN_OFF_RETWEETS: 'Απενεργοποίηση των Retweet',
  260. TURN_ON_RETWEETS: 'Ενεργοποίηση των Retweet',
  261. TWEET_ALL: 'Δημοσίευση όλων ως Tweet',
  262. },
  263. en: {
  264. ADD_MUTED_WORD: 'Add muted word',
  265. HOME: 'Home',
  266. MUTE_THIS_CONVERSATION: 'Mute this conversation',
  267. POST_ALL: 'Post all',
  268. QUOTE_TWEET: 'Quote Tweet',
  269. QUOTE_TWEETS: 'Quote Tweets',
  270. RETWEETS: 'Retweets',
  271. SHARED_TWEETS: 'Shared Tweets',
  272. SHOW: 'Show',
  273. SHOW_MORE_REPLIES: 'Show more replies',
  274. TURN_OFF_RETWEETS: 'Turn off Retweets',
  275. TURN_ON_RETWEETS: 'Turn on Retweets',
  276. TWEET: 'Tweet',
  277. TWEET_ALL: 'Tweet all',
  278. TWITTER: 'Twitter',
  279. },
  280. es: {
  281. ADD_MUTED_WORD: 'Añadir palabra silenciada',
  282. HOME: 'Inicio',
  283. MUTE_THIS_CONVERSATION: 'Silenciar esta conversación',
  284. POST_ALL: 'Publicar todo',
  285. QUOTE_TWEET: 'Citar Tweet',
  286. QUOTE_TWEETS: 'Tweets citados',
  287. SHARED_TWEETS: 'Tweets compartidos',
  288. SHOW: 'Mostrar',
  289. SHOW_MORE_REPLIES: 'Mostrar más respuestas',
  290. TURN_OFF_RETWEETS: 'Desactivar Retweets',
  291. TURN_ON_RETWEETS: 'Activar Retweets',
  292. TWEET: 'Twittear',
  293. TWEET_ALL: 'Twittear todo',
  294. },
  295. eu: {
  296. ADD_MUTED_WORD: 'Gehitu isilarazitako hitza',
  297. HOME: 'Hasiera',
  298. MUTE_THIS_CONVERSATION: 'Isilarazi elkarrizketa hau',
  299. POST_ALL: 'Post all',
  300. QUOTE_TWEET: 'Txioa apaitu',
  301. QUOTE_TWEETS: 'Aipatu txioak',
  302. RETWEETS: 'Bertxioak',
  303. SHARED_TWEETS: 'Partekatutako',
  304. SHOW: 'Erakutsi',
  305. SHOW_MORE_REPLIES: 'Erakutsi erantzun gehiago',
  306. TURN_OFF_RETWEETS: 'Desaktibatu birtxioak',
  307. TURN_ON_RETWEETS: 'Aktibatu birtxioak',
  308. TWEET: 'Txio',
  309. TWEET_ALL: 'Txiotu guztiak',
  310. },
  311. fa: {
  312. ADD_MUTED_WORD: 'افزودن واژه خموش‌سازی شده',
  313. HOME: 'خانه',
  314. MUTE_THIS_CONVERSATION: 'خموش‌سازی این گفتگو',
  315. POST_ALL: 'پست کردن همه',
  316. QUOTE_TWEET: 'نقل‌توییت',
  317. QUOTE_TWEETS: 'نقل‌توییت‌ها',
  318. RETWEETS: 'بازتوییت‌ها',
  319. SHARED_TWEETS: 'توییتهای مشترک',
  320. SHOW: 'نمایش',
  321. SHOW_MORE_REPLIES: 'نمایش پاسخ‌های بیشتر',
  322. TURN_OFF_RETWEETS: 'غیرفعال‌سازی بازتوییت‌ها',
  323. TURN_ON_RETWEETS: 'فعال سازی بازتوییت‌ها',
  324. TWEET: 'توییت',
  325. TWEET_ALL: 'توییت به همه',
  326. TWITTER: 'توییتر',
  327. },
  328. fi: {
  329. ADD_MUTED_WORD: 'Lisää hiljennetty sana',
  330. HOME: 'Etusivu',
  331. MUTE_THIS_CONVERSATION: 'Hiljennä tämä keskustelu',
  332. POST_ALL: 'Julkaise kaikki',
  333. QUOTE_TWEET: 'Twiitin lainaus',
  334. QUOTE_TWEETS: 'Twiitin lainaukset',
  335. RETWEETS: 'Uudelleentwiittaukset',
  336. SHARED_TWEETS: 'Jaetut twiitit',
  337. SHOW: 'Näytä',
  338. SHOW_MORE_REPLIES: 'Näytä lisää vastauksia',
  339. TURN_OFF_RETWEETS: 'Poista uudelleentwiittaukset käytöstä',
  340. TURN_ON_RETWEETS: 'Ota uudelleentwiittaukset käyttöön',
  341. TWEET: 'Twiittaa',
  342. TWEET_ALL: 'Twiittaa kaikki',
  343. },
  344. fil: {
  345. ADD_MUTED_WORD: 'Idagdag ang naka-mute na salita',
  346. HOME: 'Home',
  347. MUTE_THIS_CONVERSATION: 'I-mute ang usapang ito',
  348. POST_ALL: 'I-post lahat',
  349. QUOTE_TWEET: 'Quote na Tweet',
  350. QUOTE_TWEETS: 'Mga Quote na Tweet',
  351. RETWEETS: 'Mga Retweet',
  352. SHARED_TWEETS: 'Mga Ibinahaging Tweet',
  353. SHOW: 'Ipakita',
  354. SHOW_MORE_REPLIES: 'Magpakita pa ng mga sagot',
  355. TURN_OFF_RETWEETS: 'I-off ang Retweets',
  356. TURN_ON_RETWEETS: 'I-on ang Retweets',
  357. TWEET: 'Mag-tweet',
  358. TWEET_ALL: 'I-tweet lahat',
  359. },
  360. fr: {
  361. ADD_MUTED_WORD: 'Ajouter un mot masqué',
  362. HOME: 'Accueil',
  363. MUTE_THIS_CONVERSATION: 'Masquer cette conversation',
  364. POST_ALL: 'Tout publier',
  365. QUOTE_TWEET: 'Citer le Tweet',
  366. QUOTE_TWEETS: 'Tweets cités',
  367. SHARED_TWEETS: 'Tweets partagés',
  368. SHOW: 'Afficher',
  369. SHOW_MORE_REPLIES: 'Voir plus de réponses',
  370. TURN_OFF_RETWEETS: 'Désactiver les Retweets',
  371. TURN_ON_RETWEETS: 'Activer les Retweets',
  372. TWEET: 'Tweeter',
  373. TWEET_ALL: 'Tout tweeter',
  374. },
  375. ga: {
  376. ADD_MUTED_WORD: 'Cuir focal balbhaithe leis',
  377. HOME: 'Baile',
  378. MUTE_THIS_CONVERSATION: 'Balbhaigh an comhrá seo',
  379. POST_ALL: 'Post all',
  380. QUOTE_TWEET: 'Cuir Ráiteas Leis',
  381. QUOTE_TWEETS: 'Luaigh Tvuíteanna',
  382. RETWEETS: 'Atweetanna',
  383. SHARED_TWEETS: 'Tweetanna Roinnte',
  384. SHOW: 'Taispeáin',
  385. SHOW_MORE_REPLIES: 'Taispeáin tuilleadh freagraí',
  386. TURN_OFF_RETWEETS: 'Cas as Atweetanna',
  387. TURN_ON_RETWEETS: 'Cas Atweetanna air',
  388. TWEET_ALL: 'Tweetáil gach rud',
  389. },
  390. gl: {
  391. ADD_MUTED_WORD: 'Engadir palabra silenciada',
  392. HOME: 'Inicio',
  393. MUTE_THIS_CONVERSATION: 'Silenciar esta conversa',
  394. POST_ALL: 'Post all',
  395. QUOTE_TWEET: 'Citar chío',
  396. QUOTE_TWEETS: 'Chíos citados',
  397. RETWEETS: 'Rechouchíos',
  398. SHARED_TWEETS: 'Chíos compartidos',
  399. SHOW: 'Amosar',
  400. SHOW_MORE_REPLIES: 'Amosar máis respostas',
  401. TURN_OFF_RETWEETS: 'Desactivar os rechouchíos',
  402. TURN_ON_RETWEETS: 'Activar os rechouchíos',
  403. TWEET: 'Chío',
  404. TWEET_ALL: 'Chiar todo',
  405. },
  406. gu: {
  407. ADD_MUTED_WORD: 'જોડાણ અટકાવેલો શબ્દ ઉમેરો',
  408. HOME: 'હોમ',
  409. MUTE_THIS_CONVERSATION: 'આ વાર્તાલાપનું જોડાણ અટકાવો',
  410. POST_ALL: 'બધા પોસ્ટ કરો',
  411. QUOTE_TWEET: 'અવતરણની સાથે ટ્વીટ કરો',
  412. QUOTE_TWEETS: 'અવતરણની સાથે ટ્વીટ્સ',
  413. RETWEETS: 'પુનટ્વીટ્સ',
  414. SHARED_TWEETS: 'શેર કરેલી ટ્વીટ્સ',
  415. SHOW: 'બતાવો',
  416. SHOW_MORE_REPLIES: 'વધુ પ્રત્યુતરો દર્શાવો',
  417. TURN_OFF_RETWEETS: 'પુનટ્વીટ્સ બંધ કરો',
  418. TURN_ON_RETWEETS: 'પુનટ્વીટ્સ ચાલુ કરો',
  419. TWEET: 'ટ્વીટ',
  420. TWEET_ALL: 'બધાને ટ્વીટ કરો',
  421. },
  422. he: {
  423. ADD_MUTED_WORD: 'הוסף מילה מושתקת',
  424. HOME: 'דף הבית',
  425. MUTE_THIS_CONVERSATION: 'להשתיק את השיחה הזאת',
  426. POST_ALL: 'פרסום הכל',
  427. QUOTE_TWEET: 'ציטוט ציוץ',
  428. QUOTE_TWEETS: 'ציוצי ציטוט',
  429. RETWEETS: 'ציוצים מחדש',
  430. SHARED_TWEETS: 'ציוצים משותפים',
  431. SHOW: 'הצג',
  432. SHOW_MORE_REPLIES: 'הצג תשובות נוספות',
  433. TURN_OFF_RETWEETS: 'כבה ציוצים מחדש',
  434. TURN_ON_RETWEETS: 'הפעל ציוצים מחדש',
  435. TWEET: 'צייץ',
  436. TWEET_ALL: 'צייץ הכול',
  437. TWITTER: 'טוויטר',
  438. },
  439. hi: {
  440. ADD_MUTED_WORD: 'म्यूट किया गया शब्द जोड़ें',
  441. HOME: 'होम',
  442. MUTE_THIS_CONVERSATION: 'इस बातचीत को म्यूट करें',
  443. POST_ALL: 'सभी पोस्ट करें',
  444. QUOTE_TWEET: 'ट्वीट क्वोट करें',
  445. QUOTE_TWEETS: 'कोट ट्वीट्स',
  446. RETWEETS: 'रीट्वीट्स',
  447. SHARED_TWEETS: 'साझा किए गए ट्वीट',
  448. SHOW: 'दिखाएं',
  449. SHOW_MORE_REPLIES: 'और अधिक जवाब दिखाएँ',
  450. TURN_OFF_RETWEETS: 'रीट्वीट बंद करें',
  451. TURN_ON_RETWEETS: 'रीट्वीट चालू करें',
  452. TWEET: 'ट्वीट करें',
  453. TWEET_ALL: 'सभी ट्वीट करें',
  454. },
  455. hr: {
  456. ADD_MUTED_WORD: 'Dodaj onemogućenu riječ',
  457. HOME: 'Naslovnica',
  458. MUTE_THIS_CONVERSATION: 'Isključi zvuk ovog razgovora',
  459. POST_ALL: 'Objavi sve',
  460. QUOTE_TWEET: 'Citiraj Tweet',
  461. QUOTE_TWEETS: 'Citirani tweetovi',
  462. RETWEETS: 'Proslijeđeni tweetovi',
  463. SHARED_TWEETS: 'Dijeljeni tweetovi',
  464. SHOW: 'Prikaži',
  465. SHOW_MORE_REPLIES: 'Prikaži još odgovora',
  466. TURN_OFF_RETWEETS: 'Isključi proslijeđene tweetove',
  467. TURN_ON_RETWEETS: 'Uključi proslijeđene tweetove',
  468. TWEET_ALL: 'Tweetaj sve',
  469. },
  470. hu: {
  471. ADD_MUTED_WORD: 'Elnémított szó hozzáadása',
  472. HOME: 'Kezdőlap',
  473. MUTE_THIS_CONVERSATION: 'Beszélgetés némítása',
  474. POST_ALL: 'Az összes közzététele',
  475. QUOTE_TWEET: 'Tweet idézése',
  476. QUOTE_TWEETS: 'Tweet-idézések',
  477. RETWEETS: 'Retweetek',
  478. SHARED_TWEETS: 'Megosztott tweetek',
  479. SHOW: 'Megjelenítés',
  480. SHOW_MORE_REPLIES: 'Több válasz megjelenítése',
  481. TURN_OFF_RETWEETS: 'Retweetek kikapcsolása',
  482. TURN_ON_RETWEETS: 'Retweetek bekapcsolása',
  483. TWEET: 'Tweetelj',
  484. TWEET_ALL: 'Tweet küldése mindenkinek',
  485. },
  486. id: {
  487. ADD_MUTED_WORD: 'Tambahkan kata kunci yang dibisukan',
  488. HOME: 'Beranda',
  489. MUTE_THIS_CONVERSATION: 'Bisukan percakapan ini',
  490. POST_ALL: 'Posting semua',
  491. QUOTE_TWEET: 'Kutip Tweet',
  492. QUOTE_TWEETS: 'Tweet Kutipan',
  493. RETWEETS: 'Retweet',
  494. SHARED_TWEETS: 'Tweet yang Dibagikan',
  495. SHOW: 'Tampilkan',
  496. SHOW_MORE_REPLIES: 'Tampilkan balasan lainnya',
  497. TURN_OFF_RETWEETS: 'Matikan Retweet',
  498. TURN_ON_RETWEETS: 'Nyalakan Retweet',
  499. TWEET_ALL: 'Tweet semua',
  500. },
  501. it: {
  502. ADD_MUTED_WORD: 'Aggiungi parola o frase silenziata',
  503. HOME: 'Home',
  504. MUTE_THIS_CONVERSATION: 'Silenzia questa conversazione',
  505. POST_ALL: 'Pubblica tutto',
  506. QUOTE_TWEET: 'Cita Tweet',
  507. QUOTE_TWEETS: 'Tweet di citazione',
  508. RETWEETS: 'Retweet',
  509. SHARED_TWEETS: 'Tweet condivisi',
  510. SHOW: 'Mostra',
  511. SHOW_MORE_REPLIES: 'Mostra altre risposte',
  512. TURN_OFF_RETWEETS: 'Disattiva Retweet',
  513. TURN_ON_RETWEETS: 'Attiva Retweet',
  514. TWEET: 'Twitta',
  515. TWEET_ALL: 'Twitta tutto',
  516. },
  517. ja: {
  518. ADD_MUTED_WORD: 'ミュートするキーワードを追加',
  519. HOME: 'ホーム',
  520. MUTE_THIS_CONVERSATION: 'この会話をミュート',
  521. POST_ALL: 'すべて投稿',
  522. QUOTE_TWEET: '引用ツイート',
  523. QUOTE_TWEETS: '引用ツイート',
  524. RETWEETS: 'リツイート',
  525. SHARED_TWEETS: '共有ツイート',
  526. SHOW: '表示',
  527. SHOW_MORE_REPLIES: '返信をさらに表示',
  528. TURN_OFF_RETWEETS: 'リツイートをオフにする',
  529. TURN_ON_RETWEETS: 'リツイートをオンにする',
  530. TWEET: 'ツイートする',
  531. TWEET_ALL: 'すべてツイート',
  532. },
  533. kn: {
  534. ADD_MUTED_WORD: 'ಸದ್ದಡಗಿಸಿದ ಪದವನ್ನು ಸೇರಿಸಿ',
  535. HOME: 'ಹೋಮ್',
  536. MUTE_THIS_CONVERSATION: 'ಈ ಸಂವಾದವನ್ನು ಸದ್ದಡಗಿಸಿ',
  537. POST_ALL: 'ಎಲ್ಲವನ್ನೂ ಪೋಸ್ಟ್ ಮಾಡಿ',
  538. QUOTE_TWEET: 'ಟ್ವೀಟ್ ಕೋಟ್ ಮಾಡಿ',
  539. QUOTE_TWEETS: 'ಕೋಟ್ ಟ್ವೀಟ್‌ಗಳು',
  540. RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳು',
  541. SHARED_TWEETS: 'ಹಂಚಿದ ಟ್ವೀಟ್‌ಗಳು',
  542. SHOW: 'ತೋರಿಸಿ',
  543. SHOW_MORE_REPLIES: 'ಇನ್ನಷ್ಟು ಪ್ರತಿಕ್ರಿಯೆಗಳನ್ನು ತೋರಿಸಿ',
  544. TURN_OFF_RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳನ್ನು ಆಫ್ ಮಾಡಿ',
  545. TURN_ON_RETWEETS: 'ಮರುಟ್ವೀಟ್‌ಗಳನ್ನು ಆನ್ ಮಾಡಿ',
  546. TWEET: 'ಟ್ವೀಟ್',
  547. TWEET_ALL: 'ಎಲ್ಲಾ ಟ್ವೀಟ್ ಮಾಡಿ',
  548. },
  549. ko: {
  550. ADD_MUTED_WORD: '뮤트할 단어 추가하기',
  551. HOME: '홈',
  552. MUTE_THIS_CONVERSATION: '이 대화 뮤트하기',
  553. POST_ALL: '모두 게시하기',
  554. QUOTE_TWEET: '트윗 인용하기',
  555. QUOTE_TWEETS: '트윗 인용하기',
  556. RETWEETS: '리트윗',
  557. SHARED_TWEETS: '공유 트윗',
  558. SHOW: '표시',
  559. SHOW_MORE_REPLIES: '더 많은 답글 보기',
  560. TURN_OFF_RETWEETS: '리트윗 끄기',
  561. TURN_ON_RETWEETS: '리트윗 켜기',
  562. TWEET: '트윗',
  563. TWEET_ALL: '모두 트윗하기',
  564. TWITTER: '트위터',
  565. },
  566. mr: {
  567. ADD_MUTED_WORD: 'म्यूट केलेले शब्द सामील करा',
  568. HOME: 'होम',
  569. MUTE_THIS_CONVERSATION: 'ही चर्चा म्यूट करा',
  570. POST_ALL: 'सर्व पोस्ट करा',
  571. QUOTE_TWEET: 'ट्विट वर भाष्य करा',
  572. QUOTE_TWEETS: 'भाष्य ट्विट्स',
  573. RETWEETS: 'पुनर्ट्विट्स',
  574. SHARED_TWEETS: 'सामायिक ट्विट',
  575. SHOW: 'दाखवा',
  576. SHOW_MORE_REPLIES: 'अधिक प्रत्युत्तरे दाखवा',
  577. TURN_OFF_RETWEETS: 'पुनर्ट्विट्स बंद करा',
  578. TURN_ON_RETWEETS: 'पुनर्ट्विट्स चालू करा',
  579. TWEET: 'ट्विट',
  580. TWEET_ALL: 'सर्व ट्विट करा',
  581. },
  582. ms: {
  583. ADD_MUTED_WORD: 'Tambahkan perkataan yang disenyapkan',
  584. HOME: 'Laman Utama',
  585. MUTE_THIS_CONVERSATION: 'Senyapkan perbualan ini',
  586. POST_ALL: 'Siarkan semua',
  587. QUOTE_TWEET: 'Petik Tweet',
  588. QUOTE_TWEETS: 'Tweet Petikan',
  589. RETWEETS: 'Tweet semula',
  590. SHARED_TWEETS: 'Tweet Berkongsi',
  591. SHOW: 'Tunjukkan',
  592. SHOW_MORE_REPLIES: 'Tunjukkan lagi balasan',
  593. TURN_OFF_RETWEETS: 'Matikan Tweet semula',
  594. TURN_ON_RETWEETS: 'Hidupkan Tweet semula',
  595. TWEET_ALL: 'Tweet semua',
  596. },
  597. nb: {
  598. ADD_MUTED_WORD: 'Skjul nytt ord',
  599. HOME: 'Hjem',
  600. MUTE_THIS_CONVERSATION: 'Skjul denne samtalen',
  601. POST_ALL: 'Publiser alle',
  602. QUOTE_TWEET: 'Sitat-Tweet',
  603. QUOTE_TWEETS: 'Sitat-Tweets',
  604. SHARED_TWEETS: 'Delte tweets',
  605. SHOW: 'Vis',
  606. SHOW_MORE_REPLIES: 'Vis flere svar',
  607. TURN_OFF_RETWEETS: 'Slå av Retweets',
  608. TURN_ON_RETWEETS: 'Slå på Retweets',
  609. TWEET_ALL: 'Tweet alle',
  610. },
  611. nl: {
  612. ADD_MUTED_WORD: 'Genegeerd woord toevoegen',
  613. HOME: 'Startpagina',
  614. MUTE_THIS_CONVERSATION: 'Dit gesprek negeren',
  615. POST_ALL: 'Alles plaatsen',
  616. QUOTE_TWEET: 'Citeer Tweet',
  617. QUOTE_TWEETS: 'Geciteerde Tweets',
  618. SHARED_TWEETS: 'Gedeelde Tweets',
  619. SHOW: 'Weergeven',
  620. SHOW_MORE_REPLIES: 'Meer antwoorden tonen',
  621. TURN_OFF_RETWEETS: 'Retweets uitschakelen',
  622. TURN_ON_RETWEETS: 'Retweets inschakelen',
  623. TWEET: 'Tweeten',
  624. TWEET_ALL: 'Alles tweeten',
  625. },
  626. pl: {
  627. ADD_MUTED_WORD: 'Dodaj wyciszone słowo',
  628. HOME: 'Główna',
  629. MUTE_THIS_CONVERSATION: 'Wycisz tę rozmowę',
  630. POST_ALL: 'Opublikuj wszystko',
  631. QUOTE_TWEET: 'Cytuj Tweeta',
  632. QUOTE_TWEETS: 'Cytaty z Tweeta',
  633. RETWEETS: 'Tweety podane dalej',
  634. SHARED_TWEETS: 'Udostępnione Tweety',
  635. SHOW: 'Pokaż',
  636. SHOW_MORE_REPLIES: 'Pokaż więcej odpowiedzi',
  637. TURN_OFF_RETWEETS: 'Wyłącz Tweety podane dalej',
  638. TURN_ON_RETWEETS: 'Włącz Tweety podane dalej',
  639. TWEET_ALL: 'Tweetnij wszystko',
  640. },
  641. pt: {
  642. ADD_MUTED_WORD: 'Adicionar palavra silenciada',
  643. HOME: 'Página Inicial',
  644. MUTE_THIS_CONVERSATION: 'Silenciar esta conversa',
  645. POST_ALL: 'Publicar tudo',
  646. QUOTE_TWEET: 'Comentar o Tweet',
  647. QUOTE_TWEETS: 'Tweets com comentário',
  648. SHARED_TWEETS: 'Tweets Compartilhados',
  649. SHOW: 'Mostrar',
  650. SHOW_MORE_REPLIES: 'Mostrar mais respostas',
  651. TURN_OFF_RETWEETS: 'Desativar Retweets',
  652. TURN_ON_RETWEETS: 'Ativar Retweets',
  653. TWEET: 'Tweetar',
  654. TWEET_ALL: 'Tweetar tudo',
  655. },
  656. ro: {
  657. ADD_MUTED_WORD: 'Adaugă cuvântul ignorat',
  658. HOME: 'Pagina principală',
  659. MUTE_THIS_CONVERSATION: 'Ignoră această conversație',
  660. POST_ALL: 'Postează tot',
  661. QUOTE_TWEET: 'Citează Tweetul',
  662. QUOTE_TWEETS: 'Tweeturi cu citat',
  663. RETWEETS: 'Retweeturi',
  664. SHARED_TWEETS: 'Tweeturi partajate',
  665. SHOW: 'Afișează',
  666. SHOW_MORE_REPLIES: 'Afișează mai multe răspunsuri',
  667. TURN_OFF_RETWEETS: 'Dezactivează Retweeturile',
  668. TURN_ON_RETWEETS: 'Activează Retweeturile',
  669. TWEET_ALL: 'Dă Tweeturi cu tot',
  670. },
  671. ru: {
  672. ADD_MUTED_WORD: 'Добавить игнорируемое слово',
  673. HOME: 'Главная',
  674. MUTE_THIS_CONVERSATION: 'Игнорировать эту переписку',
  675. POST_ALL: 'Опубликовать все',
  676. QUOTE_TWEET: 'Цитировать',
  677. QUOTE_TWEETS: 'Твиты с цитатами',
  678. RETWEETS: 'Ретвиты',
  679. SHARED_TWEETS: 'Общие твиты',
  680. SHOW: 'Показать',
  681. SHOW_MORE_REPLIES: 'Показать еще ответы',
  682. TURN_OFF_RETWEETS: 'Отключить ретвиты',
  683. TURN_ON_RETWEETS: 'Включить ретвиты',
  684. TWEET: 'Твитнуть',
  685. TWEET_ALL: 'Твитнуть все',
  686. TWITTER: 'Твиттер',
  687. },
  688. sk: {
  689. ADD_MUTED_WORD: 'Pridať stíšené slovo',
  690. HOME: 'Domov',
  691. MUTE_THIS_CONVERSATION: 'Stíšiť túto konverzáciu',
  692. POST_ALL: 'Uverejniť všetko',
  693. QUOTE_TWEET: 'Tweet s citátom',
  694. QUOTE_TWEETS: 'Tweety s citátom',
  695. RETWEETS: 'Retweety',
  696. SHARED_TWEETS: 'Zdieľané Tweety',
  697. SHOW: 'Zobraziť',
  698. SHOW_MORE_REPLIES: 'Zobraziť viac odpovedí',
  699. TURN_OFF_RETWEETS: 'Vypnúť retweety',
  700. TURN_ON_RETWEETS: 'Zapnúť retweety',
  701. TWEET: 'Tweetnuť',
  702. TWEET_ALL: 'Tweetnuť všetko',
  703. },
  704. sr: {
  705. ADD_MUTED_WORD: 'Додај игнорисану реч',
  706. HOME: 'Почетна',
  707. MUTE_THIS_CONVERSATION: 'Игнориши овај разговор',
  708. POST_ALL: 'Објави све',
  709. QUOTE_TWEET: 'твит са цитатом',
  710. QUOTE_TWEETS: 'твит(ов)а са цитатом',
  711. RETWEETS: 'Ретвитови',
  712. SHARED_TWEETS: 'Дељени твитови',
  713. SHOW: 'Прикажи',
  714. SHOW_MORE_REPLIES: 'Прикажи још одговора',
  715. TURN_OFF_RETWEETS: 'Искључи ретвитове',
  716. TURN_ON_RETWEETS: 'Укључи ретвитове',
  717. TWEET: 'Твитуј',
  718. TWEET_ALL: 'Твитуј све',
  719. TWITTER: 'Твитер',
  720. },
  721. sv: {
  722. ADD_MUTED_WORD: 'Lägg till ignorerat ord',
  723. HOME: 'Hem',
  724. MUTE_THIS_CONVERSATION: 'Ignorera den här konversationen',
  725. POST_ALL: 'Lägg upp allt',
  726. QUOTE_TWEET: 'Citera Tweet',
  727. QUOTE_TWEETS: 'Citat-tweets',
  728. SHARED_TWEETS: 'Delade tweetsen',
  729. SHOW: 'Visa',
  730. SHOW_MORE_REPLIES: 'Visa fler svar',
  731. TURN_OFF_RETWEETS: 'Stäng av Retweets',
  732. TURN_ON_RETWEETS: 'Slå på Retweets',
  733. TWEET: 'Tweeta',
  734. TWEET_ALL: 'Tweeta allt',
  735. },
  736. ta: {
  737. ADD_MUTED_WORD: 'செயல்மறைத்த வார்த்தையைச் சேர்',
  738. HOME: 'முகப்பு',
  739. MUTE_THIS_CONVERSATION: 'இந்த உரையாடலை செயல்மறை',
  740. POST_ALL: 'எல்லாம் இடுகையிடு',
  741. QUOTE_TWEET: 'ட்விட்டை மேற்கோள் காட்டு',
  742. QUOTE_TWEETS: 'மேற்கோள் கீச்சுகள்',
  743. RETWEETS: 'மறுகீச்சுகள்',
  744. SHARED_TWEETS: 'பகிரப்பட்ட ட்வீட்டுகள்',
  745. SHOW: 'காண்பி',
  746. SHOW_MORE_REPLIES: 'மேலும் பதில்களைக் காண்பி',
  747. TURN_OFF_RETWEETS: 'மறுகீச்சுகளை அணை',
  748. TURN_ON_RETWEETS: 'மறுகீச்சுகளை இயக்கு',
  749. TWEET: 'ட்விட் செய்',
  750. TWEET_ALL: 'அனைத்தையும் ட்விட் செய்',
  751. },
  752. th: {
  753. ADD_MUTED_WORD: 'เพิ่มคำที่ซ่อน',
  754. HOME: 'หน้าแรก',
  755. MUTE_THIS_CONVERSATION: 'ซ่อนบทสนทนานี้',
  756. POST_ALL: 'โพสต์ทั้งหมด',
  757. QUOTE_TWEET: 'อ้างอิงทวีต',
  758. QUOTE_TWEETS: 'ทวีตและคำพูด',
  759. RETWEETS: 'รีทวีต',
  760. SHARED_TWEETS: 'ทวีตที่แชร์',
  761. SHOW: 'แสดง',
  762. SHOW_MORE_REPLIES: 'แสดงการตอบกลับเพิ่มเติม',
  763. TURN_OFF_RETWEETS: 'ปิดรีทวีต',
  764. TURN_ON_RETWEETS: 'เปิดรีทวีต',
  765. TWEET: 'ทวีต',
  766. TWEET_ALL: 'ทวีตทั้งหมด',
  767. TWITTER: 'ทวิตเตอร์',
  768. },
  769. tr: {
  770. ADD_MUTED_WORD: 'Sessize alınacak kelime ekle',
  771. HOME: 'Anasayfa',
  772. MUTE_THIS_CONVERSATION: 'Bu sohbeti sessize al',
  773. POST_ALL: 'Tümünü gönder',
  774. QUOTE_TWEET: 'Tweeti Alıntıla',
  775. QUOTE_TWEETS: 'Alıntı Tweetler',
  776. RETWEETS: 'Retweetler',
  777. SHARED_TWEETS: 'Paylaşılan Tweetler',
  778. SHOW: 'Göster',
  779. SHOW_MORE_REPLIES: 'Daha fazla yanıt göster',
  780. TURN_OFF_RETWEETS: 'Retweetleri kapat',
  781. TURN_ON_RETWEETS: 'Retweetleri aç',
  782. TWEET: 'Tweetle',
  783. TWEET_ALL: 'Hepsini Tweetle',
  784. },
  785. uk: {
  786. ADD_MUTED_WORD: 'Додати слово до списку ігнорування',
  787. HOME: 'Головна',
  788. MUTE_THIS_CONVERSATION: 'Ігнорувати цю розмову',
  789. POST_ALL: 'Опублікувати все',
  790. QUOTE_TWEET: 'Цитувати твіт',
  791. QUOTE_TWEETS: 'Цитовані твіти',
  792. RETWEETS: 'Ретвіти',
  793. SHARED_TWEETS: 'Спільні твіти',
  794. SHOW: 'Показати',
  795. SHOW_MORE_REPLIES: 'Показати більше відповідей',
  796. TURN_OFF_RETWEETS: 'Вимкнути ретвіти',
  797. TURN_ON_RETWEETS: 'Увімкнути ретвіти',
  798. TWEET: 'Твіт',
  799. TWEET_ALL: 'Твітнути все',
  800. TWITTER: 'Твіттер',
  801. },
  802. ur: {
  803. ADD_MUTED_WORD: 'میوٹ شدہ لفظ شامل کریں',
  804. HOME: 'ہوم',
  805. MUTE_THIS_CONVERSATION: 'اس گفتگو کو میوٹ کریں',
  806. POST_ALL: 'Post all',
  807. QUOTE_TWEET: 'ٹویٹ کا حوالہ دیں',
  808. QUOTE_TWEETS: 'ٹویٹ کو نقل کرو',
  809. RETWEETS: 'ریٹویٹس',
  810. SHARED_TWEETS: 'مشترکہ ٹویٹس',
  811. SHOW: 'دکھائیں',
  812. SHOW_MORE_REPLIES: 'مزید جوابات دکھائیں',
  813. TURN_OFF_RETWEETS: 'ری ٹویٹس غیر فعال کریں',
  814. TURN_ON_RETWEETS: 'ری ٹویٹس غیر فعال کریں',
  815. TWEET: 'ٹویٹ',
  816. TWEET_ALL: 'سب کو ٹویٹ کریں',
  817. TWITTER: 'ٹوئٹر',
  818. },
  819. vi: {
  820. ADD_MUTED_WORD: 'Thêm từ tắt tiếng',
  821. HOME: 'Trang chủ',
  822. MUTE_THIS_CONVERSATION: 'Tắt tiếng cuộc trò chuyện này',
  823. POST_ALL: 'Đăng tất cả',
  824. QUOTE_TWEET: 'Trích dẫn Tweet',
  825. QUOTE_TWEETS: 'Tweet trích dẫn',
  826. RETWEETS: 'Các Tweet lại',
  827. SHARED_TWEETS: 'Tweet được chia sẻ',
  828. SHOW: 'Hiện',
  829. SHOW_MORE_REPLIES: 'Hiển thị thêm trả lời',
  830. TURN_OFF_RETWEETS: 'Tắt Tweet lại',
  831. TURN_ON_RETWEETS: 'Bật Tweet lại',
  832. TWEET_ALL: 'Đăng Tweet tất cả',
  833. },
  834. 'zh-Hant': {
  835. ADD_MUTED_WORD: '加入靜音文字',
  836. HOME: '首頁',
  837. MUTE_THIS_CONVERSATION: '將此對話靜音',
  838. POST_ALL: '全部發佈',
  839. QUOTE_TWEET: '引用推文',
  840. QUOTE_TWEETS: '引用的推文',
  841. RETWEETS: '轉推',
  842. SHARED_TWEETS: '分享的推文',
  843. SHOW: '顯示',
  844. SHOW_MORE_REPLIES: '顯示更多回覆',
  845. TURN_OFF_RETWEETS: '關閉轉推',
  846. TURN_ON_RETWEETS: '開啟轉推',
  847. TWEET: '推文',
  848. TWEET_ALL: '推全部內容',
  849. },
  850. zh: {
  851. ADD_MUTED_WORD: '添加要隐藏的字词',
  852. HOME: '主页',
  853. MUTE_THIS_CONVERSATION: '隐藏此对话',
  854. POST_ALL: '全部发布',
  855. QUOTE_TWEET: '引用推文',
  856. QUOTE_TWEETS: '引用推文',
  857. RETWEETS: '转推',
  858. SHARED_TWEETS: '分享的推文',
  859. SHOW: '显示',
  860. SHOW_MORE_REPLIES: '显示更多回复',
  861. TURN_OFF_RETWEETS: '关闭转推',
  862. TURN_ON_RETWEETS: '开启转推',
  863. TWEET: '推文',
  864. TWEET_ALL: '全部发推',
  865. },
  866. }
  867.  
  868. /**
  869. * @param {import("./types").LocaleKey} code
  870. * @returns {string}
  871. */
  872. function getString(code) {
  873. return (locales[lang] || locales['en'])[code] || locales['en'][code];
  874. }
  875. //#endregion
  876.  
  877. //#region Constants
  878. /** @enum {string} */
  879. const PagePaths = {
  880. ADD_MUTED_WORD: '/settings/add_muted_keyword',
  881. BOOKMARKS: '/i/bookmarks',
  882. COMPOSE_MESSAGE: '/messages/compose',
  883. COMPOSE_TWEET: '/compose/tweet',
  884. CONNECT: '/i/connect',
  885. CUSTOMIZE_YOUR_VIEW: '/i/display',
  886. HOME: '/home',
  887. NOTIFICATION_TIMELINE: '/i/timeline',
  888. PROFILE_SETTINGS: '/settings/profile',
  889. SEARCH: '/search',
  890. }
  891.  
  892. /** @enum {string} */
  893. const Selectors = {
  894. BLOCK_MENU_ITEM: '[data-testid="block"]',
  895. DESKTOP_TIMELINE_HEADER: 'div[data-testid="primaryColumn"] > div > div:first-of-type',
  896. DISPLAY_DONE_BUTTON_DESKTOP: '#layers div[role="button"]:not([aria-label])',
  897. DISPLAY_DONE_BUTTON_MOBILE: 'main div[role="button"]:not([aria-label])',
  898. MESSAGES_DRAWER: 'div[data-testid="DMDrawer"]',
  899. MODAL_TIMELINE: '#layers section > h1 + div[aria-label] > div > div > div',
  900. MOBILE_TIMELINE_HEADER_OLD: 'header > div:nth-of-type(2) > div:first-of-type',
  901. MOBILE_TIMELINE_HEADER_NEW: 'div[data-testid="TopNavBar"]',
  902. NAV_HOME_LINK: 'a[data-testid="AppTabBar_Home_Link"]',
  903. PRIMARY_COLUMN: 'div[data-testid="primaryColumn"]',
  904. PRIMARY_NAV_DESKTOP: 'header nav',
  905. PRIMARY_NAV_MOBILE: '#layers nav',
  906. PROMOTED_TWEET_CONTAINER: '[data-testid="placementTracking"]',
  907. SIDEBAR: 'div[data-testid="sidebarColumn"]',
  908. SIDEBAR_WRAPPERS: 'div[data-testid="sidebarColumn"] > div > div > div > div > div',
  909. TIMELINE: 'div[data-testid="primaryColumn"] section > h1 + div[aria-label] > div > div > div',
  910. TIMELINE_HEADING: 'h2[role="heading"]',
  911. TWEET: '[data-testid="tweet"]',
  912. VERIFIED_TICK: 'svg[data-testid="icon-verified"]',
  913. X_LOGO_PATH: 'svg path[d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"]',
  914. }
  915.  
  916. /** @enum {string} */
  917. const Svgs = {
  918. 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',
  919. 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>',
  920. 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>',
  921. 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>',
  922. 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>',
  923. TWITTER_LOGO_PATH: 'M23.643 4.937c-.835.37-1.732.62-2.675.733.962-.576 1.7-1.49 2.048-2.578-.9.534-1.897.922-2.958 1.13-.85-.904-2.06-1.47-3.4-1.47-2.572 0-4.658 2.086-4.658 4.66 0 .364.042.718.12 1.06-3.873-.195-7.304-2.05-9.602-4.868-.4.69-.63 1.49-.63 2.342 0 1.616.823 3.043 2.072 3.878-.764-.025-1.482-.234-2.11-.583v.06c0 2.257 1.605 4.14 3.737 4.568-.392.106-.803.162-1.227.162-.3 0-.593-.028-.877-.082.593 1.85 2.313 3.198 4.352 3.234-1.595 1.25-3.604 1.995-5.786 1.995-.376 0-.747-.022-1.112-.065 2.062 1.323 4.51 2.093 7.14 2.093 8.57 0 13.255-7.098 13.255-13.254 0-.2-.005-.402-.014-.602.91-.658 1.7-1.477 2.323-2.41z',
  924. }
  925.  
  926. /** @enum {string} */
  927. const Images = {
  928. TWITTER_FAVICON: 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAA0pJREFUWAntVk1oE1EQnnlJbFK3KUq9VJPYWgQVD/5QD0qpfweL1YJQoZAULBRPggp6kB78PQn14kHx0jRB0UO9REVFb1YqVBEsbZW2SbVS0B6apEnbbMbZ6qbZdTempqCHPAjvzcw3P5mdmfcAiquYgX+cAVwu/+5AdDMQnSPCHUhQA0hf+Rxy2OjicIvzm+qnKhito0qpb2wvJhWeJgCPP7oPELeHvdJ1VSGf3eOPnSWga0S0Qo9HxEkEusDBuNjbEca8G291nlBxmgDc/ukuIvAJxI6wr+yKCsq1ewLxQ2lZfpQLo8oQ4ZXdCkfnACrGWpyDCl+oQmVn5xuVPU102e2P3qoJkFOhzVb9S7KSnL5jJs/mI+As01PJFPSlZeFSZZoAGBRXBZyq9lk5NrC+e7pJ5en30c+JWk59pZ5vRDOuhAD381c/H/FKz1SMNgCE16rg505r5TT0uLqme93d0fbq+1SeLSeU83Ke0RHYFPGVPcjQfNDUwIa7M665+dQAEEjZoMwZMcEF9RxIDAgBQ2mCcqJ0Z0b+h4MNbZ4RnyOSDbNmE2iRk5jCNgIIckFoZAs4IgfLGrlKGjkzS16iwj6pV9I4mUvCPf73JVytH9nRJj24QHrqU8NCIWrMaGqAC+Ut/3ZzAS63cx4v2K/x/IvQBOCwWzu5KmJGwEJ5PIgeG9nQBDDcXPpFoDjJ7ThvBC6EZxXWkJG+JgAFwGM4KBAOcibeGCn8FQ/hyajXPmSk+1sACogn4hYk7OdiHDFSWipPkPWSmY6mCzIghEEuxJvcEYUvxIdhX2mvmSHDDPBF9AJRnDZTyp+P40671JYLbxiAohDxSTfQIg4oNxgPzCWPHaWQBViOf2jGqVwBaEaxGbAqOFMrp+SefC8eNhoFIY5lXzpmtnMGUB2IbU3JdIqVW9m5zcxINn/hAYKiIexdaTh4srHKORMAP0b28PNgJyGt5gvHzQVYx91QpVcwpRFl/p63HSR1DLbid1OcTpAJQOG7u+KH+aI5Qwj13IsamU5vkUSIc8uGLDa8OtoivV8U5HcydFLtT7hlSDVy2nfxI2Ibg9awuVU8IeJAOMF5m2B6jFs1tM5R9rS3GRP5uSuiihn4DzPwA7z7GDH+43gqAAAAAElFTkSuQmCC',
  929. TWITTER_PIP_FAVICON: 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAALASURBVHgB7VZNchJBFP5eM9FoRWV2WiZmbmBuIJ4g5ASBRWJlRXIC4ASQVUqxCo4QTwDegJzAiYlFXM1YZWmVQD9fQ6YyAwMMGBZW8i2G6e7He1+/3wHuOih4+fWieJhiKsirA0ZbE44fXZUaWDIGBH4/L+UUUB897DMfPf5ermKJUOaRIhTiDlNEBSwZlnkwY2vCuYOEWD/xMrCoKC41utISRlcc3Or2dfnqwHbDcj9X0fbztn9DAHxOoM0xrZILSIBXtR9F0VGKbJIhz7kVi3Lr770yAz4p2iYm188/awVi6lo4Ns4mETEDLz94uTHjIxDDRaWoohhOSjwi/9mKEFjtlKsayAuRM7M2HmFJwCRVIIqLSAAJjS822v0Vaip1E1oKC6XrXtrExjnxnJ6ldoVKFj0+ujywW3FKTTzJoibmAXP+Yt9uBEsrfLbWRelJzS/0B8z4WoKa6zW/1dd83Hlnn0Z0peAQkqNHvNPZi+qIELBWUNU97LLJ4hDESMZSlNmo+b5UTEvC85m0JCipTQREE+BhdzypIwSkLvyn4LKYrEzQkSZCloiyw+xJbnygfxX+VAJrPWnBoC9ixBXdDm4XflD7YajIinFq3L0E45J7fBa3HyEg7mhgeWjPJODu223J/iMsATzhcmp04+ueXTW1OsiD2zIuVfNNLockBAyIkdaaPxHGs3YR0JTQWnGbWkFCQZX5imwCmBoX++nGpONYD1zu2S0a9IN/g3jSNcNnqsy0ww2ZdPJzCKLXWAAy1N6ay2BRAgEcGZ+aqDnaoqdbjw6dhQgYwz1S2xKOQyQ0Phy7vDPr5iH5ITY+elmtpddLFyQzZBTP3xGl3FJ95NzQJ1hiAgMSw5jnJOZvMA/EMBNKSW89kUAAp+45+g+yojRjljL9NoP4GxdLYzk334vy3lYP0HBjhsw97vHf4C/b8RLHAOr+CQAAAABJRU5ErkJggg==',
  930. }
  931.  
  932. const THEME_COLORS = new Set([
  933. 'rgb(29, 155, 240)', // blue
  934. 'rgb(255, 212, 0)', // yellow
  935. 'rgb(244, 33, 46)', // pink
  936. 'rgb(120, 86, 255)', // purple
  937. 'rgb(255, 122, 0)', // orange
  938. 'rgb(0, 186, 124)', // green
  939. ])
  940. // <body> pseudo-selector for pages the full-width content feature works on
  941. const FULL_WIDTH_BODY_PSEUDO = ':is(.Community, .List, .MainTimeline)'
  942. // Matches any notification count at the start of the title
  943. const TITLE_NOTIFICATION_RE = /^\(\d+\+?\) /
  944. // The Communities nav item takes you to /yourusername/communities
  945. const URL_COMMUNITIES_RE = /^\/[a-zA-Z\d_]{1,20}\/communities\/?$/
  946. const URL_COMMUNITY_RE = /^\/i\/communities\/\d+(?:\/about)?\/?$/
  947. const URL_COMMUNITY_MEMBERS_RE = /^\/i\/communities\/\d+\/(?:members|moderators)\/?$/
  948. const URL_DISCOVER_COMMUNITIES_RE = /^\/i\/communities\/suggested\/?/
  949. const URL_LIST_RE = /\/i\/lists\/\d+\/?$/
  950. const URL_MEDIA_RE = /\/(?:photo|video)\/\d\/?$/
  951. const URL_MEDIAVIEWER_RE = /^\/[a-zA-Z\d_]{1,20}\/status\/\d+\/mediaviewer$/i
  952. // Matches URLs which show one of the tabs on a user profile page
  953. const URL_PROFILE_RE = /^\/([a-zA-Z\d_]{1,20})(?:\/(?:with_replies|superfollows|highlights|media|likes))?\/?$/
  954. // Matches URLs which show a user's Followers you know / Followers / Following tab
  955. const URL_PROFILE_FOLLOWS_RE = /^\/[a-zA-Z\d_]{1,20}\/follow(?:ing|ers|ers_you_follow)\/?$/
  956. const URL_TWEET_RE = /^\/([a-zA-Z\d_]{1,20})\/status\/(\d+)\/?$/
  957. const URL_TWEET_LIKES_RETWEETS_RE = /^\/[a-zA-Z\d_]{1,20}\/status\/\d+\/(likes|retweets)\/?$/
  958.  
  959. // The Twitter Media Assist exension adds a new button at the end of the action
  960. // bar (#346)
  961. const TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR = '.tva-download-icon, .tva-modal-download-icon'
  962. //#endregion
  963.  
  964. //#region Variables
  965. /**
  966. * The quoted Tweet associated with a caret menu that's just been opened.
  967. * @type {import("./types").QuotedTweet}
  968. */
  969. let quotedTweet = null
  970.  
  971. /** `true` when a 'Block @${user}' menu item was seen in the last popup. */
  972. let blockMenuItemSeen = false
  973.  
  974. /** Notification count in the title (including trailing space), e.g. `'(1) '`. */
  975. let currentNotificationCount = ''
  976.  
  977. /** Title of the current page, without the `' / Twitter'` suffix. */
  978. let currentPage = ''
  979.  
  980. /** Current `location.pathname`. */
  981. let currentPath = ''
  982.  
  983. /**
  984. * CSS rule in the React Native stylesheet which defines the Chirp font-family
  985. * and fallbacks for the whole app.
  986. * @type {CSSStyleRule}
  987. */
  988. let fontFamilyRule = null
  989.  
  990. /** @type {string} */
  991. let fontSize = null
  992.  
  993. /** Set to `true` when a Home/Following heading or Home nav link is used. */
  994. let homeNavigationIsBeingUsed = false
  995.  
  996. /** Set to `true` when the media modal is open on desktop. */
  997. let isDesktopMediaModalOpen = false
  998.  
  999. /** Set to `true` when the compose tweet modal is open on desktop. */
  1000. let isDesktopComposeTweetModalOpen = false
  1001.  
  1002. /** Set to `true` when a user list modal is open on desktop. */
  1003. let isDesktopUserListModalOpen = false
  1004.  
  1005. /**
  1006. * Cache for the last page title which was used for the main timeline.
  1007. * @type {string}
  1008. */
  1009. let lastMainTimelineTitle = null
  1010.  
  1011. /**
  1012. * MutationObservers active on the current modal.
  1013. * @type {import("./types").Disconnectable[]}
  1014. */
  1015. let modalObservers = []
  1016.  
  1017. /**
  1018. * `true` after the app has initialised.
  1019. * @type {boolean}
  1020. */
  1021. let observingPageChanges = false
  1022.  
  1023. /**
  1024. * MutationObservers active on the current page, or anything else we want to
  1025. * clean up when the user moves off the current page.
  1026. * @type {import("./types").Disconnectable[]}
  1027. */
  1028. let pageObservers = []
  1029.  
  1030. /** `true` when a 'Pin to your profile' menu item was seen in the last popup. */
  1031. let pinMenuItemSeen = false
  1032.  
  1033. /** @type {number} */
  1034. let selectedHomeTabIndex = -1
  1035.  
  1036. /**
  1037. * Title for the fake timeline used to separate out retweets and quote tweets.
  1038. * @type {string}
  1039. */
  1040. let separatedTweetsTimelineTitle = null
  1041.  
  1042. /**
  1043. * The current "Color" setting, which can be changed in "Customize your view".
  1044. * @type {string}
  1045. */
  1046. let themeColor = localStorage.lastThemeColor
  1047.  
  1048. /**
  1049. * `true` when "For you" was the last tab selected on the main timeline.
  1050. */
  1051. let wasForYouTabSelected = false
  1052.  
  1053. function isOnBookmarksPage() {
  1054. return currentPath == PagePaths.BOOKMARKS
  1055. }
  1056.  
  1057. function isOnCommunitiesPage() {
  1058. return URL_COMMUNITIES_RE.test(currentPath)
  1059. }
  1060.  
  1061. function isOnCommunityPage() {
  1062. return URL_COMMUNITY_RE.test(currentPath)
  1063. }
  1064.  
  1065. function isOnCommunityMembersPage() {
  1066. return URL_COMMUNITY_MEMBERS_RE.test(currentPath)
  1067. }
  1068.  
  1069. function isOnDiscoverCommunitiesPage() {
  1070. return URL_DISCOVER_COMMUNITIES_RE.test(currentPath)
  1071. }
  1072.  
  1073. function isOnExplorePage() {
  1074. return currentPath.startsWith('/explore')
  1075. }
  1076.  
  1077. function isOnFollowListPage() {
  1078. return URL_PROFILE_FOLLOWS_RE.test(currentPath)
  1079. }
  1080.  
  1081. function isOnHomeTimeline() {
  1082. return currentPage == getString('HOME')
  1083. }
  1084.  
  1085. function isOnIndividualTweetPage() {
  1086. return URL_TWEET_RE.test(currentPath)
  1087. }
  1088.  
  1089. function isOnListPage() {
  1090. return URL_LIST_RE.test(currentPath)
  1091. }
  1092.  
  1093. function isOnMainTimelinePage() {
  1094. return currentPath == PagePaths.HOME || (
  1095. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW &&
  1096. isOnHomeTimeline() ||
  1097. isOnSeparatedTweetsTimeline()
  1098. )
  1099. }
  1100.  
  1101. function isOnNotificationsPage() {
  1102. return currentPath.startsWith('/notifications')
  1103. }
  1104.  
  1105. function isOnProfilePage() {
  1106. let profilePathUsername = currentPath.match(URL_PROFILE_RE)?.[1]
  1107. if (!profilePathUsername) return false
  1108. // twitter.com/user and its sub-URLs put @user in the title
  1109. return currentPage.toLowerCase().includes(`${ltr ? '@' : ''}${profilePathUsername.toLowerCase()}${!ltr ? '@' : ''}`)
  1110. }
  1111.  
  1112. function isOnQuoteTweetsPage() {
  1113. return currentPath.endsWith('/retweets/with_comments')
  1114. }
  1115.  
  1116. function isOnSearchPage() {
  1117. return currentPath.startsWith('/search') || currentPath.startsWith('/hashtag/')
  1118. }
  1119.  
  1120. function isOnSeparatedTweetsTimeline() {
  1121. return currentPage == separatedTweetsTimelineTitle
  1122. }
  1123.  
  1124. function isOnSettingsPage() {
  1125. return currentPath.startsWith('/settings')
  1126. }
  1127.  
  1128. function shouldHideSidebar() {
  1129. return isOnExplorePage() || isOnDiscoverCommunitiesPage()
  1130. }
  1131.  
  1132. function shouldShowSeparatedTweetsTab() {
  1133. return config.retweets == 'separate' || config.quoteTweets == 'separate'
  1134. }
  1135. //#endregion
  1136.  
  1137. //#region Utility functions
  1138. /**
  1139. * @param {string} role
  1140. * @return {HTMLStyleElement}
  1141. */
  1142. function addStyle(role) {
  1143. let $style = document.createElement('style')
  1144. $style.dataset.insertedBy = 'control-panel-for-twitter'
  1145. $style.dataset.role = role
  1146. document.head.appendChild($style)
  1147. return $style
  1148. }
  1149.  
  1150. /**
  1151. * @param {Element} $svg
  1152. */
  1153. function blueCheck($svg) {
  1154. if (!$svg) {
  1155. warn('blueCheck was given', $svg)
  1156. return
  1157. }
  1158. $svg.classList.add('tnt_blue_check')
  1159. // Safari doesn't support using `d: path(…)` to replace paths in an SVG, so
  1160. // we have to manually patch the path in it.
  1161. if (isSafari && config.twitterBlueChecks == 'replace') {
  1162. $svg.firstElementChild.firstElementChild.setAttribute('d', Svgs.BLUE_LOGO_PATH)
  1163. }
  1164. }
  1165.  
  1166. /**
  1167. * @param {Element} $svgPath
  1168. */
  1169. function twitterLogo($svgPath) {
  1170. // Safari doesn't support using `d: path(…)` to replace paths in an SVG, so
  1171. // we have to manually patch the path in it.
  1172. $svgPath.setAttribute('d', Svgs.TWITTER_LOGO_PATH)
  1173. $svgPath.parentElement.classList.add('tnt_logo')
  1174. }
  1175.  
  1176. /**
  1177. * @param {string} str
  1178. * @return {string}
  1179. */
  1180. function dedent(str) {
  1181. str = str.replace(/^[ \t]*\r?\n/, '')
  1182. let indent = /^[ \t]+/m.exec(str)
  1183. if (indent) str = str.replace(new RegExp('^' + indent[0], 'gm'), '')
  1184. return str.replace(/(\r?\n)[ \t]+$/, '$1')
  1185. }
  1186.  
  1187. /**
  1188. * @param {string} name
  1189. * @param {import("./types").Disconnectable[]} observers
  1190. * @param {string?} type
  1191. */
  1192. function disconnectObserver(name, observers, type = 'observer') {
  1193. for (let i = observers.length -1; i >= 0; i--) {
  1194. let observer = observers[i]
  1195. if ('name' in observer && observer.name == name) {
  1196. observer.disconnect()
  1197. observers.splice(i, 1)
  1198. log(`disconnected ${name} ${type}`)
  1199. }
  1200. }
  1201. }
  1202.  
  1203. function disconnectModalObserver(name) {
  1204. disconnectObserver(name, modalObservers)
  1205. }
  1206.  
  1207. function disconnectAllModalObservers() {
  1208. if (modalObservers.length > 0) {
  1209. log(
  1210. `disconnecting ${modalObservers.length} modal observer${s(modalObservers.length)}`,
  1211. modalObservers.map(observer => observer['name'])
  1212. )
  1213. modalObservers.forEach(observer => observer.disconnect())
  1214. modalObservers = []
  1215. }
  1216. }
  1217.  
  1218. function disconnectPageObserver(name) {
  1219. disconnectObserver(name, pageObservers, 'page observer')
  1220. }
  1221.  
  1222. /**
  1223. * @param {string} selector
  1224. * @param {{
  1225. * name?: string
  1226. * stopIf?: () => boolean
  1227. * timeout?: number
  1228. * context?: Document | HTMLElement
  1229. * }?} options
  1230. * @returns {Promise<HTMLElement | null>}
  1231. */
  1232. function getElement(selector, {
  1233. name = null,
  1234. stopIf = null,
  1235. timeout = Infinity,
  1236. context = document,
  1237. } = {}) {
  1238. return new Promise((resolve) => {
  1239. let startTime = Date.now()
  1240. let rafId
  1241. let timeoutId
  1242.  
  1243. function stop($element, reason) {
  1244. if ($element == null) {
  1245. warn(`stopped waiting for ${name || selector} after ${reason}`)
  1246. }
  1247. else if (Date.now() > startTime) {
  1248. log(`${name || selector} appeared after ${Date.now() - startTime}ms`)
  1249. }
  1250. if (rafId) {
  1251. cancelAnimationFrame(rafId)
  1252. }
  1253. if (timeoutId) {
  1254. clearTimeout(timeoutId)
  1255. }
  1256. resolve($element)
  1257. }
  1258.  
  1259. if (timeout !== Infinity) {
  1260. timeoutId = setTimeout(stop, timeout, null, `${timeout}ms timeout`)
  1261. }
  1262.  
  1263. function queryElement() {
  1264. let $element = context.querySelector(selector)
  1265. if ($element) {
  1266. stop($element)
  1267. }
  1268. else if (stopIf?.() === true) {
  1269. stop(null, 'stopIf condition met')
  1270. }
  1271. else {
  1272. rafId = requestAnimationFrame(queryElement)
  1273. }
  1274. }
  1275.  
  1276. queryElement()
  1277. })
  1278. }
  1279.  
  1280. /**
  1281. * Gets cached user info from React state.
  1282. * @returns {import("./types").UserInfoObject}
  1283. */
  1284. function getUserInfo() {
  1285. /** @type {import("./types").UserInfoObject} */
  1286. let userInfo = {}
  1287. let reactRootContainer = ($reactRoot?.wrappedJSObject ? $reactRoot.wrappedJSObject : $reactRoot)?._reactRootContainer
  1288. if (reactRootContainer) {
  1289. let userEntities = reactRootContainer?._internalRoot?.current?.memoizedState?.element?.props?.children?.props?.store?.getState()?.entities?.users?.entities
  1290. if (userEntities) {
  1291. for (let user of Object.values(userEntities)) {
  1292. userInfo[user.screen_name] = {
  1293. following: user.following,
  1294. followedBy: user.followed_by,
  1295. followersCount: user.followers_count,
  1296. shyBlue: false,
  1297. }
  1298. }
  1299. } else {
  1300. warn('user entities not found')
  1301. }
  1302. } else {
  1303. warn('React root container not found')
  1304. }
  1305. return userInfo
  1306. }
  1307.  
  1308. function log(...args) {
  1309. if (debug) {
  1310. console.log(`${currentPage ? `(${
  1311. currentPage.length < 70 ? currentPage : currentPage.slice(0, 70) + '…'
  1312. })` : ''}`, ...args)
  1313. }
  1314. }
  1315.  
  1316. function warn(...args) {
  1317. if (debug) {
  1318. console.log(`❗ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1319. }
  1320. }
  1321.  
  1322. function error(...args) {
  1323. console.log(`❌ ${currentPage ? `(${currentPage})` : ''}`, ...args)
  1324. }
  1325.  
  1326. /**
  1327. * @param {() => boolean} condition
  1328. * @returns {() => boolean}
  1329. */
  1330. function not(condition) {
  1331. return () => !condition()
  1332. }
  1333.  
  1334. /**
  1335. * Convenience wrapper for the MutationObserver API - the callback is called
  1336. * immediately to support using an observer and its options as a trigger for any
  1337. * change, without looking at MutationRecords.
  1338. * @param {Node} $element
  1339. * @param {MutationCallback} callback
  1340. * @param {string} name
  1341. * @param {MutationObserverInit} options
  1342. * @return {import("./types").NamedMutationObserver}
  1343. */
  1344. function observeElement($element, callback, name = '', options = {childList: true}) {
  1345. if (name) {
  1346. if (options.childList && callback.length > 0) {
  1347. log(`observing ${name}`, $element)
  1348. } else {
  1349. log (`observing ${name}`)
  1350. }
  1351. }
  1352.  
  1353. let observer = new MutationObserver(callback)
  1354. callback([], observer)
  1355. observer.observe($element, options)
  1356. observer['name'] = name
  1357. return observer
  1358. }
  1359.  
  1360. /**
  1361. * @param {string} page
  1362. * @returns {() => boolean}
  1363. */
  1364. function pageIsNot(page) {
  1365. return () => page != currentPage
  1366. }
  1367.  
  1368. /**
  1369. * @param {string} path
  1370. * @returns {() => boolean}
  1371. */
  1372. function pathIsNot(path) {
  1373. return () => path != currentPath
  1374. }
  1375.  
  1376. /**
  1377. * @param {number} n
  1378. * @returns {string}
  1379. */
  1380. function s(n) {
  1381. return n == 1 ? '' : 's'
  1382. }
  1383.  
  1384. /**
  1385. * @param {Element} $tweetButtonText
  1386. */
  1387. function setTweetButtonText($tweetButtonText) {
  1388. let currentText = $tweetButtonText.textContent
  1389. if (currentText == getString('TWEET') || currentText == getString('TWEET_ALL')) return
  1390. $tweetButtonText.textContent = currentText == getString('POST_ALL') ? getString('TWEET_ALL') : getString('TWEET')
  1391. }
  1392.  
  1393. function storeConfigChanges(changes) {
  1394. window.postMessage({type: 'tntConfigChange', changes})
  1395. }
  1396. //#endregion
  1397.  
  1398. //#region Global observers
  1399. const checkReactNativeStylesheet = (() => {
  1400. /** @type {number} */
  1401. let startTime
  1402.  
  1403. return function checkReactNativeStylesheet() {
  1404. if (startTime == null) {
  1405. startTime = Date.now()
  1406. }
  1407.  
  1408. let $style = /** @type {HTMLStyleElement} */ (document.querySelector('style#react-native-stylesheet'))
  1409. if (!$style) {
  1410. warn('React Native stylesheet not found')
  1411. return
  1412. }
  1413.  
  1414. for (let rule of $style.sheet.cssRules) {
  1415. if (!(rule instanceof CSSStyleRule)) continue
  1416.  
  1417. if (fontFamilyRule == null &&
  1418. rule.style.fontFamily &&
  1419. rule.style.fontFamily.includes('TwitterChirp')) {
  1420. fontFamilyRule = rule
  1421. log('found Chirp fontFamily CSS rule in React Native stylesheet')
  1422. configureFont()
  1423. }
  1424.  
  1425. if (themeColor == null &&
  1426. rule.style.backgroundColor &&
  1427. THEME_COLORS.has(rule.style.backgroundColor)) {
  1428. themeColor = rule.style.backgroundColor
  1429. localStorage.lastThemeColor = themeColor
  1430. log(`found initial theme color in React Native stylesheet: ${themeColor}`)
  1431. configureThemeCss()
  1432. }
  1433. }
  1434.  
  1435. let elapsedTime = Date.now() - startTime
  1436. if (fontFamilyRule == null || themeColor == null) {
  1437. if (elapsedTime < 3000) {
  1438. setTimeout(checkReactNativeStylesheet, 100)
  1439. } else {
  1440. warn(`stopped checking React Native stylesheet after ${elapsedTime}ms`)
  1441. }
  1442. } else {
  1443. log(`finished checking React Native stylesheet in ${elapsedTime}ms`)
  1444. }
  1445. }
  1446. })()
  1447.  
  1448. /**
  1449. * When the "Background" setting is changed in "Customize your view", <body>'s
  1450. * backgroundColor is changed and the app is re-rendered, so we need to
  1451. * re-process the current page.
  1452. */
  1453. function observeBodyBackgroundColor() {
  1454. let lastBackgroundColor = null
  1455.  
  1456. observeElement($body, () => {
  1457. let backgroundColor = $body.style.backgroundColor
  1458. if (backgroundColor == lastBackgroundColor) return
  1459.  
  1460. $body.classList.toggle('Default', backgroundColor == 'rgb(255, 255, 255)')
  1461. $body.classList.toggle('Dim', backgroundColor == 'rgb(21, 32, 43)')
  1462. $body.classList.toggle('LightsOut', backgroundColor == 'rgb(0, 0, 0)')
  1463.  
  1464. if (lastBackgroundColor != null) {
  1465. log('Background setting changed - re-processing current page')
  1466. observePopups()
  1467. observeSideNavTweetButton()
  1468. processCurrentPage()
  1469. }
  1470. lastBackgroundColor = backgroundColor
  1471. }, '<body> style attribute for background colour changes', {
  1472. attributes: true,
  1473. attributeFilter: ['style']
  1474. })
  1475. }
  1476.  
  1477. /**
  1478. * When the "Color" setting is changed in "Customize your view", the app
  1479. * re-renders from a certain point, so we need to re-process the current page.
  1480. */
  1481. async function observeColor() {
  1482. let $colorRerenderBoundary = await getElement('#react-root > div > div')
  1483.  
  1484. observeElement($colorRerenderBoundary, async () => {
  1485. if (location.pathname != PagePaths.CUSTOMIZE_YOUR_VIEW) return
  1486.  
  1487. let $doneButton = await getElement(desktop ? Selectors.DISPLAY_DONE_BUTTON_DESKTOP : Selectors.DISPLAY_DONE_BUTTON_MOBILE, {
  1488. name: 'Done button',
  1489. stopIf: not(() => location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW),
  1490. })
  1491. if (!$doneButton) return
  1492.  
  1493. let color = getComputedStyle($doneButton).backgroundColor
  1494. if (color == themeColor) return
  1495.  
  1496. log('Color setting changed - re-processing current page')
  1497. themeColor = color
  1498. localStorage.lastThemeColor = color
  1499. configureThemeCss()
  1500. observePopups()
  1501. observeSideNavTweetButton()
  1502. processCurrentPage()
  1503. }, 'Color change re-render boundary')
  1504. }
  1505.  
  1506. /**
  1507. * When the "Font size" setting is changed in "Customize your view" on desktop,
  1508. * `<html>`'s fontSize is changed and the app is re-rendered.
  1509. */
  1510. const observeHtmlFontSize = (() => {
  1511. /** @type {MutationObserver} */
  1512. let fontSizeObserver
  1513.  
  1514. return function observeHtmlFontSize() {
  1515. if (fontSizeObserver) {
  1516. fontSizeObserver.disconnect()
  1517. fontSizeObserver = null
  1518. }
  1519.  
  1520. if (mobile) return
  1521.  
  1522. let lastOverflow = ''
  1523.  
  1524. fontSizeObserver = observeElement($html, () => {
  1525. if (!$html.style.fontSize) return
  1526.  
  1527. let hasFontSizeChanged = fontSize != null && $html.style.fontSize != fontSize
  1528.  
  1529. if ($html.style.fontSize != fontSize) {
  1530. fontSize = $html.style.fontSize
  1531. log(`<html> fontSize has changed to ${fontSize}`)
  1532. configureNavFontSizeCss()
  1533. }
  1534.  
  1535. // Ignore overflow changes, which happen when a dialog is shown or hidden
  1536. let hasOverflowChanged = $html.style.overflow != lastOverflow
  1537. lastOverflow = $html.style.overflow
  1538. if (!hasFontSizeChanged && hasOverflowChanged) {
  1539. log('ignoring <html> style overflow change')
  1540. return
  1541. }
  1542.  
  1543. // When you switch between the smallest "Font size" options, <html>'s
  1544. // style is updated but the font size is kept the same - re-process just
  1545. // in case.
  1546. if (hasFontSizeChanged ||
  1547. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW && fontSize == '14px') {
  1548. log('<html> style attribute changed, re-processing current page')
  1549. observePopups()
  1550. observeSideNavTweetButton()
  1551. processCurrentPage()
  1552. }
  1553. }, '<html> style attribute for font size changes', {
  1554. attributes: true,
  1555. attributeFilter: ['style']
  1556. })
  1557. }
  1558. })()
  1559.  
  1560. async function observeDesktopComposeTweetModal($popup) {
  1561. let $modalDialog = await getElement('div[role="dialog"][aria-labelledby]', {
  1562. context: $popup,
  1563. stopIf: () => !isDesktopComposeTweetModalOpen
  1564. })
  1565. if (!$modalDialog) return
  1566.  
  1567. /** @type {import("./types").Disconnectable} */
  1568. let tweetButtonObserver
  1569.  
  1570. function disconnectTweetButtonObserver() {
  1571. if (tweetButtonObserver) {
  1572. log('disconnecting tweet button dialog observer')
  1573. tweetButtonObserver.disconnect()
  1574. modalObservers.splice(modalObservers.indexOf(tweetButtonObserver), 1)
  1575. tweetButtonObserver = null
  1576. }
  1577. }
  1578.  
  1579. let waitingForTweetButton = false
  1580.  
  1581. modalObservers.push(
  1582. observeElement($modalDialog, async () => {
  1583. if (waitingForTweetButton) return
  1584.  
  1585. waitingForTweetButton = true
  1586. let $tweetButtonText = await getElement('div[data-testid="tweetButton"] span > span', {
  1587. context: $modalDialog,
  1588. name: 'tweet button',
  1589. timeout: 500,
  1590. })
  1591. waitingForTweetButton = false
  1592.  
  1593. if (!$tweetButtonText) {
  1594. disconnectTweetButtonObserver()
  1595. return
  1596. }
  1597.  
  1598. setTweetButtonText($tweetButtonText)
  1599.  
  1600. // The button will be moved around when multiple Tweets are being edited
  1601. tweetButtonObserver = observeElement($modalDialog, (mutations) => {
  1602. for (let mutation of mutations) {
  1603. for (let $addedNode of mutation.addedNodes) {
  1604. let $tweetButtonText = $addedNode.querySelector?.('div[data-testid="tweetButton"] span > span')
  1605. if ($tweetButtonText) {
  1606. setTweetButtonText($tweetButtonText)
  1607. }
  1608. }
  1609. }
  1610. }, 'tweet button dialog', {childList: true, subtree: true})
  1611. modalObservers.push(tweetButtonObserver)
  1612. }, 'compose tweet modal dialog')
  1613. )
  1614. }
  1615.  
  1616. async function observeDesktopModalTimeline() {
  1617. // Media modals remember if they were previously collapsed, so we could be
  1618. // waiting for the initial timeline to be either rendered or expanded.
  1619. let $initialTimeline = await getElement(Selectors.MODAL_TIMELINE, {
  1620. name: 'initial modal timeline',
  1621. stopIf: () => !isDesktopMediaModalOpen,
  1622. })
  1623.  
  1624. if ($initialTimeline == null) return
  1625.  
  1626. /**
  1627. * @param {HTMLElement} $timeline
  1628. */
  1629. function observeModalTimelineItems($timeline) {
  1630. disconnectModalObserver('modal timeline')
  1631. modalObservers.push(
  1632. observeElement($timeline, () => onIndividualTweetTimelineChange($timeline), 'modal timeline')
  1633. )
  1634.  
  1635. // If other media in the modal is clicked, the timeline is replaced.
  1636. disconnectModalObserver('modal timeline parent')
  1637. modalObservers.push(
  1638. observeElement($timeline.parentElement, (mutations) => {
  1639. mutations.forEach((mutation) => {
  1640. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1641. log('modal timeline replaced')
  1642. disconnectModalObserver('modal timeline')
  1643. modalObservers.push(
  1644. observeElement($newTimeline, () => onIndividualTweetTimelineChange($newTimeline), 'modal timeline')
  1645. )
  1646. })
  1647. })
  1648. }, 'modal timeline parent')
  1649. )
  1650. }
  1651.  
  1652. /**
  1653. * @param {HTMLElement} $timeline
  1654. */
  1655. function observeModalTimeline($timeline) {
  1656. // If the inital timeline doesn't have a style attribute it's a placeholder
  1657. if ($timeline.hasAttribute('style')) {
  1658. observeModalTimelineItems($timeline)
  1659. }
  1660. else {
  1661. log('waiting for modal timeline')
  1662. let startTime = Date.now()
  1663. modalObservers.push(
  1664. observeElement($timeline.parentElement, (mutations) => {
  1665. mutations.forEach((mutation) => {
  1666. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  1667. disconnectModalObserver('modal timeline parent')
  1668. if (Date.now() > startTime) {
  1669. log(`modal timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  1670. }
  1671. observeModalTimelineItems($timeline)
  1672. })
  1673. })
  1674. }, 'modal timeline parent')
  1675. )
  1676. }
  1677. }
  1678.  
  1679. // The modal timeline can be expanded and collapsed
  1680. let $expandedContainer = $initialTimeline.closest('[aria-expanded="true"]')
  1681. modalObservers.push(
  1682. observeElement($expandedContainer.parentElement, async (mutations) => {
  1683. if (mutations.some(mutation => mutation.removedNodes.length > 0)) {
  1684. log('modal timeline collapsed')
  1685. disconnectModalObserver('modal timeline parent')
  1686. disconnectModalObserver('modal timeline')
  1687. }
  1688. else if (mutations.some(mutation => mutation.addedNodes.length > 0)) {
  1689. log('modal timeline expanded')
  1690. let $timeline = await getElement(Selectors.MODAL_TIMELINE, {
  1691. name: 'expanded modal timeline',
  1692. stopIf: () => !isDesktopMediaModalOpen,
  1693. })
  1694. if ($timeline == null) return
  1695. observeModalTimeline($timeline)
  1696. }
  1697. }, 'collapsible modal timeline container')
  1698. )
  1699.  
  1700. observeModalTimeline($initialTimeline)
  1701. }
  1702.  
  1703. const observeFavicon = (() => {
  1704. /** @type {HTMLElement} */
  1705. let $shortcutIcon
  1706. /** @type {MutationObserver} */
  1707. let shortcutIconObserver
  1708.  
  1709. async function observeFavicon() {
  1710. if ($shortcutIcon == null) {
  1711. $shortcutIcon = await getElement('link[rel="shortcut icon"]', {name: 'shortcut icon'})
  1712. }
  1713.  
  1714. if (!config.replaceLogo) {
  1715. if (shortcutIconObserver != null) {
  1716. shortcutIconObserver.disconnect()
  1717. shortcutIconObserver = null
  1718. if ($shortcutIcon.getAttribute('href').startsWith('data:')) {
  1719. $shortcutIcon.setAttribute('href', `//abs.twimg.com/favicons/twitter${currentNotificationCount ? '-pip' : ''}.3.ico`)
  1720. }
  1721. }
  1722. return
  1723. }
  1724.  
  1725. shortcutIconObserver = observeElement($shortcutIcon, () => {
  1726. let href = $shortcutIcon.getAttribute('href')
  1727. if (href.startsWith('data:')) return
  1728. $shortcutIcon.setAttribute('href', href.includes('pip') ? Images.TWITTER_PIP_FAVICON : Images.TWITTER_FAVICON)
  1729. }, 'shortcut icon href', {
  1730. attributes: true,
  1731. attributeFilter: ['href']
  1732. })
  1733. }
  1734.  
  1735. observeFavicon.updatePip = function(showPip) {
  1736. if (!$shortcutIcon) return
  1737. let icon = showPip ? Images.TWITTER_PIP_FAVICON : Images.TWITTER_FAVICON
  1738. if ($shortcutIcon.getAttribute('href') != icon) {
  1739. $shortcutIcon.setAttribute('href', icon)
  1740. }
  1741. }
  1742.  
  1743. return observeFavicon
  1744. })()
  1745.  
  1746. /**
  1747. * Twitter displays popups in the #layers element. It also reuses open popups
  1748. * in certain cases rather than creating one from scratch, so we also need to
  1749. * deal with nested popups, e.g. if you hover over the caret menu in a Tweet, a
  1750. * popup will be created to display a "More" tootip and clicking to open the
  1751. * menu will create a nested element in the existing popup, whereas clicking the
  1752. * caret quickly without hovering over it will display the menu in new popup.
  1753. * Use of nested popups can also differ between desktop and mobile, so features
  1754. * need to be mindful of that.
  1755. */
  1756. const observePopups = (() => {
  1757. /** @type {MutationObserver} */
  1758. let popupObserver
  1759. /** @type {WeakMap<HTMLElement, {disconnect()}>} */
  1760. let nestedObservers = new WeakMap()
  1761.  
  1762. return async function observePopups() {
  1763. if (popupObserver) {
  1764. popupObserver.disconnect()
  1765. popupObserver = null
  1766. }
  1767.  
  1768. let $layers = await getElement('#layers', {
  1769. name: 'layers',
  1770. })
  1771.  
  1772. // There can be only one
  1773. if (popupObserver) {
  1774. popupObserver.disconnect()
  1775. }
  1776.  
  1777. popupObserver = observeElement($layers, (mutations) => {
  1778. mutations.forEach((mutation) => {
  1779. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1780. let nestedObserver = onPopup($el)
  1781. if (nestedObserver) {
  1782. nestedObservers.set($el, nestedObserver)
  1783. }
  1784. })
  1785. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  1786. if (nestedObservers.has($el)) {
  1787. nestedObservers.get($el).disconnect()
  1788. nestedObservers.delete($el)
  1789. }
  1790. })
  1791. })
  1792. }, 'popup container')
  1793. }
  1794. })()
  1795.  
  1796. async function observeTitle() {
  1797. let $title = await getElement('title', {name: '<title>'})
  1798. observeElement($title, () => {
  1799. let title = $title.textContent
  1800. if (config.replaceLogo && (ltr ? /X$/ : /^(?:\(\d+\+?\) )?X/).test(title)) {
  1801. document.title = title.replace(ltr ? /X$/ : 'X', getString('TWITTER'))
  1802. return
  1803. }
  1804. if (observingPageChanges) {
  1805. onTitleChange(title)
  1806. }
  1807. }, '<title>')
  1808. }
  1809. //#endregion
  1810.  
  1811. //#region Page observers
  1812. /**
  1813. * If a profile is blocked its media box won't appear, add a `Blocked` class to
  1814. * `<body>` to hide sidebar content.
  1815. * @param {string} currentPage
  1816. */
  1817. async function observeProfileBlockedStatus(currentPage) {
  1818. let $buttonContainer = await getElement(`[data-testid="userActions"] ~ [data-testid="placementTracking"], a[href="${PagePaths.PROFILE_SETTINGS}"]`, {
  1819. name: 'Follow / Unblock button container or Edit profile button',
  1820. stopIf: pageIsNot(currentPage),
  1821. })
  1822. if ($buttonContainer == null) return
  1823.  
  1824. if ($buttonContainer.hasAttribute('href')) {
  1825. log('on own profile page')
  1826. $body.classList.remove('Blocked')
  1827. return
  1828. }
  1829.  
  1830. pageObservers.push(
  1831. observeElement($buttonContainer, () => {
  1832. let isBlocked = (/** @type {HTMLElement} */ ($buttonContainer.querySelector('[role="button"]'))?.dataset.testid ?? '').endsWith('unblock')
  1833. $body.classList.toggle('Blocked', isBlocked)
  1834. }, 'Follow / Unblock button container')
  1835. )
  1836. }
  1837.  
  1838. /**
  1839. * If an account has never tweeted any media, add a `NoMedia` class to `<body>`
  1840. * to hide the "You might like" section which will appear where the media box
  1841. * would have been.
  1842. * @param {string} currentPage
  1843. */
  1844. async function observeProfileSidebar(currentPage) {
  1845. let $sidebarContent = await getElement(Selectors.SIDEBAR_WRAPPERS, {
  1846. name: 'profile sidebar content container',
  1847. stopIf: pageIsNot(currentPage),
  1848. })
  1849. if ($sidebarContent == null) return
  1850.  
  1851. let sidebarContentObserver = observeElement($sidebarContent, () => {
  1852. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1853. }, 'profile sidebar content container')
  1854. pageObservers.push(sidebarContentObserver)
  1855.  
  1856. // On initial appearance, the sidebar is injected with static HTML with
  1857. // spinner placeholders, which gets replaced. When this happens we need to
  1858. // observe the new content container instead.
  1859. let $sidebarContentParent = $sidebarContent.parentElement
  1860. pageObservers.push(
  1861. observeElement($sidebarContentParent, (mutations) => {
  1862. let sidebarContentReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($sidebarContent))
  1863. if (sidebarContentReplaced) {
  1864. log('profile sidebar content container replaced, observing new container')
  1865. sidebarContentObserver.disconnect()
  1866. pageObservers.splice(pageObservers.indexOf(sidebarContentObserver), 1)
  1867. $sidebarContent = /** @type {HTMLElement} */ ($sidebarContentParent.firstElementChild)
  1868. pageObservers.push(
  1869. observeElement($sidebarContent, () => {
  1870. $body.classList.toggle('NoMedia', $sidebarContent.childElementCount == 5)
  1871. }, 'sidebar content container')
  1872. )
  1873. }
  1874. }, 'sidebar content container parent')
  1875. )
  1876. }
  1877.  
  1878. async function observeSidebar() {
  1879. let $primaryColumn = await getElement(Selectors.PRIMARY_COLUMN, {
  1880. name: 'primary column'
  1881. })
  1882. let $sidebarContainer = $primaryColumn.parentElement
  1883. pageObservers.push(
  1884. observeElement($sidebarContainer, () => {
  1885. let $sidebar = $sidebarContainer.querySelector(Selectors.SIDEBAR)
  1886. log(`sidebar ${$sidebar ? 'appeared' : 'disappeared'}`)
  1887. $body.classList.toggle('Sidebar', Boolean($sidebar))
  1888. if ($sidebar && config.twitterBlueChecks != 'ignore' && !isOnSearchPage() && !isOnExplorePage()) {
  1889. observeSearchForm()
  1890. }
  1891. }, 'sidebar container')
  1892. )
  1893. }
  1894.  
  1895. const observeSideNavTweetButton = (() => {
  1896. /** @type {MutationObserver} */
  1897. let observer
  1898.  
  1899. return async function observeSideNavTweetButton() {
  1900. if (observer) {
  1901. observer.disconnect()
  1902. observer = null
  1903. }
  1904.  
  1905. if (!desktop || !config.replaceLogo) return
  1906.  
  1907. // This element is updated when text is added or removed on resize
  1908. let $buttonTextContainer = await getElement('a[data-testid="SideNav_NewTweet_Button"] > div > span')
  1909. observer = observeElement($buttonTextContainer, () => {
  1910. if ($buttonTextContainer.childElementCount > 0) {
  1911. let $buttonText = /** @type {HTMLElement} */ ($buttonTextContainer.querySelector('span > span'))
  1912. if ($buttonText) {
  1913. setTweetButtonText($buttonText)
  1914. } else {
  1915. warn('could not find tweet button text')
  1916. }
  1917. }
  1918. }, 'sidenav tweet button')
  1919. }
  1920. })()
  1921.  
  1922. async function observeSearchForm() {
  1923. let $searchForm = await getElement('form[role="search"]', {
  1924. name: 'search form',
  1925. stopIf: pageIsNot(currentPage),
  1926. // The sidebar on Profile pages can be really slow
  1927. timeout: 2000,
  1928. })
  1929. if (!$searchForm) return
  1930. let $results = /** @type {HTMLElement} */ ($searchForm.lastElementChild)
  1931. pageObservers.push(
  1932. observeElement($results, () => {
  1933. processBlueChecks($results)
  1934. }, 'search results', {childList: true, subtree: true})
  1935. )
  1936. }
  1937.  
  1938. /**
  1939. * @param {string} page
  1940. * @param {import("./types").TimelineOptions?} options
  1941. */
  1942. async function observeTimeline(page, options = {}) {
  1943. let {
  1944. isTabbed = false,
  1945. onTabChanged = null,
  1946. onTimelineAppeared = null,
  1947. onTimelineItemsChanged = onTimelineChange,
  1948. tabbedTimelineContainerSelector = null,
  1949. timelineSelector = Selectors.TIMELINE,
  1950. } = options
  1951.  
  1952. let $timeline = await getElement(timelineSelector, {
  1953. name: 'initial timeline',
  1954. stopIf: pageIsNot(page),
  1955. })
  1956.  
  1957. if ($timeline == null) return
  1958.  
  1959. /**
  1960. * @param {HTMLElement} $timeline
  1961. */
  1962. function observeTimelineItems($timeline) {
  1963. disconnectPageObserver('timeline')
  1964. pageObservers.push(
  1965. observeElement($timeline, () => onTimelineItemsChanged($timeline, page, options), 'timeline')
  1966. )
  1967. onTimelineAppeared?.()
  1968. if (isTabbed) {
  1969. // When a tab which has been viewed before is revisited, the timeline is
  1970. // replaced.
  1971. disconnectPageObserver('timeline parent')
  1972. pageObservers.push(
  1973. observeElement($timeline.parentElement, (mutations) => {
  1974. mutations.forEach((mutation) => {
  1975. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $newTimeline) => {
  1976. disconnectPageObserver('timeline')
  1977. log('tab changed')
  1978. onTabChanged?.()
  1979. pageObservers.push(
  1980. observeElement($newTimeline, () => onTimelineItemsChanged($newTimeline, page, options), 'timeline')
  1981. )
  1982. })
  1983. })
  1984. }, 'timeline parent')
  1985. )
  1986. }
  1987. }
  1988.  
  1989. // If the inital timeline doesn't have a style attribute it's a placeholder
  1990. if ($timeline.hasAttribute('style')) {
  1991. observeTimelineItems($timeline)
  1992. }
  1993. else {
  1994. log('waiting for timeline')
  1995. let startTime = Date.now()
  1996. pageObservers.push(
  1997. observeElement($timeline.parentElement, (mutations) => {
  1998. mutations.forEach((mutation) => {
  1999. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $timeline) => {
  2000. disconnectPageObserver('timeline parent')
  2001. if (Date.now() > startTime) {
  2002. log(`timeline appeared after ${Date.now() - startTime}ms`, $timeline)
  2003. }
  2004. observeTimelineItems($timeline)
  2005. })
  2006. })
  2007. }, 'timeline parent')
  2008. )
  2009. }
  2010.  
  2011. // On some tabbed timeline pages, the first time a new tab is navigated to,
  2012. // the element containing the timeline is replaced with a loading spinner.
  2013. if (isTabbed && tabbedTimelineContainerSelector) {
  2014. let $tabbedTimelineContainer = document.querySelector(tabbedTimelineContainerSelector)
  2015. if ($tabbedTimelineContainer) {
  2016. let waitingForNewTimeline = false
  2017. pageObservers.push(
  2018. observeElement($tabbedTimelineContainer, async (mutations) => {
  2019. // This is going to fire twice on a new tab, as the spinner is added
  2020. // then replaced with the new timeline element.
  2021. if (!mutations.some(mutation => mutation.addedNodes.length > 0) || waitingForNewTimeline) return
  2022.  
  2023. waitingForNewTimeline = true
  2024. let $newTimeline = await getElement(timelineSelector, {
  2025. name: 'new timeline',
  2026. stopIf: pageIsNot(page),
  2027. })
  2028. waitingForNewTimeline = false
  2029. if (!$newTimeline) return
  2030.  
  2031. log('tab changed')
  2032. onTabChanged?.()
  2033. observeTimelineItems($newTimeline)
  2034. }, 'tabbed timeline container')
  2035. )
  2036. } else {
  2037. warn('tabbed timeline container not found')
  2038. }
  2039. }
  2040. }
  2041.  
  2042. /**
  2043. * @param {HTMLElement} $context
  2044. * @param {string} initialPath
  2045. */
  2046. async function observeUserListTimeline($context, initialPath) {
  2047. let $timeline = await getElement('h1[id^="accessible-list"] + div > div > div > div', {
  2048. context: $context,
  2049. name: 'user list timeline',
  2050. stopIf: not(() => initialPath == location.pathname),
  2051. })
  2052. if (!$timeline) return
  2053.  
  2054. modalObservers.push(
  2055. observeElement($timeline, () => {
  2056. processBlueChecks($timeline)
  2057. }, 'user list timeline')
  2058. )
  2059. }
  2060. //#endregion
  2061.  
  2062. //#region Tweak functions
  2063. /**
  2064. * Add an "Add muted word" menu item after the given link which takes you
  2065. * straight to entering a new muted word (by clicking its way through all the
  2066. * individual screens!).
  2067. * @param {HTMLElement} $link
  2068. * @param {string} linkSelector
  2069. */
  2070. async function addAddMutedWordMenuItem($link, linkSelector) {
  2071. log('adding "Add muted word" menu item')
  2072.  
  2073. // Wait for the dropdown to appear on desktop
  2074. if (desktop) {
  2075. $link = await getElement(`#layers div[data-testid="Dropdown"] ${linkSelector}`, {
  2076. name: 'rendered menu item',
  2077. timeout: 100,
  2078. })
  2079. if (!$link) return
  2080. }
  2081.  
  2082. let $addMutedWord = /** @type {HTMLElement} */ ($link.parentElement.cloneNode(true))
  2083. $addMutedWord.classList.add('tnt_menu_item')
  2084. $addMutedWord.querySelector('a').href = PagePaths.ADD_MUTED_WORD
  2085. $addMutedWord.querySelector('span').textContent = getString('ADD_MUTED_WORD')
  2086. $addMutedWord.querySelector('svg').innerHTML = Svgs.MUTE
  2087. $addMutedWord.addEventListener('click', (e) => {
  2088. e.preventDefault()
  2089. addMutedWord()
  2090. })
  2091. $link.parentElement.insertAdjacentElement('afterend', $addMutedWord)
  2092. }
  2093.  
  2094. function addCaretMenuListenerForQuoteTweet($tweet) {
  2095. let $caret = /** @type {HTMLElement} */ ($tweet.querySelector('[data-testid="caret"]'))
  2096. if ($caret && !$caret.dataset.tweakNewTwitterListener) {
  2097. $caret.addEventListener('click', () => {
  2098. quotedTweet = getQuotedTweetDetails($tweet, {getText: true})
  2099. })
  2100. $caret.dataset.tweakNewTwitterListener = 'true'
  2101. }
  2102. }
  2103.  
  2104. /**
  2105. * Add a "Mute this conversation" menu item to a Quote Tweet's menu.
  2106. * @param {HTMLElement} $blockMenuItem
  2107. */
  2108. async function addMuteQuotesMenuItem($blockMenuItem) {
  2109. log('adding "Mute this conversation" menu item')
  2110.  
  2111. // Wait for the menu to render properly on desktop
  2112. if (desktop) {
  2113. $blockMenuItem = await getElement(`:scope > div > div > div > ${Selectors.BLOCK_MENU_ITEM}`, {
  2114. context: $blockMenuItem.parentElement,
  2115. name: 'rendered block menu item',
  2116. timeout: 100,
  2117. })
  2118. if (!$blockMenuItem) return
  2119. }
  2120.  
  2121. let $muteQuotes = /** @type {HTMLElement} */ ($blockMenuItem.previousElementSibling.cloneNode(true))
  2122. $muteQuotes.classList.add('tnt_menu_item')
  2123. $muteQuotes.querySelector('span').textContent = getString('MUTE_THIS_CONVERSATION')
  2124. $muteQuotes.addEventListener('click', (e) => {
  2125. e.preventDefault()
  2126. log('muting quotes of a tweet', quotedTweet)
  2127. config.mutedQuotes = config.mutedQuotes.concat(quotedTweet)
  2128. storeConfigChanges({mutedQuotes: config.mutedQuotes})
  2129. processCurrentPage()
  2130. // Dismiss the menu
  2131. let $menuLayer = /** @type {HTMLElement} */ ($blockMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  2132. if (!$menuLayer) {
  2133. log('could not find menu layer to dismiss menu')
  2134. }
  2135. $menuLayer?.click()
  2136. })
  2137.  
  2138. $blockMenuItem.insertAdjacentElement('beforebegin', $muteQuotes)
  2139. }
  2140.  
  2141. async function addMutedWord() {
  2142. if (!document.querySelector('a[href="/settings')) {
  2143. let $settingsAndSupport = /** @type {HTMLElement} */ (document.querySelector('[data-testid="settingsAndSupport"]'))
  2144. $settingsAndSupport?.click()
  2145. }
  2146.  
  2147. for (let path of [
  2148. '/settings',
  2149. '/settings/privacy_and_safety',
  2150. '/settings/mute_and_block',
  2151. '/settings/muted_keywords',
  2152. '/settings/add_muted_keyword',
  2153. ]) {
  2154. let $link = await getElement(`a[href="${path}"]`, {timeout: 500})
  2155. if (!$link) return
  2156. $link.click()
  2157. }
  2158. let $input = await getElement('input[name="keyword"]')
  2159. setTimeout(() => $input.focus(), 100)
  2160. }
  2161.  
  2162. /**
  2163. * Add a "Turn on/off Retweets" menu item to a List's menu.
  2164. * @param {HTMLElement} $switchMenuItem
  2165. */
  2166. async function addToggleListRetweetsMenuItem($switchMenuItem) {
  2167. log('adding "Turn on/off Retweets" menu item')
  2168.  
  2169. // Wait for the menu to render properly on desktop
  2170. if (desktop) {
  2171. $switchMenuItem = await getElement(':scope > div > div > div > [role="menuitem"]', {
  2172. context: $switchMenuItem.parentElement,
  2173. name: 'rendered switch menu item',
  2174. timeout: 100,
  2175. })
  2176. if (!$switchMenuItem) return
  2177. }
  2178.  
  2179. let $toggleRetweets = /** @type {HTMLElement} */ ($switchMenuItem.cloneNode(true))
  2180. $toggleRetweets.classList.add('tnt_menu_item')
  2181. $toggleRetweets.querySelector('span').textContent = getString(`TURN_${config.listRetweets == 'ignore' ? 'OFF' : 'ON'}_RETWEETS`)
  2182. $toggleRetweets.querySelector('svg').innerHTML = config.listRetweets == 'ignore' ? Svgs.RETWEETS_OFF : Svgs.RETWEET
  2183. // Remove subtitle if the cloned menu item has one
  2184. $toggleRetweets.querySelector('div[dir] + div[dir]')?.remove()
  2185. $toggleRetweets.addEventListener('click', (e) => {
  2186. e.preventDefault()
  2187. log('toggling list retweets')
  2188. config.listRetweets = config.listRetweets == 'ignore' ? 'hide' : 'ignore'
  2189. storeConfigChanges({listRetweets: config.listRetweets})
  2190. processCurrentPage()
  2191. // Dismiss the menu
  2192. let $menuLayer = /** @type {HTMLElement} */ ($switchMenuItem.closest('[role="group"]')?.firstElementChild?.firstElementChild)
  2193. if (!$menuLayer) {
  2194. log('could not find menu layer to dismiss menu')
  2195. }
  2196. $menuLayer?.click()
  2197. })
  2198.  
  2199. $switchMenuItem.insertAdjacentElement('beforebegin', $toggleRetweets)
  2200. }
  2201.  
  2202. /**
  2203. * Redirects away from the home timeline if we're on it and it's been disabled.
  2204. * @returns {boolean} `true` if redirected as a result of this call
  2205. */
  2206. function checkforDisabledHomeTimeline() {
  2207. if (config.disableHomeTimeline && location.pathname == '/home') {
  2208. log(`home timeline disabled, redirecting to /${config.disabledHomeTimelineRedirect}`)
  2209. let primaryNavSelector = desktop ? Selectors.PRIMARY_NAV_DESKTOP : Selectors.PRIMARY_NAV_MOBILE
  2210. ;/** @type {HTMLElement} */ (
  2211. document.querySelector(`${primaryNavSelector} a[href="/${config.disabledHomeTimelineRedirect}"]`)
  2212. ).click()
  2213. return true
  2214. }
  2215. }
  2216.  
  2217. const configureCss = (() => {
  2218. let $style
  2219.  
  2220. return function configureCss() {
  2221. if ($style == null) {
  2222. $style = addStyle('features')
  2223. }
  2224. let cssRules = []
  2225. let hideCssSelectors = []
  2226. let menuRole = `[role="${desktop ? 'menu' : 'dialog'}"]`
  2227.  
  2228. // Hover colours for custom menu items
  2229. cssRules.push(`
  2230. body.Default .tnt_menu_item:hover { background-color: rgb(247, 249, 249) !important; }
  2231. body.Dim .tnt_menu_item:hover { background-color: rgb(30, 39, 50) !important; }
  2232. body.LightsOut .tnt_menu_item:hover { background-color: rgb(22, 24, 28) !important; }
  2233. `)
  2234.  
  2235. if (config.alwaysUseLatestTweets && config.hideForYouTimeline) {
  2236. cssRules.push(`
  2237. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child {
  2238. flex: 0;
  2239. }
  2240. body.TabbedTimeline ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:first-child > a {
  2241. display: none;
  2242. }
  2243. `)
  2244. }
  2245. if (config.disableTweetTextFormatting) {
  2246. cssRules.push(`
  2247. div[data-testid="tweetText"] span {
  2248. font-style: normal;
  2249. font-weight: normal;
  2250. }
  2251. `)
  2252. }
  2253. if (config.dropdownMenuFontWeight) {
  2254. cssRules.push(`
  2255. [data-testid="${desktop ? 'Dropdown' : 'sheetDialog'}"] [role="menuitem"] [dir] {
  2256. font-weight: normal;
  2257. }
  2258. `)
  2259. }
  2260. if (config.hideAnalyticsNav) {
  2261. hideCssSelectors.push(`${menuRole} a[href*="analytics.twitter.com"]`)
  2262. }
  2263. if (config.hideBookmarkButton) {
  2264. hideCssSelectors.push(
  2265. // Under individual tweets
  2266. '[data-testid="tweet"][tabindex="-1"] [role="group"][id^="id__"] > div:nth-child(4)',
  2267. )
  2268. }
  2269. if (config.hideBookmarksNav) {
  2270. hideCssSelectors.push(`${menuRole} a[href$="/bookmarks"]`)
  2271. }
  2272. if (config.hideCommunitiesNav) {
  2273. hideCssSelectors.push(`${menuRole} a[href$="/communities"]`)
  2274. }
  2275. if (config.hideShareTweetButton) {
  2276. hideCssSelectors.push(
  2277. // Under timeline tweets
  2278. `[data-testid="tweet"][tabindex="0"] [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2279. // Under individual tweets
  2280. `[data-testid="tweet"][tabindex="-1"] [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2281. )
  2282. }
  2283. if (config.hideSubscriptions) {
  2284. hideCssSelectors.push(
  2285. // Subscribe buttons in profile (multiple locations)
  2286. 'body.Profile [role="button"][style*="border-color: rgb(201, 54, 204)"]',
  2287. // Subscriptions count in profile
  2288. 'body.Profile a[href$="/creator-subscriptions/subscriptions"]',
  2289. // Subs tab in profile (3rd of 5, or 6 if they have Highlights)
  2290. 'body.Profile [data-testid="ScrollSnap-List"] > [role="presentation"]:nth-child(3):is(:nth-last-child(3), :nth-last-child(4))',
  2291. // Subscribe button in focused tweet
  2292. '[data-testid="tweet"][tabindex="-1"] [data-testid$="-subscribe"]',
  2293. // "Subscribe to" dropdown item (desktop)
  2294. '[data-testid="Dropdown"] > [data-testid="subscribe"]',
  2295. // "Subscribe to" menu item (mobile)
  2296. '[data-testid="sheetDialog"] > [data-testid="subscribe"]',
  2297. // "Subscriber" indicator in replies from subscribers
  2298. 'body.Default [data-testid="tweet"] [data-testid="userFollowIndicator"][style*="color: rgb(141, 32, 144)"]',
  2299. 'body:is(.Dim, .LightsOut) [data-testid="tweet"] [data-testid="userFollowIndicator"][style*="color: rgb(223, 130, 224)"]',
  2300. // Monetization and Subscriptions items in Settings
  2301. 'body.Settings a[href="/settings/monetization"]',
  2302. 'body.Settings a[href="/settings/manage_subscriptions"]',
  2303. )
  2304. }
  2305. if (config.hideHelpCenterNav) {
  2306. hideCssSelectors.push(`${menuRole} a[href*="support.twitter.com"]`)
  2307. }
  2308. if (config.hideMetrics) {
  2309. configureHideMetricsCss(cssRules, hideCssSelectors)
  2310. }
  2311. if (config.hideMonetizationNav) {
  2312. hideCssSelectors.push(`${menuRole} a[href$="/settings/monetization"]`)
  2313. }
  2314. if (config.hideTweetAnalyticsLinks) {
  2315. hideCssSelectors.push('[data-testid="analyticsButton"]')
  2316. }
  2317. if (config.hideTwitterAdsNav) {
  2318. hideCssSelectors.push(`${menuRole} a[href*="ads.twitter.com"]`)
  2319. }
  2320. if (config.hideTwitterBlueUpsells) {
  2321. hideCssSelectors.push(
  2322. // Twitter Blue menu item
  2323. `${menuRole} a[href$="/i/blue_sign_up"]`,
  2324. // "Highlight on your profile" on your tweets
  2325. '[role="menuitem"][data-testid="highlightUpsell"]',
  2326. // "Edit with Twitter Blue" on recent tweets
  2327. '[role="menuitem"][data-testid="editWithTwitterBlue"]',
  2328. // Twitter Blue item in Settings
  2329. 'body.Settings a[href="/i/blue_sign_up"]',
  2330. // "Highlight your best content instead" on the pin modal
  2331. '.PinModal [data-testid="sheetDialog"] > div > div:last-child > div > div > div:first-child',
  2332. // Highlight button on the pin modal
  2333. '.PinModal [data-testid="sheetDialog"] [role="button"]:first-child:nth-last-child(3)',
  2334. )
  2335. // Allow Pin and Cancel buttons go to max-width on the pin modal
  2336. cssRules.push(`
  2337. .PinModal [data-testid="sheetDialog"] > div > div:last-child > div > div {
  2338. width: 100%;
  2339. margin-top: 0;
  2340. padding-left: 32px;
  2341. padding-right: 32px;
  2342. }
  2343. `)
  2344. }
  2345. if (config.hideVerifiedNotificationsTab) {
  2346. hideCssSelectors.push(
  2347. `body.Notifications ${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav div[role="tablist"] > div:nth-child(2)`
  2348. )
  2349. }
  2350. if (config.hideViews) {
  2351. hideCssSelectors.push(
  2352. // "Views" under individual tweets
  2353. '[data-testid="tweet"][tabindex="-1"] div[dir] + div[aria-hidden="true"]:nth-child(2):nth-last-child(2)',
  2354. '[data-testid="tweet"][tabindex="-1"] div[dir] + div[aria-hidden="true"]:nth-child(2):nth-last-child(2) + div[dir]:last-child'
  2355. )
  2356. }
  2357. if (config.hideWhoToFollowEtc) {
  2358. hideCssSelectors.push(`body.Profile ${Selectors.PRIMARY_COLUMN} aside[role="complementary"]`)
  2359. }
  2360. if (config.reducedInteractionMode) {
  2361. hideCssSelectors.push(
  2362. '[data-testid="tweet"] [role="group"]',
  2363. 'body.Tweet a:is([href$="/retweets"], [href$="/likes"])',
  2364. 'body.Tweet [data-testid="tweet"] + div > div [role="group"]',
  2365. )
  2366. }
  2367. if (config.tweakQuoteTweetsPage) {
  2368. // Hide the quoted tweet, which is repeated in every quote tweet
  2369. hideCssSelectors.push('body.QuoteTweets [data-testid="tweet"] [aria-labelledby] > div:last-child')
  2370. }
  2371. if (config.twitterBlueChecks == 'hide') {
  2372. hideCssSelectors.push('.tnt_blue_check')
  2373. }
  2374. if (config.twitterBlueChecks == 'replace') {
  2375. cssRules.push(`
  2376. :is(${Selectors.VERIFIED_TICK}, svg[data-testid="verificationBadge"]).tnt_blue_check path {
  2377. d: path("${Svgs.BLUE_LOGO_PATH}");
  2378. }
  2379. `)
  2380. }
  2381.  
  2382. // Hide "Creator Studio" if all its contents are hidden
  2383. if (config.hideAnalyticsNav) {
  2384. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(1)`)
  2385. }
  2386. // Hide "Professional Tools" if all its contents are hidden
  2387. if (config.hideTwitterAdsNav) {
  2388. hideCssSelectors.push(`${menuRole} div[role="button"][aria-expanded]:nth-of-type(2)`)
  2389. }
  2390.  
  2391. if (shouldShowSeparatedTweetsTab()) {
  2392. cssRules.push(`
  2393. body.Default {
  2394. --active-tab-text: rgb(15, 20, 25);
  2395. --inactive-tab-text: rgb(83, 100, 113);
  2396. --tab-border: rgb(239, 243, 244);
  2397. --tab-hover: rgba(15, 20, 25, 0.1);
  2398. }
  2399. body.Dim {
  2400. --active-tab-text: rgb(247, 249, 249);
  2401. --inactive-tab-text: rgb(139, 152, 165);
  2402. --tab-border: rgb(56, 68, 77);
  2403. --tab-hover: rgba(247, 249, 249, 0.1);
  2404. }
  2405. body.LightsOut {
  2406. --active-tab-text: rgb(247, 249, 249);
  2407. --inactive-tab-text: rgb(113, 118, 123);
  2408. --tab-border: rgb(47, 51, 54);
  2409. --tab-hover: rgba(231, 233, 234, 0.1);
  2410. }
  2411.  
  2412. /* Tabbed timeline */
  2413. body.Desktop #tnt_separated_tweets_tab:hover,
  2414. body.Mobile:not(.SeparatedTweets) #tnt_separated_tweets_tab:hover,
  2415. body.Mobile #tnt_separated_tweets_tab:active {
  2416. background-color: var(--tab-hover);
  2417. }
  2418. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div,
  2419. 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 {
  2420. font-weight: normal !important;
  2421. color: var(--inactive-tab-text) !important;
  2422. }
  2423. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div {
  2424. font-weight: bold;
  2425. color: var(--active-tab-text); !important;
  2426. }
  2427. body:not(.SeparatedTweets) #tnt_separated_tweets_tab > a > div > div > div,
  2428. 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 {
  2429. height: 0 !important;
  2430. }
  2431. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2432. height: 4px !important;
  2433. min-width: 56px;
  2434. width: 100%;
  2435. position: absolute;
  2436. bottom: 0;
  2437. border-radius: 9999px;
  2438. }
  2439. `)
  2440. }
  2441.  
  2442. if (desktop) {
  2443. if (config.navDensity == 'comfortable' || config.navDensity == 'compact') {
  2444. cssRules.push(`
  2445. header nav > a,
  2446. header nav > div[data-testid="AppTabBar_More_Menu"] {
  2447. padding-top: 0 !important;
  2448. padding-bottom: 0 !important;
  2449. }
  2450. `)
  2451. }
  2452. if (config.navDensity == 'compact') {
  2453. cssRules.push(`
  2454. header nav > a > div,
  2455. header nav > div[data-testid="AppTabBar_More_Menu"] > div {
  2456. padding-top: 6px !important;
  2457. padding-bottom: 6px !important;
  2458. }
  2459. `)
  2460. }
  2461. if (config.hideHomeHeading) {
  2462. hideCssSelectors.push(`body.TabbedTimeline ${Selectors.DESKTOP_TIMELINE_HEADER} > div:first-child > div:first-child`)
  2463. }
  2464. if (config.hideSeeNewTweets) {
  2465. hideCssSelectors.push(`body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div > div:first-child > div[style^="transform"]`)
  2466. }
  2467. if (config.disableHomeTimeline) {
  2468. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/home"]`)
  2469. }
  2470. if (config.fullWidthContent) {
  2471. cssRules.push(`
  2472. /* Use full width when the sidebar is visible */
  2473. body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN},
  2474. body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2475. max-width: 990px;
  2476. }
  2477. /* Make the "What's happening" input keep its original width */
  2478. body.MainTimeline ${Selectors.PRIMARY_COLUMN} > div:first-child > div:nth-of-type(3) div[role="progressbar"] + div {
  2479. max-width: 598px;
  2480. }
  2481. /* Use full width when the sidebar is not visible */
  2482. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} header[role="banner"] {
  2483. flex-grow: 0;
  2484. }
  2485. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} main[role="main"] > div {
  2486. width: 100%;
  2487. }
  2488. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} {
  2489. max-width: unset;
  2490. width: 100%;
  2491. }
  2492. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:first-child div,
  2493. body:not(.Sidebar)${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} > div:first-child > div:last-child {
  2494. max-width: unset;
  2495. }
  2496. `)
  2497. if (!config.fullWidthMedia) {
  2498. // Make media & cards keep their original width
  2499. cssRules.push(`
  2500. body${FULL_WIDTH_BODY_PSEUDO} ${Selectors.PRIMARY_COLUMN} ${Selectors.TWEET} > div > div > div:nth-of-type(2) > div:nth-of-type(2) > div[id][aria-labelledby]:not(:empty) {
  2501. max-width: 504px;
  2502. }
  2503. `)
  2504. }
  2505. // Hide the sidebar when present
  2506. hideCssSelectors.push(`body.Sidebar${FULL_WIDTH_BODY_PSEUDO} ${Selectors.SIDEBAR}`)
  2507. }
  2508. if (config.hideAccountSwitcher) {
  2509. cssRules.push(`
  2510. header[role="banner"] > div > div > div > div:last-child {
  2511. flex-shrink: 1 !important;
  2512. align-items: flex-end !important;
  2513. }
  2514. `)
  2515. hideCssSelectors.push(
  2516. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child:not(:only-child)',
  2517. '[data-testid="SideNav_AccountSwitcher_Button"] > div:first-child + div',
  2518. )
  2519. }
  2520. if (config.hideExplorePageContents) {
  2521. hideCssSelectors.push(
  2522. // Tabs
  2523. `body.Explore ${Selectors.DESKTOP_TIMELINE_HEADER} nav`,
  2524. // Content
  2525. `body.Explore ${Selectors.TIMELINE}`,
  2526. )
  2527. }
  2528. if (config.hideConnectNav) {
  2529. hideCssSelectors.push(`${menuRole} a[href$="/i/connect_people"]`)
  2530. }
  2531. if (config.hideKeyboardShortcutsNav) {
  2532. hideCssSelectors.push(`${menuRole} a[href$="/i/keyboard_shortcuts"]`)
  2533. }
  2534. if (config.hideListsNav) {
  2535. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/lists"]`)
  2536. }
  2537. if (config.hideTwitterBlueUpsells) {
  2538. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/i/verified-choose"]`)
  2539. }
  2540. if (config.hideSidebarContent) {
  2541. // Only show the first sidebar item by default
  2542. // Re-show subsequent non-algorithmic sections on specific pages
  2543. cssRules.push(`
  2544. ${Selectors.SIDEBAR_WRAPPERS} > div:not(:first-of-type) {
  2545. display: none;
  2546. }
  2547. body.Profile:not(.Blocked, .NoMedia) ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2548. display: block;
  2549. }
  2550. body.Search ${Selectors.SIDEBAR_WRAPPERS} > div:nth-of-type(2) {
  2551. display: block;
  2552. }
  2553. `)
  2554. if (config.showRelevantPeople) {
  2555. cssRules.push(`
  2556. body.Tweet ${Selectors.SIDEBAR_WRAPPERS} > div:is(:nth-of-type(2), :nth-of-type(3)) {
  2557. display: block;
  2558. }
  2559. `)
  2560. }
  2561. hideCssSelectors.push(`body.HideSidebar ${Selectors.SIDEBAR}`)
  2562. } else if (config.hideTwitterBlueUpsells) {
  2563. hideCssSelectors.push(
  2564. `body.MainTimeline ${Selectors.SIDEBAR_WRAPPERS} > div:nth-of-type(3)`
  2565. )
  2566. }
  2567. if (config.hideShareTweetButton) {
  2568. hideCssSelectors.push(
  2569. // In media modal
  2570. `[aria-modal="true"] [role="group"] > div[style]:not([role]):not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2571. )
  2572. }
  2573. if (config.hideExploreNav) {
  2574. // When configured, hide Explore only when the sidebar is showing, or
  2575. // when on a page full-width content is enabled on.
  2576. let bodySelector = `${config.hideExploreNavWithSidebar ? `body.Sidebar${config.fullWidthContent ? `:not(${FULL_WIDTH_BODY_PSEUDO})` : ''} ` : ''}`
  2577. hideCssSelectors.push(`${bodySelector}${Selectors.PRIMARY_NAV_DESKTOP} a[href="/explore"]`)
  2578. }
  2579. if (config.hideBookmarksNav) {
  2580. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href="/i/bookmarks"]`)
  2581. }
  2582. if (config.hideCommunitiesNav) {
  2583. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_DESKTOP} a[href$="/communities"]`)
  2584. }
  2585. if (config.hideMessagesDrawer) {
  2586. cssRules.push(`${Selectors.MESSAGES_DRAWER} { visibility: hidden; }`)
  2587. }
  2588. if (config.hideViews) {
  2589. hideCssSelectors.push(
  2590. // Under timeline tweets
  2591. // The Buffer extension adds a new button in position 2 - use their added class to avoid
  2592. // hiding the wrong button (#209)
  2593. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-of-type(4)',
  2594. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-of-type(5)',
  2595. )
  2596. }
  2597. if (config.retweets != 'separate' && config.quoteTweets != 'separate') {
  2598. hideCssSelectors.push('#tnt_separated_tweets_tab')
  2599. }
  2600. }
  2601.  
  2602. if (mobile) {
  2603. if (config.disableHomeTimeline) {
  2604. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/home"]`)
  2605. }
  2606. if (config.hideSeeNewTweets) {
  2607. hideCssSelectors.push(`body.MainTimeline ${Selectors.MOBILE_TIMELINE_HEADER_NEW} ~ div[style^="transform"]:last-child`)
  2608. }
  2609. if (config.hideAppNags) {
  2610. cssRules.push(`
  2611. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_OLD} div:nth-of-type(3) > div > [role="button"],
  2612. body.Tweet ${Selectors.MOBILE_TIMELINE_HEADER_NEW} div:nth-of-type(3) > div > [role="button"] {
  2613. visibility: hidden;
  2614. }
  2615. `)
  2616. }
  2617. if (config.hideExplorePageContents) {
  2618. // Hide explore page contents so we don't get a brief flash of them
  2619. // before automatically switching the page to search mode.
  2620. hideCssSelectors.push(
  2621. // Tabs
  2622. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_OLD} > div:nth-of-type(2)`,
  2623. `body.Explore ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:nth-of-type(2)`,
  2624. // Content
  2625. `body.Explore ${Selectors.TIMELINE}`,
  2626. )
  2627. }
  2628. if (config.hideListsNav) {
  2629. hideCssSelectors.push(`${menuRole} a[href$="/lists"]`)
  2630. }
  2631. if (config.hideMessagesBottomNavItem) {
  2632. hideCssSelectors.push(`${Selectors.PRIMARY_NAV_MOBILE} a[href="/messages"]`)
  2633. }
  2634. if (config.hideShareTweetButton) {
  2635. hideCssSelectors.push(
  2636. // In media modal
  2637. `body.MobileMedia [role="group"] > div[style]:not(${TWITTER_MEDIA_ASSIST_BUTTON_SELECTOR})`,
  2638. )
  2639. }
  2640. if (config.hideViews) {
  2641. hideCssSelectors.push(
  2642. // Under timeline tweets
  2643. // Views only display on mobile at larger widths - only hide the 4th button if there are 5
  2644. '[data-testid="tweet"][tabindex="0"] [role="group"]:not(.buffer-inserted) > div:nth-child(4):nth-last-child(2)',
  2645. '[data-testid="tweet"][tabindex="0"] [role="group"].buffer-inserted > div:nth-child(4):nth-last-child(2)',
  2646. )
  2647. }
  2648. }
  2649.  
  2650. if (hideCssSelectors.length > 0) {
  2651. cssRules.push(`
  2652. ${hideCssSelectors.join(',\n')} {
  2653. display: none !important;
  2654. }
  2655. `)
  2656. }
  2657.  
  2658. $style.textContent = cssRules.map(dedent).join('\n')
  2659. }
  2660. })()
  2661.  
  2662. function configureFont() {
  2663. if (!fontFamilyRule) {
  2664. warn('no fontFamilyRule found for configureFont to use')
  2665. return
  2666. }
  2667.  
  2668. if (config.dontUseChirpFont) {
  2669. if (fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2670. fontFamilyRule.style.fontFamily = fontFamilyRule.style.fontFamily.replace(/"?TwitterChirp"?, ?/, '')
  2671. log('disabled Chirp font')
  2672. }
  2673. } else if (!fontFamilyRule.style.fontFamily.includes('TwitterChirp')) {
  2674. fontFamilyRule.style.fontFamily = `"TwitterChirp", ${fontFamilyRule.style.fontFamily}`
  2675. log(`enabled Chirp font`)
  2676. }
  2677. }
  2678.  
  2679. /**
  2680. * @param {string[]} cssRules
  2681. * @param {string[]} hideCssSelectors
  2682. */
  2683. function configureHideMetricsCss(cssRules, hideCssSelectors) {
  2684. if (config.hideFollowingMetrics) {
  2685. // User profile hover card and page metrics
  2686. hideCssSelectors.push(
  2687. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) > :first-child'
  2688. )
  2689. // Fix display of whitespace after hidden metrics
  2690. cssRules.push(
  2691. ':is(#layers, body.Profile) a:is([href$="/following"], [href$="/followers"]) { white-space: pre-line; }'
  2692. )
  2693. }
  2694.  
  2695. if (config.hideTotalTweetsMetrics) {
  2696. // Tweet count under username header on profile pages
  2697. hideCssSelectors.push(
  2698. mobile ? `
  2699. body.Profile header > div > div:first-of-type h2 + div[dir],
  2700. body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} > div > div:first-of-type h2 + div[dir]
  2701. ` : `body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 + div[dir]`
  2702. )
  2703. }
  2704.  
  2705. let individualTweetMetricSelectors = [
  2706. config.hideRetweetMetrics && '[href$="/retweets"]',
  2707. config.hideLikeMetrics && '[href$="/likes"]',
  2708. config.hideQuoteTweetMetrics && '[href$="/retweets/with_comments"]',
  2709. ].filter(Boolean).join(', ')
  2710.  
  2711. if (individualTweetMetricSelectors) {
  2712. // Individual tweet metrics
  2713. hideCssSelectors.push(
  2714. `body.Tweet a:is(${individualTweetMetricSelectors}) > :first-child`,
  2715. `[aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) > :first-child`
  2716. )
  2717. // Fix display of whitespace after hidden metrics
  2718. cssRules.push(
  2719. `body.Tweet a:is(${individualTweetMetricSelectors}), [aria-modal="true"] [data-testid="tweet"] a:is(${individualTweetMetricSelectors}) { white-space: pre-line; }`
  2720. )
  2721. }
  2722.  
  2723. if (config.hideBookmarkMetrics) {
  2724. // Bookmark metrics are the only one without a link
  2725. hideCssSelectors.push('[data-testid="tweet"][tabindex="-1"] [role="group"]:not([id]) > div > div')
  2726. }
  2727.  
  2728. let timelineMetricSelectors = [
  2729. config.hideReplyMetrics && '[data-testid="reply"]',
  2730. config.hideRetweetMetrics && '[data-testid$="retweet"]',
  2731. config.hideLikeMetrics && '[data-testid$="like"]',
  2732. ].filter(Boolean).join(', ')
  2733.  
  2734. if (timelineMetricSelectors) {
  2735. cssRules.push(
  2736. `[role="group"] div:is(${timelineMetricSelectors}) span { visibility: hidden; }`
  2737. )
  2738. }
  2739. }
  2740.  
  2741. const configureNavFontSizeCss = (() => {
  2742. let $style
  2743.  
  2744. return function configureNavFontSizeCss() {
  2745. if ($style == null) {
  2746. $style = addStyle('nav-font-size')
  2747. }
  2748. let cssRules = []
  2749.  
  2750. if (fontSize != null && config.navBaseFontSize) {
  2751. cssRules.push(`
  2752. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] span { font-size: ${fontSize}; font-weight: normal; }
  2753. ${Selectors.PRIMARY_NAV_DESKTOP} div[dir] { margin-top: -4px; }
  2754. `)
  2755. }
  2756.  
  2757. $style.textContent = cssRules.map(dedent).join('\n')
  2758. }
  2759. })()
  2760.  
  2761. /**
  2762. * Configures – or re-configures – the separated tweets timeline title.
  2763. *
  2764. * If we're currently on the separated tweets timeline and…
  2765. * - …its title has changed, the page title will be changed to "navigate" to it.
  2766. * - …the separated tweets timeline is no longer needed, we'll change the page
  2767. * title to "navigate" back to the main timeline.
  2768. *
  2769. * @returns {boolean} `true` if "navigation" was triggered by this call
  2770. */
  2771. function configureSeparatedTweetsTimelineTitle() {
  2772. let wasOnSeparatedTweetsTimeline = isOnSeparatedTweetsTimeline()
  2773. let previousTitle = separatedTweetsTimelineTitle
  2774.  
  2775. if (config.retweets == 'separate' && config.quoteTweets == 'separate') {
  2776. separatedTweetsTimelineTitle = getString('SHARED_TWEETS')
  2777. } else if (config.retweets == 'separate') {
  2778. separatedTweetsTimelineTitle = getString('RETWEETS')
  2779. } else if (config.quoteTweets == 'separate') {
  2780. separatedTweetsTimelineTitle = getString('QUOTE_TWEETS')
  2781. } else {
  2782. separatedTweetsTimelineTitle = null
  2783. }
  2784.  
  2785. let titleChanged = previousTitle != separatedTweetsTimelineTitle
  2786. if (wasOnSeparatedTweetsTimeline) {
  2787. if (separatedTweetsTimelineTitle == null) {
  2788. log('moving from separated tweets timeline to main timeline after config change')
  2789. setTitle(getString('HOME'))
  2790. return true
  2791. }
  2792. if (titleChanged) {
  2793. log('applying new separated tweets timeline title after config change')
  2794. setTitle(separatedTweetsTimelineTitle)
  2795. return true
  2796. }
  2797. } else {
  2798. if (titleChanged && previousTitle != null && lastMainTimelineTitle == previousTitle) {
  2799. log('updating lastMainTimelineTitle with new separated tweets timeline title')
  2800. lastMainTimelineTitle = separatedTweetsTimelineTitle
  2801. }
  2802. }
  2803. }
  2804.  
  2805. const configureThemeCss = (() => {
  2806. let $style
  2807.  
  2808. return function configureThemeCss() {
  2809. if ($style == null) {
  2810. $style = addStyle('theme')
  2811. }
  2812. let cssRules = []
  2813.  
  2814. if (debug) {
  2815. cssRules.push(`
  2816. [data-item-type]::after {
  2817. position: absolute;
  2818. top: 0;
  2819. ${ltr ? 'right': 'left'}: 50px;
  2820. content: attr(data-item-type);
  2821. font-family: ${fontFamilyRule?.style.fontFamily || '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial'};
  2822. background-color: rgb(242, 29, 29);
  2823. color: white;
  2824. font-size: 11px;
  2825. font-weight: bold;
  2826. padding: 4px 6px;
  2827. border-bottom-left-radius: 1em;
  2828. border-bottom-right-radius: 1em;
  2829. }
  2830. `)
  2831. }
  2832.  
  2833. // Active tab colour for custom tabs
  2834. if (themeColor != null && shouldShowSeparatedTweetsTab()) {
  2835. cssRules.push(`
  2836. body.SeparatedTweets #tnt_separated_tweets_tab > a > div > div > div {
  2837. background-color: ${themeColor} !important;
  2838. }
  2839. `)
  2840. }
  2841.  
  2842. if (config.replaceLogo) {
  2843. cssRules.push(`
  2844. ${Selectors.X_LOGO_PATH} {
  2845. ${themeColor ? `fill: ${themeColor};` : ''}
  2846. d: path("${Svgs.TWITTER_LOGO_PATH}");
  2847. }
  2848. .tnt_logo {
  2849. ${themeColor ? `fill: ${themeColor};` : ''}
  2850. }
  2851. `)
  2852. }
  2853.  
  2854. if (config.uninvertFollowButtons) {
  2855. // Shared styles for Following and Follow buttons
  2856. cssRules.push(`
  2857. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2858. border-color: rgba(0, 0, 0, 0) !important;
  2859. }
  2860. [role="button"][data-testid$="-follow"] {
  2861. background-color: rgba(0, 0, 0, 0) !important;
  2862. }
  2863. `)
  2864. if (config.followButtonStyle == 'monochrome' || themeColor == null) {
  2865. cssRules.push(`
  2866. /* Following button */
  2867. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2868. background-color: rgb(15, 20, 25) !important;
  2869. }
  2870. body.Default [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2871. color: rgb(255, 255, 255) !important;
  2872. }
  2873. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2874. background-color: rgb(255, 255, 255) !important;
  2875. }
  2876. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2877. color: rgb(15, 20, 25) !important;
  2878. }
  2879. /* Follow button */
  2880. body.Default [role="button"][data-testid$="-follow"] {
  2881. border-color: rgb(207, 217, 222) !important;
  2882. }
  2883. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] {
  2884. border-color: rgb(83, 100, 113) !important;
  2885. }
  2886. body.Default [role="button"][data-testid$="-follow"] > :is(div, span) {
  2887. color: rgb(15, 20, 25) !important;
  2888. }
  2889. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"] > :is(div, span) {
  2890. color: rgb(255, 255, 255) !important;
  2891. }
  2892. body.Default [role="button"][data-testid$="-follow"]:hover {
  2893. background-color: rgba(15, 20, 25, 0.1) !important;
  2894. }
  2895. body:is(.Dim, .LightsOut) [role="button"][data-testid$="-follow"]:hover {
  2896. background-color: rgba(255, 255, 255, 0.1) !important;
  2897. }
  2898. `)
  2899. }
  2900. if (config.followButtonStyle == 'themed' && themeColor != null) {
  2901. cssRules.push(`
  2902. /* Following button */
  2903. [role="button"][data-testid$="-unfollow"]:not(:hover) {
  2904. background-color: ${themeColor} !important;
  2905. }
  2906. [role="button"][data-testid$="-unfollow"]:not(:hover) > :is(div, span) {
  2907. color: rgb(255, 255, 255) !important;
  2908. }
  2909. /* Follow button */
  2910. [role="button"][data-testid$="-follow"] {
  2911. border-color: ${themeColor} !important;
  2912. }
  2913. [role="button"][data-testid$="-follow"] > :is(div, span) {
  2914. color: ${themeColor} !important;
  2915. }
  2916. [role="button"][data-testid$="-follow"]:hover {
  2917. background-color: ${themeColor} !important;
  2918. }
  2919. [role="button"][data-testid$="-follow"]:hover > :is(div, span) {
  2920. color: rgb(255, 255, 255) !important;
  2921. }
  2922. `)
  2923. }
  2924. if (mobile) {
  2925. cssRules.push(`
  2926. body.MediaViewer [role="button"][data-testid$="follow"]:not(:hover) {
  2927. border: revert !important;
  2928. background-color: transparent !important;
  2929. }
  2930. body.MediaViewer [role="button"][data-testid$="follow"]:not(:hover) > div {
  2931. color: ${themeColor} !important;
  2932. }
  2933. `)
  2934. }
  2935. }
  2936.  
  2937. $style.textContent = cssRules.map(dedent).join('\n')
  2938. }
  2939. })()
  2940.  
  2941. /**
  2942. * @param {HTMLElement} $tweet
  2943. * @param {?{getText?: boolean}} options
  2944. * @returns {import("./types").QuotedTweet}
  2945. */
  2946. function getQuotedTweetDetails($tweet, options = {}) {
  2947. let {getText = false} = options
  2948. let $quotedTweet = $tweet.querySelector('div[id^="id__"] > div[dir] > span').parentElement.nextElementSibling
  2949. let $userName = $quotedTweet?.querySelector('[data-testid="User-Name"]')
  2950. let user = $userName?.querySelector('[tabindex="-1"]')?.textContent
  2951. let time = $userName?.querySelector('time')?.dateTime
  2952. if (!getText) return {user, time}
  2953.  
  2954. let $heading = $quotedTweet?.querySelector(':scope > div > div:first-child')
  2955. let $qtText = $heading?.nextElementSibling?.querySelector('[lang]')
  2956. let text = $qtText && Array.from($qtText.childNodes, node => {
  2957. if (node.nodeType == 1) {
  2958. if (node.nodeName == 'IMG') return node.alt
  2959. return node.textContent
  2960. }
  2961. return node.nodeValue
  2962. }).join('')
  2963. return {user, time, text}
  2964. }
  2965.  
  2966. /**
  2967. * Attempts to determine the type of a timeline Tweet given the element with
  2968. * data-testid="tweet" on it, falling back to TWEET if it doesn't appear to be
  2969. * one of the particular types we care about.
  2970. * @param {HTMLElement} $tweet
  2971. * @param {?boolean} checkSocialContext
  2972. * @returns {import("./types").TweetType}
  2973. */
  2974. function getTweetType($tweet, checkSocialContext = false) {
  2975. if ($tweet.closest(Selectors.PROMOTED_TWEET_CONTAINER)) {
  2976. return 'PROMOTED_TWEET'
  2977. }
  2978. // Assume social context tweets are Retweets
  2979. if ($tweet.querySelector('[data-testid="socialContext"]')) {
  2980. if (checkSocialContext) {
  2981. let svgPath = $tweet.querySelector('svg path')?.getAttribute('d') ?? ''
  2982. if (svgPath.startsWith('M7 4.5C7 3.12 8.12 2 9.5 2h5C1')) return 'PINNED_TWEET'
  2983. }
  2984. // Quoted tweets from accounts you blocked or muted are displayed as an
  2985. // <article> with "This Tweet is unavailable."
  2986. if ($tweet.querySelector('article')) {
  2987. return 'UNAVAILABLE_RETWEET'
  2988. }
  2989. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2990. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2991. return 'RETWEETED_QUOTE_TWEET'
  2992. }
  2993. return 'RETWEET'
  2994. }
  2995. // Quoted tweets are preceded by visually-hidden "Quote Tweet" text
  2996. if ($tweet.querySelector('div[id^="id__"] > div[dir] > span')?.textContent.includes(getString('QUOTE_TWEET'))) {
  2997. return 'QUOTE_TWEET'
  2998. }
  2999. // Quoted tweets from accounts you blocked or muted are displayed as an
  3000. // <article> with "This Tweet is unavailable."
  3001. if ($tweet.querySelector('article')) {
  3002. return 'UNAVAILABLE_QUOTE_TWEET'
  3003. }
  3004. return 'TWEET'
  3005. }
  3006.  
  3007. // Add 1 every time this gets broken: 6
  3008. function getVerifiedProps($svg) {
  3009. let propsGetter = (props) => props?.children?.props?.children?.[0]?.[0]?.props
  3010. let $parent = $svg.parentElement.parentElement
  3011. // Verified badge button on the profile screen
  3012. if (isOnProfilePage() && $svg.parentElement.getAttribute('role') == 'button') {
  3013. $parent = $svg.closest('span').parentElement
  3014. }
  3015. // Link variant in "user followed/liked/retweeted" notifications
  3016. else if (isOnNotificationsPage() && $parent.getAttribute('role') == 'link') {
  3017. propsGetter = (props) => {
  3018. let linkChildren = props?.children?.props?.children?.[0]
  3019. return linkChildren?.[linkChildren.length - 1]?.props
  3020. }
  3021. }
  3022. if ($parent.wrappedJSObject) {
  3023. $parent = $parent.wrappedJSObject
  3024. }
  3025. let reactPropsKey = Object.keys($parent).find(key => key.startsWith('__reactProps$'))
  3026. let props = propsGetter($parent[reactPropsKey])
  3027. if (!props) {
  3028. warn('React props not found for', $svg)
  3029. }
  3030. else if (!('isVerified' in props)) {
  3031. warn('isVerified not in React props for', $svg, {props})
  3032. }
  3033. return props
  3034. }
  3035.  
  3036. /**
  3037. * @param {HTMLElement} $popup
  3038. * @returns {{tookAction: boolean, onPopupClosed?: () => void}}
  3039. */
  3040. function handlePopup($popup) {
  3041. let result = {tookAction: false, onPopupClosed: null}
  3042.  
  3043. if (desktop && !isDesktopComposeTweetModalOpen && location.pathname.startsWith(PagePaths.COMPOSE_TWEET)) {
  3044. log('compose tweet modal opened')
  3045. isDesktopComposeTweetModalOpen = true
  3046. observeDesktopComposeTweetModal($popup)
  3047. return {
  3048. tookAction: true,
  3049. onPopupClosed() {
  3050. log('compose tweet modal closed')
  3051. isDesktopComposeTweetModalOpen = false
  3052. // The Tweet button will re-render if the modal was opened to edit
  3053. // multiple Tweets on the home timeline.
  3054. if (config.replaceLogo && isOnHomeTimeline()) {
  3055. tweakTweetButton()
  3056. }
  3057. }
  3058. }
  3059. }
  3060.  
  3061. if (desktop && !isDesktopMediaModalOpen && URL_MEDIA_RE.test(location.pathname) && currentPath != location.pathname) {
  3062. log('media modal opened')
  3063. isDesktopMediaModalOpen = true
  3064. observeDesktopModalTimeline()
  3065. return {
  3066. tookAction: true,
  3067. onPopupClosed() {
  3068. log('media modal closed')
  3069. isDesktopMediaModalOpen = false
  3070. disconnectAllModalObservers()
  3071. }
  3072. }
  3073. }
  3074.  
  3075. if (config.twitterBlueChecks != 'ignore' && desktop && !isDesktopUserListModalOpen && URL_TWEET_LIKES_RETWEETS_RE.test(location.pathname)) {
  3076. let modalType = URL_TWEET_LIKES_RETWEETS_RE.exec(location.pathname)[1]
  3077. log(`${modalType} modal opened`)
  3078. isDesktopUserListModalOpen = true
  3079. observeUserListTimeline($popup, location.pathname)
  3080. return {
  3081. tookAction: true,
  3082. onPopupClosed() {
  3083. log(`${modalType} modal closed`)
  3084. isDesktopUserListModalOpen = false
  3085. disconnectAllModalObservers()
  3086. }
  3087. }
  3088. }
  3089.  
  3090. if (isOnListPage()) {
  3091. let $switchSvg = $popup.querySelector(`svg path[d^="M12 3.75c-4.56 0-8.25 3.69-8.25 8.25s"]`)
  3092. if ($switchSvg) {
  3093. addToggleListRetweetsMenuItem($popup.querySelector(`[role="menuitem"]`))
  3094. return {tookAction: true}
  3095. }
  3096. }
  3097.  
  3098. if (config.mutableQuoteTweets) {
  3099. if (quotedTweet) {
  3100. let $blockMenuItem = /** @type {HTMLElement} */ ($popup.querySelector(Selectors.BLOCK_MENU_ITEM))
  3101. if ($blockMenuItem) {
  3102. addMuteQuotesMenuItem($blockMenuItem)
  3103. result.tookAction = true
  3104. // Clear the quoted tweet when the popup closes
  3105. result.onPopupClosed = () => {
  3106. quotedTweet = null
  3107. }
  3108. } else {
  3109. quotedTweet = null
  3110. }
  3111. }
  3112. }
  3113.  
  3114. if (config.fastBlock) {
  3115. if (blockMenuItemSeen && $popup.querySelector('[data-testid="confirmationSheetConfirm"]')) {
  3116. log('fast blocking')
  3117. ;/** @type {HTMLElement} */ ($popup.querySelector('[data-testid="confirmationSheetConfirm"]')).click()
  3118. result.tookAction = true
  3119. }
  3120. else if ($popup.querySelector(Selectors.BLOCK_MENU_ITEM)) {
  3121. log('preparing for fast blocking')
  3122. blockMenuItemSeen = true
  3123. // Create a nested observer for mobile, as it reuses the popup element
  3124. result.tookAction = !mobile
  3125. } else {
  3126. blockMenuItemSeen = false
  3127. }
  3128. }
  3129.  
  3130. if (config.hideTwitterBlueUpsells) {
  3131. // The "Pin to your profile" menu item is currently the only one which opens
  3132. // a sheet dialog.
  3133. if (pinMenuItemSeen && $popup.querySelector('[data-testid="sheetDialog"]')) {
  3134. log('pin to your profile modal opened')
  3135. $popup.classList.add('PinModal')
  3136. result.tookAction = true
  3137. }
  3138. else if ($popup.querySelector('[data-testid="highlighOnPin"]')) {
  3139. log('preparing to hide Twitter Blue upsell when pinning a tweet')
  3140. pinMenuItemSeen = true
  3141. // Create a nested observer for mobile, as it reuses the popup element
  3142. result.tookAction = !mobile
  3143. } else {
  3144. pinMenuItemSeen = false
  3145. }
  3146. }
  3147.  
  3148. if (config.addAddMutedWordMenuItem) {
  3149. let linkSelector = desktop ? 'a[href$="/compose/tweet/unsent/drafts"]' : 'a[href$="/bookmarks"]'
  3150. let $link = /** @type {HTMLElement} */ ($popup.querySelector(linkSelector))
  3151. if ($link) {
  3152. addAddMutedWordMenuItem($link, linkSelector)
  3153. result.tookAction = true
  3154. }
  3155. }
  3156.  
  3157. if (config.twitterBlueChecks != 'ignore') {
  3158. // User typeahead dropdown
  3159. let $typeaheadDropdown = /** @type {HTMLElement} */ ($popup.querySelector('div[id^="typeaheadDropdown"]'))
  3160. if ($typeaheadDropdown) {
  3161. log('typeahead dropdown appeared')
  3162. let observer = observeElement($typeaheadDropdown, () => {
  3163. processBlueChecks($typeaheadDropdown)
  3164. }, 'popup typeahead dropdown')
  3165. return {
  3166. tookAction: true,
  3167. onPopupClosed() {
  3168. log('typeahead dropdown closed')
  3169. observer.disconnect()
  3170. }
  3171. }
  3172. }
  3173.  
  3174. // User hovercard popup
  3175. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  3176. if ($hoverCard) {
  3177. result.tookAction = true
  3178. getElement('div[data-testid^="UserAvatar-Container"]', {
  3179. context: $hoverCard,
  3180. name: 'user hovercard contents',
  3181. timeout: 500,
  3182. }).then(($contents) => {
  3183. if ($contents) processBlueChecks($popup)
  3184. })
  3185. }
  3186. }
  3187.  
  3188. // Verified account popup when you press the check button on a profile page
  3189. if (config.twitterBlueChecks == 'replace' && isOnProfilePage()) {
  3190. if (mobile) {
  3191. let $verificationBadge = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="sheetDialog"] [data-testid="verificationBadge"]'))
  3192. if ($verificationBadge) {
  3193. result.tookAction = true
  3194. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.MOBILE_TIMELINE_HEADER_NEW} .tnt_blue_check`)
  3195. if ($headerBlueCheck) {
  3196. blueCheck($verificationBadge)
  3197. }
  3198. }
  3199. } else {
  3200. let $hoverCard = /** @type {HTMLElement} */ ($popup.querySelector('[data-testid="HoverCard"]'))
  3201. if ($hoverCard) {
  3202. result.tookAction = true
  3203. getElement(':scope > div > div > div > svg[data-testid="verificationBadge"]', {
  3204. context: $hoverCard,
  3205. name: 'verified account hovercard verification badge',
  3206. timeout: 500,
  3207. }).then(($verificationBadge) => {
  3208. if (!$verificationBadge) return
  3209.  
  3210. let $headerBlueCheck = document.querySelector(`body.Profile ${Selectors.PRIMARY_COLUMN} > div > div:first-of-type h2 .tnt_blue_check`)
  3211. if (!$headerBlueCheck) return
  3212.  
  3213. // Wait for the hovercard to render its contents
  3214. let popupRenderObserver = observeElement($popup, (mutations) => {
  3215. if (!mutations.length) return
  3216. blueCheck($popup.querySelector('svg[data-testid="verificationBadge"]'))
  3217. popupRenderObserver.disconnect()
  3218. }, 'verified popup render', {childList: true, subtree: true})
  3219. })
  3220. }
  3221. }
  3222. }
  3223.  
  3224. return result
  3225. }
  3226.  
  3227. function isBlueVerified($svg) {
  3228. let props = getVerifiedProps($svg)
  3229. return Boolean(props && props.isBlueVerified && !(
  3230. props.verifiedType || (
  3231. props.affiliateBadgeInfo?.userLabelType == 'BusinessLabel' &&
  3232. props.affiliateBadgeInfo?.description == 'X'
  3233. )
  3234. ))
  3235. }
  3236.  
  3237. /**
  3238. * Checks if a tweet is preceded by an element creating a vertical reply line.
  3239. * @param {HTMLElement} $tweet
  3240. * @returns {boolean}
  3241. */
  3242. function isReplyToPreviousTweet($tweet) {
  3243. let $replyLine = $tweet.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild?.firstElementChild
  3244. if ($replyLine) {
  3245. return getComputedStyle($replyLine).width == '2px'
  3246. }
  3247. }
  3248.  
  3249. /**
  3250. * @returns {{disconnect()}}
  3251. */
  3252. function onPopup($popup) {
  3253. log('popup appeared', $popup, location.pathname)
  3254.  
  3255. // If handlePopup did something, we don't need to observe nested popups
  3256. let {tookAction, onPopupClosed} = handlePopup($popup)
  3257. if (tookAction) {
  3258. return onPopupClosed ? {disconnect: onPopupClosed} : null
  3259. }
  3260.  
  3261. /** @type {HTMLElement} */
  3262. let $nestedPopup
  3263.  
  3264. let nestedObserver = observeElement($popup, (mutations) => {
  3265. mutations.forEach((mutation) => {
  3266. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3267. log('nested popup appeared', $el)
  3268. $nestedPopup = $el
  3269. ;({onPopupClosed} = handlePopup($el))
  3270. })
  3271. mutation.removedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  3272. if ($el !== $nestedPopup) return
  3273. if (onPopupClosed) {
  3274. log('cleaning up after nested popup removed')
  3275. onPopupClosed()
  3276. }
  3277. })
  3278. })
  3279. })
  3280.  
  3281. let disconnect = nestedObserver.disconnect.bind(nestedObserver)
  3282. nestedObserver.disconnect = () => {
  3283. if (onPopupClosed) {
  3284. log('cleaning up after nested popup observer disconnected')
  3285. onPopupClosed()
  3286. }
  3287. disconnect()
  3288. }
  3289.  
  3290. return nestedObserver
  3291. }
  3292.  
  3293. /**
  3294. * @param {HTMLElement} $timeline
  3295. * @param {string} page
  3296. * @param {import("./types").TimelineOptions?} options
  3297. */
  3298. function onTimelineChange($timeline, page, options = {}) {
  3299. let startTime = Date.now()
  3300. let {classifyTweets = true, hideHeadings = true} = options
  3301.  
  3302. let isOnMainTimeline = isOnMainTimelinePage()
  3303. let isOnListTimeline = isOnListPage()
  3304. let isOnProfileTimeline = isOnProfilePage()
  3305. let timelineHasSpecificHandling = isOnMainTimeline || isOnListTimeline || isOnProfileTimeline
  3306.  
  3307. if (config.twitterBlueChecks != 'ignore' && !timelineHasSpecificHandling) {
  3308. processBlueChecks($timeline)
  3309. }
  3310.  
  3311. if (isSafari && config.replaceLogo && isOnNotificationsPage()) {
  3312. processTwitterLogos($timeline)
  3313. }
  3314.  
  3315. if (!classifyTweets) return
  3316.  
  3317. let itemTypes = {}
  3318. let hiddenItemCount = 0
  3319. let hiddenItemTypes = {}
  3320.  
  3321. /** @type {?boolean} */
  3322. let hidPreviousItem = null
  3323. /** @type {{$item: Element, hideItem?: boolean}[]} */
  3324. let changes = []
  3325.  
  3326. for (let $item of $timeline.children) {
  3327. /** @type {?import("./types").TimelineItemType} */
  3328. let itemType = null
  3329. /** @type {?boolean} */
  3330. let hideItem = null
  3331. /** @type {?HTMLElement} */
  3332. let $tweet = $item.querySelector(Selectors.TWEET)
  3333. /** @type {boolean} */
  3334. let isReply = false
  3335. /** @type {boolean} */
  3336. let isBlueTweet = false
  3337.  
  3338. if ($tweet != null) {
  3339. itemType = getTweetType($tweet, isOnProfileTimeline)
  3340. if (timelineHasSpecificHandling) {
  3341. isReply = isReplyToPreviousTweet($tweet)
  3342. if (isReply && hidPreviousItem != null) {
  3343. hideItem = hidPreviousItem
  3344. } else {
  3345. if (isOnMainTimeline) {
  3346. hideItem = shouldHideMainTimelineItem(itemType, page)
  3347. }
  3348. else if (isOnListTimeline) {
  3349. hideItem = shouldHideListTimelineItem(itemType)
  3350. }
  3351. else if (isOnProfileTimeline) {
  3352. hideItem = shouldHideProfileTimelineItem(itemType)
  3353. }
  3354. }
  3355.  
  3356. if (!hideItem && config.mutableQuoteTweets && (itemType == 'QUOTE_TWEET' || itemType == 'RETWEETED_QUOTE_TWEET')) {
  3357. if (config.mutedQuotes.length > 0) {
  3358. let quotedTweet = getQuotedTweetDetails($tweet)
  3359. hideItem = config.mutedQuotes.some(muted => muted.user == quotedTweet.user && muted.time == quotedTweet.time)
  3360. }
  3361. if (!hideItem) {
  3362. addCaretMenuListenerForQuoteTweet($tweet)
  3363. }
  3364. }
  3365.  
  3366. if (config.twitterBlueChecks != 'ignore') {
  3367. for (let $svg of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  3368. let isBlueCheck = isBlueVerified($svg)
  3369. if (!isBlueCheck) continue
  3370.  
  3371. blueCheck($svg)
  3372.  
  3373. let userProfileLink = $svg.closest('a[role="link"]:not([href^="/i/status"])')
  3374. if (!userProfileLink) continue
  3375.  
  3376. isBlueTweet = true
  3377. }
  3378. }
  3379. }
  3380. }
  3381. else if (!timelineHasSpecificHandling) {
  3382. if ($item.querySelector(':scope > div > div > div > article')) {
  3383. itemType = 'UNAVAILABLE'
  3384. }
  3385. }
  3386.  
  3387. if (!timelineHasSpecificHandling) {
  3388. if (itemType != null) {
  3389. hideItem = shouldHideOtherTimelineItem(itemType)
  3390. }
  3391. }
  3392.  
  3393. if (itemType == null) {
  3394. if ($item.querySelector(Selectors.TIMELINE_HEADING)) {
  3395. itemType = 'HEADING'
  3396. hideItem = hideHeadings && config.hideWhoToFollowEtc
  3397. }
  3398. }
  3399.  
  3400. if (debug && itemType != null) {
  3401. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${isBlueTweet ? ' / BLUE' : ''}`
  3402. }
  3403.  
  3404. // Assume a non-identified item following an identified item is related
  3405. if (itemType == null && hidPreviousItem != null) {
  3406. hideItem = hidPreviousItem
  3407. itemType = 'SUBSEQUENT_ITEM'
  3408. }
  3409.  
  3410. if (itemType != null) {
  3411. itemTypes[itemType] ||= 0
  3412. itemTypes[itemType]++
  3413. }
  3414.  
  3415. if (hideItem) {
  3416. hiddenItemCount++
  3417. hiddenItemTypes[itemType] ||= 0
  3418. hiddenItemTypes[itemType]++
  3419. }
  3420.  
  3421. if (hideItem != null && $item.firstElementChild) {
  3422. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  3423. changes.push({$item, hideItem})
  3424. }
  3425. }
  3426.  
  3427. hidPreviousItem = hideItem
  3428. }
  3429.  
  3430. for (let change of changes) {
  3431. /** @type {HTMLElement} */ (change.$item.firstElementChild).style.display = change.hideItem ? 'none' : ''
  3432. }
  3433.  
  3434. log(
  3435. `processed ${$timeline.children.length} timeline item${s($timeline.children.length)} in ${Date.now() - startTime}ms`,
  3436. itemTypes, `hid ${hiddenItemCount}`, hiddenItemTypes
  3437. )
  3438. }
  3439.  
  3440. /**
  3441. * @param {HTMLElement} $timeline
  3442. */
  3443. function onIndividualTweetTimelineChange($timeline) {
  3444. let startTime = Date.now()
  3445.  
  3446. let itemTypes = {}
  3447. let hiddenItemCount = 0
  3448. let hiddenItemTypes = {}
  3449.  
  3450. /** @type {?boolean} */
  3451. let hidPreviousItem = null
  3452. /** @type {boolean} */
  3453. let hideAllSubsequentItems = false
  3454. /** @type {string} */
  3455. let opScreenName = /^\/([a-zA-Z\d_]{1,20})\//.exec(location.pathname)[1].toLowerCase()
  3456. /** @type {{$item: Element, hideItem?: boolean}[]} */
  3457. let changes = []
  3458. /** @type {import("./types").UserInfoObject} */
  3459. let userInfo = getUserInfo()
  3460.  
  3461. for (let $item of $timeline.children) {
  3462. /** @type {?import("./types").TimelineItemType} */
  3463. let itemType = null
  3464. /** @type {?boolean} */
  3465. let hideItem = null
  3466. /** @type {?HTMLElement} */
  3467. let $tweet = $item.querySelector(Selectors.TWEET)
  3468. /** @type {boolean} */
  3469. let isFocusedTweet = false
  3470. /** @type {boolean} */
  3471. let isReply = false
  3472. /** @type {boolean} */
  3473. let isBlueTweet = false
  3474. /** @type {boolean} */
  3475. let isShy = false
  3476. /** @type {?string} */
  3477. let screenName = null
  3478.  
  3479. if (hideAllSubsequentItems) {
  3480. hideItem = true
  3481. itemType = 'DISCOVER_MORE_TWEET'
  3482. }
  3483. else if ($tweet != null) {
  3484. isFocusedTweet = $tweet.tabIndex == -1
  3485. isReply = isReplyToPreviousTweet($tweet)
  3486. if (isFocusedTweet) {
  3487. itemType = 'FOCUSED_TWEET'
  3488. hideItem = false
  3489. } else {
  3490. itemType = getTweetType($tweet)
  3491. if (isReply && hidPreviousItem != null) {
  3492. hideItem = hidPreviousItem
  3493. } else {
  3494. hideItem = shouldHideIndividualTweetTimelineItem(itemType)
  3495. }
  3496. }
  3497.  
  3498. if (config.twitterBlueChecks != 'ignore' || config.hideTwitterBlueReplies) {
  3499. for (let $svg of $tweet.querySelectorAll(Selectors.VERIFIED_TICK)) {
  3500. let isBlueCheck = isBlueVerified($svg)
  3501. if (!isBlueCheck) continue
  3502.  
  3503. if (config.twitterBlueChecks != 'ignore') {
  3504. blueCheck($svg)
  3505. }
  3506.  
  3507. let $userProfileLink = /** @type {HTMLAnchorElement} */ ($svg.closest('a[role="link"]:not([href^="/i/status"])'))
  3508. if (!$userProfileLink) continue
  3509.  
  3510. isBlueTweet = true
  3511. screenName = $userProfileLink.href.split('/').pop()
  3512. }
  3513.  
  3514. // Check replies to the focused tweet for Blue users hiding their check
  3515. // if (!isBlueTweet && !isFocusedTweet && !isReply) {
  3516. // let $userProfileLink = /** @type {HTMLAnchorElement} */ ($tweet.querySelector('[data-testid="User-Name"] a'))
  3517. // if ($userProfileLink) {
  3518. // screenName = $userProfileLink.href.split('/').pop()
  3519. // if (userInfo[screenName]?.shyBlue) {
  3520. // isBlueTweet = true
  3521. // isShy = true
  3522. // }
  3523. // }
  3524. // }
  3525.  
  3526. // Replies to the focused tweet don't have the reply indicator
  3527. if (isBlueTweet && !isFocusedTweet && !isReply && screenName.toLowerCase() != opScreenName) {
  3528. itemType = 'BLUE_REPLY'
  3529. if (!hideItem) {
  3530. let user = userInfo[screenName]
  3531. hideItem = config.hideTwitterBlueReplies && (user == null || !(
  3532. user.following && !config.hideBlueReplyFollowing ||
  3533. user.followedBy && !config.hideBlueReplyFollowedBy ||
  3534. user.followersCount >= 1000000 && config.showBlueReplyFollowersCount
  3535. ))
  3536. }
  3537. }
  3538. }
  3539. }
  3540. else if ($item.querySelector('article')) {
  3541. if ($item.querySelector('[role="button"]')?.textContent == getString('SHOW')) {
  3542. itemType = 'SHOW_MORE'
  3543. } else {
  3544. itemType = 'UNAVAILABLE'
  3545. hideItem = config.hideUnavailableQuoteTweets
  3546. }
  3547. } else {
  3548. // We need to identify "Show more replies" so it doesn't get hidden if the
  3549. // item immediately before it was hidden.
  3550. let $button = $item.querySelector('div[role="button"]')
  3551. if ($button) {
  3552. if ($button?.textContent == getString('SHOW_MORE_REPLIES')) {
  3553. itemType = 'SHOW_MORE'
  3554. }
  3555. } else {
  3556. let $heading = $item.querySelector(Selectors.TIMELINE_HEADING)
  3557. if ($heading) {
  3558. // Discover More headings have a description next to them
  3559. if ($heading.nextElementSibling &&
  3560. $heading.nextElementSibling.tagName == 'DIV' &&
  3561. $heading.nextElementSibling.getAttribute('dir') != null) {
  3562. itemType = 'DISCOVER_MORE_HEADING'
  3563. hideItem = config.hideMoreTweets
  3564. hideAllSubsequentItems = config.hideMoreTweets
  3565. } else {
  3566. itemType = 'HEADING'
  3567. }
  3568. }
  3569. }
  3570. }
  3571.  
  3572. if (debug && itemType != null) {
  3573. $item.firstElementChild.dataset.itemType = `${itemType}${isReply ? ' / REPLY' : ''}${isBlueTweet && itemType != 'BLUE_REPLY' ? ' / BLUE' : ''}${isShy ? ' / SHY' : ''}`
  3574. }
  3575.  
  3576. // Assume a non-identified item following an identified item is related
  3577. if (itemType == null && hidPreviousItem != null) {
  3578. hideItem = hidPreviousItem
  3579. itemType = 'SUBSEQUENT_ITEM'
  3580. }
  3581.  
  3582. if (itemType != null) {
  3583. itemTypes[itemType] ||= 0
  3584. itemTypes[itemType]++
  3585. }
  3586.  
  3587. if (hideItem) {
  3588. hiddenItemCount++
  3589. hiddenItemTypes[itemType] ||= 0
  3590. hiddenItemTypes[itemType]++
  3591. }
  3592.  
  3593. if (isFocusedTweet) {
  3594. // Tweets prior to the focused tweet should never be hidden
  3595. changes = []
  3596. hiddenItemCount = 0
  3597. hiddenItemTypes = {}
  3598. }
  3599. else if (hideItem != null && $item.firstElementChild) {
  3600. if (/** @type {HTMLElement} */ ($item.firstElementChild).style.display != (hideItem ? 'none' : '')) {
  3601. changes.push({$item, hideItem})
  3602. }
  3603. }
  3604.  
  3605. hidPreviousItem = hideItem
  3606. }
  3607.  
  3608. for (let change of changes) {
  3609. /** @type {HTMLElement} */ (change.$item.firstElementChild).style.display = change.hideItem ? 'none' : ''
  3610. }
  3611.  
  3612. log(
  3613. `processed ${$timeline.children.length} thread item${s($timeline.children.length)} in ${Date.now() - startTime}ms`,
  3614. itemTypes, `hid ${hiddenItemCount}`, hiddenItemTypes
  3615. )
  3616. }
  3617.  
  3618. /**
  3619. * Title format (including notification count):
  3620. * - LTR: (3) ${title} / X
  3621. * - RTL: (3) X \ ${title}
  3622. * @param {string} title
  3623. */
  3624. function onTitleChange(title) {
  3625. log('title changed', {title, path: location.pathname})
  3626.  
  3627. if (checkforDisabledHomeTimeline()) return
  3628.  
  3629. // Ignore leading notification counts in titles
  3630. let notificationCount = ''
  3631. if (TITLE_NOTIFICATION_RE.test(title)) {
  3632. notificationCount = TITLE_NOTIFICATION_RE.exec(title)[0]
  3633. title = title.replace(TITLE_NOTIFICATION_RE, '')
  3634. }
  3635.  
  3636. if (config.replaceLogo && Boolean(notificationCount) != Boolean(currentNotificationCount)) {
  3637. observeFavicon.updatePip(Boolean(notificationCount))
  3638. }
  3639.  
  3640. let homeNavigationWasUsed = homeNavigationIsBeingUsed
  3641. homeNavigationIsBeingUsed = false
  3642.  
  3643. if (title == 'X' || title == getString('TWITTER')) {
  3644. // Mobile uses "Twitter" when viewing media - we need to let these process
  3645. // so the next page will be re-processed when the media is closed.
  3646. if (mobile && (URL_MEDIA_RE.test(location.pathname) || URL_MEDIAVIEWER_RE.test(location.pathname))) {
  3647. log('viewing media on mobile')
  3648. }
  3649. // Ignore Flash of Uninitialised Title when navigating to a page for the
  3650. // first time.
  3651. else {
  3652. log('ignoring Flash of Uninitialised Title')
  3653. return
  3654. }
  3655. }
  3656.  
  3657. // Remove " / Twitter" or "Twitter \ " from the title
  3658. let newPage = title
  3659. if (newPage != 'X' && newPage != getString('TWITTER')) {
  3660. newPage = title.slice(...ltr ? [0, title.lastIndexOf('/') - 1] : [title.indexOf('\\') + 2])
  3661. }
  3662.  
  3663. // Only allow the same page to re-process after a title change on desktop if
  3664. // the "Customize your view" dialog is currently open.
  3665. if (newPage == currentPage && !(desktop && location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW)) {
  3666. log('ignoring duplicate title change')
  3667. currentNotificationCount = notificationCount
  3668. return
  3669. }
  3670.  
  3671. // Search terms are shown in the title
  3672. if (currentPath == PagePaths.SEARCH && location.pathname == PagePaths.SEARCH) {
  3673. log('ignoring title change on Search page')
  3674. currentNotificationCount = notificationCount
  3675. return
  3676. }
  3677.  
  3678. // On desktop, stay on the separated tweets timeline when…
  3679. if (desktop && currentPage == separatedTweetsTimelineTitle &&
  3680. // …the title has changed back to the main timeline…
  3681. (newPage == getString('HOME')) &&
  3682. // …the Home nav link or Following / Home header _wasn't_ clicked and…
  3683. !homeNavigationWasUsed &&
  3684. (
  3685. // …the user viewed media.
  3686. URL_MEDIA_RE.test(location.pathname) ||
  3687. // …the user stopped viewing media.
  3688. URL_MEDIA_RE.test(currentPath) ||
  3689. // …the user opened or used the "Customize your view" dialog.
  3690. location.pathname == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  3691. // …the user closed the "Customize your view" dialog.
  3692. currentPath == PagePaths.CUSTOMIZE_YOUR_VIEW ||
  3693. // …the user opened the "Send via Direct Message" dialog.
  3694. location.pathname == PagePaths.COMPOSE_MESSAGE ||
  3695. // …the user closed the "Send via Direct Message" dialog.
  3696. currentPath == PagePaths.COMPOSE_MESSAGE ||
  3697. // …the user opened the compose Tweet dialog.
  3698. location.pathname == PagePaths.COMPOSE_TWEET ||
  3699. // …the user closed the compose Tweet dialog.
  3700. currentPath == PagePaths.COMPOSE_TWEET ||
  3701. // …the notification count in the title changed.
  3702. notificationCount != currentNotificationCount
  3703. )) {
  3704. log('ignoring title change on separated tweets timeline')
  3705. currentNotificationCount = notificationCount
  3706. currentPath = location.pathname
  3707. setTitle(separatedTweetsTimelineTitle)
  3708. return
  3709. }
  3710.  
  3711. // Restore display of the separated tweets timelne if it's the last one we
  3712. // saw, and the user navigated back home without using the Home navigation
  3713. // item.
  3714. if (location.pathname == PagePaths.HOME &&
  3715. currentPath != PagePaths.HOME &&
  3716. !homeNavigationWasUsed &&
  3717. lastMainTimelineTitle != null &&
  3718. separatedTweetsTimelineTitle != null &&
  3719. lastMainTimelineTitle == separatedTweetsTimelineTitle) {
  3720. log('restoring display of the separated tweets timeline')
  3721. currentNotificationCount = notificationCount
  3722. currentPath = location.pathname
  3723. setTitle(separatedTweetsTimelineTitle)
  3724. return
  3725. }
  3726.  
  3727. // Assumption: all non-FOUT, non-duplicate title changes are navigation, which
  3728. // need the page to be re-processed.
  3729.  
  3730. currentPage = newPage
  3731. currentNotificationCount = notificationCount
  3732. currentPath = location.pathname
  3733.  
  3734. if (isOnMainTimelinePage()) {
  3735. lastMainTimelineTitle = currentPage
  3736. }
  3737.  
  3738. log('processing new page')
  3739.  
  3740. processCurrentPage()
  3741. }
  3742.  
  3743. /**
  3744. * Processes all Twitter Blue checks inside an element.
  3745. * @param {HTMLElement} $el
  3746. */
  3747. function processBlueChecks($el) {
  3748. for (let $svg of $el.querySelectorAll(`${Selectors.VERIFIED_TICK}:not(.tnt_blue_check)`)) {
  3749. if (isBlueVerified($svg)) {
  3750. blueCheck($svg)
  3751. }
  3752. }
  3753. }
  3754.  
  3755. /**
  3756. * Processes all Twitter logos inside an element.
  3757. */
  3758. function processTwitterLogos($el) {
  3759. for (let $svgPath of $el.querySelectorAll(Selectors.X_LOGO_PATH)) {
  3760. twitterLogo($svgPath)
  3761. }
  3762. }
  3763.  
  3764. function processCurrentPage() {
  3765. if (pageObservers.length > 0) {
  3766. log(
  3767. `disconnecting ${pageObservers.length} page observer${s(pageObservers.length)}`,
  3768. pageObservers.map(observer => observer['name'])
  3769. )
  3770. pageObservers.forEach(observer => observer.disconnect())
  3771. pageObservers = []
  3772. }
  3773.  
  3774. // Hooks for styling pages
  3775. $body.classList.toggle('Community', isOnCommunityPage())
  3776. $body.classList.toggle('Explore', isOnExplorePage())
  3777. $body.classList.toggle('HideSidebar', shouldHideSidebar())
  3778. $body.classList.toggle('List', isOnListPage())
  3779. $body.classList.toggle('MainTimeline', isOnMainTimelinePage())
  3780. $body.classList.toggle('Notifications', isOnNotificationsPage())
  3781. $body.classList.toggle('Profile', isOnProfilePage())
  3782. if (!isOnProfilePage()) {
  3783. $body.classList.remove('Blocked', 'NoMedia')
  3784. }
  3785. $body.classList.toggle('QuoteTweets', isOnQuoteTweetsPage())
  3786. $body.classList.toggle('Tweet', isOnIndividualTweetPage())
  3787. $body.classList.toggle('Search', isOnSearchPage())
  3788. $body.classList.toggle('Settings', isOnSettingsPage())
  3789. $body.classList.toggle('MobileMedia', mobile && URL_MEDIA_RE.test(location.pathname))
  3790. $body.classList.toggle('MediaViewer', mobile && URL_MEDIAVIEWER_RE.test(location.pathname))
  3791. $body.classList.remove('TabbedTimeline')
  3792. $body.classList.remove('SeparatedTweets')
  3793.  
  3794. if (desktop) {
  3795. if (config.twitterBlueChecks != 'ignore' || config.fullWidthContent && (isOnMainTimelinePage() || isOnListPage())) {
  3796. observeSidebar()
  3797. } else {
  3798. $body.classList.remove('Sidebar')
  3799. }
  3800. if (isSafari && config.replaceLogo) {
  3801. tweakDesktopLogo()
  3802. }
  3803. }
  3804.  
  3805. if (config.twitterBlueChecks != 'ignore' && (isOnSearchPage() || isOnExplorePage())) {
  3806. observeSearchForm()
  3807. }
  3808.  
  3809. if (isOnMainTimelinePage()) {
  3810. tweakMainTimelinePage()
  3811. }
  3812. else {
  3813. removeMobileTimelineHeaderElements()
  3814. }
  3815.  
  3816. if (isOnProfilePage()) {
  3817. tweakProfilePage()
  3818. }
  3819. else if (isOnFollowListPage()) {
  3820. tweakFollowListPage()
  3821. }
  3822. else if (isOnIndividualTweetPage()) {
  3823. tweakIndividualTweetPage()
  3824. }
  3825. else if (isOnNotificationsPage()) {
  3826. tweakNotificationsPage()
  3827. }
  3828. else if (isOnSearchPage()) {
  3829. tweakSearchPage()
  3830. }
  3831. else if (isOnQuoteTweetsPage()) {
  3832. tweakQuoteTweetsPage()
  3833. }
  3834. else if (isOnListPage()) {
  3835. tweakListPage()
  3836. }
  3837. else if (isOnExplorePage()) {
  3838. tweakExplorePage()
  3839. }
  3840. else if (isOnBookmarksPage()) {
  3841. tweakBookmarksPage()
  3842. }
  3843. else if (isOnCommunitiesPage()) {
  3844. tweakCommunitiesPage()
  3845. }
  3846. else if (isOnCommunityPage()) {
  3847. tweakCommunityPage()
  3848. }
  3849. else if (isOnCommunityMembersPage()) {
  3850. tweakCommunityMembersPage()
  3851. }
  3852.  
  3853. // On mobile, these are pages instead of modals
  3854. if (mobile) {
  3855. if (currentPath == PagePaths.COMPOSE_TWEET) {
  3856. tweakMobileComposeTweetPage()
  3857. }
  3858. else if (URL_MEDIAVIEWER_RE.test(currentPath)) {
  3859. tweakMobileMediaViewerPage()
  3860. }
  3861. else if (URL_TWEET_LIKES_RETWEETS_RE.test(currentPath)) {
  3862. tweakMobileUserListPage()
  3863. }
  3864. }
  3865. }
  3866.  
  3867. /**
  3868. * The mobile version of Twitter reuses heading elements between screens, so we
  3869. * always remove any elements which could be there from the previous page and
  3870. * re-add them later when needed.
  3871. */
  3872. function removeMobileTimelineHeaderElements() {
  3873. if (mobile) {
  3874. document.querySelector('#tnt_separated_tweets_tab')?.remove()
  3875. }
  3876. }
  3877.  
  3878. /**
  3879. * Sets the page name in <title>, retaining any current notification count.
  3880. * @param {string} page
  3881. */
  3882. function setTitle(page) {
  3883. document.title = ltr ? (
  3884. `${currentNotificationCount}${page} / ${getString('TWITTER')}`
  3885. ) : (
  3886. `${currentNotificationCount}${getString('TWITTER')} \\ ${page}`
  3887. )
  3888. }
  3889.  
  3890. /**
  3891. * @param {import("./types").TimelineItemType} type
  3892. * @returns {boolean}
  3893. */
  3894. function shouldHideIndividualTweetTimelineItem(type) {
  3895. switch (type) {
  3896. case 'QUOTE_TWEET':
  3897. case 'RETWEET':
  3898. case 'RETWEETED_QUOTE_TWEET':
  3899. case 'TWEET':
  3900. return false
  3901. case 'UNAVAILABLE_QUOTE_TWEET':
  3902. case 'UNAVAILABLE_RETWEET':
  3903. return config.hideUnavailableQuoteTweets
  3904. default:
  3905. return true
  3906. }
  3907. }
  3908.  
  3909. /**
  3910. * @param {import("./types").TimelineItemType} type
  3911. * @returns {boolean}
  3912. */
  3913. function shouldHideListTimelineItem(type) {
  3914. switch (type) {
  3915. case 'RETWEET':
  3916. case 'RETWEETED_QUOTE_TWEET':
  3917. return config.listRetweets == 'hide'
  3918. case 'UNAVAILABLE_QUOTE_TWEET':
  3919. return config.hideUnavailableQuoteTweets
  3920. case 'UNAVAILABLE_RETWEET':
  3921. return config.hideUnavailableQuoteTweets || config.listRetweets == 'hide'
  3922. default:
  3923. return false
  3924. }
  3925. }
  3926.  
  3927. /**
  3928. * @param {import("./types").TimelineItemType} type
  3929. * @param {string} page
  3930. * @returns {boolean}
  3931. */
  3932. function shouldHideMainTimelineItem(type, page) {
  3933. switch (type) {
  3934. case 'QUOTE_TWEET':
  3935. return shouldHideSharedTweet(config.quoteTweets, page)
  3936. case 'RETWEET':
  3937. return selectedHomeTabIndex >= 2 ? config.listRetweets == 'hide' : shouldHideSharedTweet(config.retweets, page)
  3938. case 'RETWEETED_QUOTE_TWEET':
  3939. return selectedHomeTabIndex >= 2 ? (
  3940. config.listRetweets == 'hide'
  3941. ) : (
  3942. shouldHideSharedTweet(config.retweets, page) || shouldHideSharedTweet(config.quoteTweets, page)
  3943. )
  3944. case 'TWEET':
  3945. return page == separatedTweetsTimelineTitle
  3946. case 'UNAVAILABLE_QUOTE_TWEET':
  3947. return config.hideUnavailableQuoteTweets || shouldHideSharedTweet(config.quoteTweets, page)
  3948. case 'UNAVAILABLE_RETWEET':
  3949. return config.hideUnavailableQuoteTweets || selectedHomeTabIndex >= 2 ? config.listRetweets == 'hide' : shouldHideSharedTweet(config.retweets, page)
  3950. default:
  3951. return true
  3952. }
  3953. }
  3954.  
  3955. /**
  3956. * @param {import("./types").TimelineItemType} type
  3957. * @returns {boolean}
  3958. */
  3959. function shouldHideProfileTimelineItem(type) {
  3960. switch (type) {
  3961. case 'PINNED_TWEET':
  3962. case 'QUOTE_TWEET':
  3963. case 'TWEET':
  3964. return false
  3965. case 'RETWEET':
  3966. case 'RETWEETED_QUOTE_TWEET':
  3967. return config.hideProfileRetweets
  3968. case 'UNAVAILABLE_QUOTE_TWEET':
  3969. return config.hideUnavailableQuoteTweets
  3970. default:
  3971. return true
  3972. }
  3973. }
  3974.  
  3975. /**
  3976. * @param {import("./types").TimelineItemType} type
  3977. * @returns {boolean}
  3978. */
  3979. function shouldHideOtherTimelineItem(type) {
  3980. switch (type) {
  3981. case 'QUOTE_TWEET':
  3982. case 'RETWEET':
  3983. case 'RETWEETED_QUOTE_TWEET':
  3984. case 'TWEET':
  3985. case 'UNAVAILABLE':
  3986. case 'UNAVAILABLE_QUOTE_TWEET':
  3987. case 'UNAVAILABLE_RETWEET':
  3988. return false
  3989. default:
  3990. return true
  3991. }
  3992. }
  3993.  
  3994. /**
  3995. * @param {import("./types").SharedTweetsConfig} config
  3996. * @param {string} page
  3997. * @returns {boolean}
  3998. */
  3999. function shouldHideSharedTweet(config, page) {
  4000. switch (config) {
  4001. case 'hide': return true
  4002. case 'ignore': return page == separatedTweetsTimelineTitle
  4003. case 'separate': return page != separatedTweetsTimelineTitle
  4004. }
  4005. }
  4006.  
  4007. async function tweakBookmarksPage() {
  4008. if (config.twitterBlueChecks != 'ignore') {
  4009. observeTimeline(currentPage, {
  4010. classifyTweets: false,
  4011. })
  4012. }
  4013. }
  4014.  
  4015. async function tweakExplorePage() {
  4016. if (!config.hideExplorePageContents) return
  4017.  
  4018. let $searchInput = await getElement('input[data-testid="SearchBox_Search_Input"]', {
  4019. name: 'explore page search input',
  4020. stopIf: () => !isOnExplorePage(),
  4021. })
  4022. if (!$searchInput) return
  4023.  
  4024. log('focusing search input')
  4025. $searchInput.focus()
  4026.  
  4027. if (mobile) {
  4028. // The back button appears after the search input is focused on mobile. When
  4029. // you tap it or otherwise navigate back, it's replaced with the slide-out
  4030. // menu button and Explore page contents are shown - we want to skip that.
  4031. let $backButton = await getElement('div[data-testid="app-bar-back"]', {
  4032. name: 'back button',
  4033. stopIf: () => !isOnExplorePage(),
  4034. })
  4035. if (!$backButton) return
  4036.  
  4037. pageObservers.push(
  4038. observeElement($backButton.parentElement, (mutations) => {
  4039. mutations.forEach((mutation) => {
  4040. mutation.addedNodes.forEach((/** @type {HTMLElement} */ $el) => {
  4041. if ($el.querySelector('[data-testid="DashButton_ProfileIcon_Link"]')) {
  4042. log('slide-out menu button appeared, going back to skip Explore page')
  4043. history.go(-2)
  4044. }
  4045. })
  4046. })
  4047. }, 'back button parent')
  4048. )
  4049. }
  4050. }
  4051.  
  4052. function tweakCommunitiesPage() {
  4053. observeTimeline(currentPage)
  4054. }
  4055.  
  4056. function tweakCommunityPage() {
  4057. if (config.twitterBlueChecks != 'ignore') {
  4058. observeTimeline(currentPage, {
  4059. classifyTweets: false,
  4060. isTabbed: true,
  4061. tabbedTimelineContainerSelector: `${Selectors.PRIMARY_COLUMN} > div > div:last-child`,
  4062. onTimelineAppeared() {
  4063. // The About tab has static content at the top which can include a check
  4064. if (/\/about\/?$/.test(location.pathname)) {
  4065. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  4066. }
  4067. }
  4068. })
  4069. }
  4070. }
  4071.  
  4072. function tweakCommunityMembersPage() {
  4073. if (config.twitterBlueChecks != 'ignore') {
  4074. observeTimeline(currentPage, {
  4075. classifyTweets: false,
  4076. isTabbed: true,
  4077. timelineSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  4078. })
  4079. }
  4080. }
  4081.  
  4082. function tweakFollowListPage() {
  4083. if (config.twitterBlueChecks != 'ignore') {
  4084. observeTimeline(currentPage, {
  4085. classifyTweets: false,
  4086. })
  4087. }
  4088. }
  4089.  
  4090. function tweakIndividualTweetPage() {
  4091. observeTimeline(currentPage, {
  4092. hideHeadings: false,
  4093. onTimelineItemsChanged: onIndividualTweetTimelineChange
  4094. })
  4095. }
  4096.  
  4097. function tweakListPage() {
  4098. observeTimeline(currentPage, {
  4099. hideHeadings: false,
  4100. })
  4101. }
  4102.  
  4103. async function tweakDesktopLogo() {
  4104. let $logoPath = await getElement(`h1 ${Selectors.X_LOGO_PATH}`, {name: 'desktop nav logo', timeout: 5000})
  4105. if ($logoPath) {
  4106. twitterLogo($logoPath)
  4107. }
  4108. }
  4109.  
  4110. async function tweakTweetBox() {
  4111. // Observe username typeahead dropdowns to replace Blue checks
  4112. if (config.twitterBlueChecks != 'ignore') {
  4113. let $tweetTextarea = await getElement(`${desktop ? 'div[data-testid="primaryColumn"]': 'main'} label[data-testid^="tweetTextarea"]`, {
  4114. name: 'tweet textarea',
  4115. stopIf: pageIsNot(currentPage),
  4116. })
  4117. if (!$tweetTextarea) return
  4118.  
  4119. /** @type {HTMLElement} */
  4120. let $typeaheadDropdown
  4121.  
  4122. pageObservers.push(
  4123. observeElement($tweetTextarea.parentElement.parentElement.parentElement.parentElement, (mutations) => {
  4124. for (let mutation of mutations) {
  4125. if ($typeaheadDropdown && mutations.some(mutation => Array.from(mutation.removedNodes).includes($typeaheadDropdown))) {
  4126. disconnectPageObserver('tweet textarea typeahead dropdown')
  4127. $typeaheadDropdown = null
  4128. }
  4129. for (let $addedNode of mutation.addedNodes) {
  4130. if ($addedNode instanceof HTMLElement && $addedNode.getAttribute('id')?.startsWith('typeaheadDropdown')) {
  4131. $typeaheadDropdown = $addedNode
  4132. pageObservers.push(
  4133. observeElement($typeaheadDropdown, () => {
  4134. processBlueChecks($typeaheadDropdown)
  4135. }, 'tweet textarea typeahead dropdown')
  4136. )
  4137. }
  4138. }
  4139. }
  4140. }, 'tweet textarea typeahead dropdown container')
  4141. )
  4142. }
  4143.  
  4144. if (config.replaceLogo) {
  4145. tweakTweetButton()
  4146. }
  4147. }
  4148.  
  4149. async function tweakTweetButton() {
  4150. let $tweetButton = await getElement(`${desktop ? 'div[data-testid="primaryColumn"]': 'main'} div[data-testid^="tweetButton"]`, {
  4151. name: 'tweet button',
  4152. stopIf: pageIsNot(currentPage),
  4153. })
  4154. if ($tweetButton) {
  4155. let $text = $tweetButton.querySelector('span > span')
  4156. if ($text) {
  4157. setTweetButtonText($text)
  4158. } else {
  4159. warn('could not find tweet button text')
  4160. }
  4161. }
  4162. }
  4163.  
  4164. function tweakMainTimelinePage() {
  4165. if (desktop) {
  4166. tweakTweetBox()
  4167. }
  4168.  
  4169. let $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4170.  
  4171. // "Which version of the main timeline are we on?" hooks for styling
  4172. $body.classList.toggle('TabbedTimeline', $timelineTabs != null)
  4173. $body.classList.toggle('SeparatedTweets', isOnSeparatedTweetsTimeline())
  4174.  
  4175. if ($timelineTabs == null) {
  4176. warn('could not find timeline tabs')
  4177. return
  4178. }
  4179.  
  4180. tweakTimelineTabs($timelineTabs)
  4181. if (mobile && isSafari && config.replaceLogo) {
  4182. processTwitterLogos(document.querySelector(Selectors.MOBILE_TIMELINE_HEADER_NEW))
  4183. }
  4184.  
  4185. function updateSelectedHomeTabIndex() {
  4186. let $selectedHomeTabLink = $timelineTabs.querySelector('div[role="tablist"] a[aria-selected="true"]')
  4187. if ($selectedHomeTabLink) {
  4188. selectedHomeTabIndex = Array.from($selectedHomeTabLink.parentElement.parentElement.children).indexOf($selectedHomeTabLink.parentElement)
  4189. log({selectedHomeTabIndex})
  4190. } else {
  4191. warn('could not find selected Home tab link')
  4192. selectedHomeTabIndex = -1
  4193. }
  4194. }
  4195.  
  4196. updateSelectedHomeTabIndex()
  4197.  
  4198. // If there are pinned lists, the timeline tabs <nav> will be replaced when they load
  4199. pageObservers.push(
  4200. observeElement($timelineTabs.parentElement, (mutations) => {
  4201. let timelineTabsReplaced = mutations.some(mutation => Array.from(mutation.removedNodes).includes($timelineTabs))
  4202. if (timelineTabsReplaced) {
  4203. log('timeline tabs replaced')
  4204. $timelineTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4205. tweakTimelineTabs($timelineTabs)
  4206. }
  4207. }, 'timeline tabs nav container')
  4208. )
  4209.  
  4210. observeTimeline(currentPage, {
  4211. isTabbed: true,
  4212. onTabChanged: () => {
  4213. updateSelectedHomeTabIndex()
  4214. wasForYouTabSelected = selectedHomeTabIndex == 0
  4215. },
  4216. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child > div',
  4217. })
  4218. }
  4219.  
  4220. function tweakMobileComposeTweetPage() {
  4221. tweakTweetBox()
  4222. }
  4223.  
  4224. function tweakMobileMediaViewerPage() {
  4225. if (config.twitterBlueChecks == 'ignore') return
  4226.  
  4227. let $timeline = /** @type {HTMLElement} */ (document.querySelector('[data-testid="vss-scroll-view"] > div'))
  4228. if (!$timeline) {
  4229. warn('media viewer timeline not found')
  4230. return
  4231. }
  4232.  
  4233. observeElement($timeline, (mutations) => {
  4234. for (let mutation of mutations) {
  4235. if (!mutation.addedNodes) continue
  4236. for (let $addedNode of mutation.addedNodes) {
  4237. if ($addedNode.querySelector?.('div[data-testid^="immersive-tweet-ui-content-container"]')) {
  4238. processBlueChecks($addedNode)
  4239. }
  4240. }
  4241. }
  4242. }, 'media viewer timeline', {childList: true, subtree: true})
  4243. }
  4244.  
  4245. async function tweakTimelineTabs($timelineTabs) {
  4246. let $followingTabLink = /** @type {HTMLElement} */ ($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a'))
  4247.  
  4248. if (config.alwaysUseLatestTweets && !document.title.startsWith(separatedTweetsTimelineTitle)) {
  4249. let isForYouTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:first-child > a[aria-selected="true"]'))
  4250. if (isForYouTabSelected && (!wasForYouTabSelected || config.hideForYouTimeline)) {
  4251. log('switching to Following timeline')
  4252. $followingTabLink.click()
  4253. wasForYouTabSelected = false
  4254. } else {
  4255. wasForYouTabSelected = isForYouTabSelected
  4256. }
  4257. }
  4258.  
  4259. if (shouldShowSeparatedTweetsTab()) {
  4260. let $newTab = /** @type {HTMLElement} */ ($timelineTabs.querySelector('#tnt_separated_tweets_tab'))
  4261. if ($newTab) {
  4262. log('separated tweets timeline tab already present')
  4263. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  4264. }
  4265. else {
  4266. log('inserting separated tweets tab')
  4267. $newTab = /** @type {HTMLElement} */ ($followingTabLink.parentElement.cloneNode(true))
  4268. $newTab.id = 'tnt_separated_tweets_tab'
  4269. $newTab.querySelector('span').textContent = separatedTweetsTimelineTitle
  4270. let $link = $newTab.querySelector('a')
  4271. $link.removeAttribute('aria-selected')
  4272.  
  4273. // This script assumes navigation has occurred when the document title
  4274. // changes, so by changing the title we fake navigation to a non-existent
  4275. // page representing the separated tweets timeline.
  4276. $link.addEventListener('click', (e) => {
  4277. e.preventDefault()
  4278. e.stopPropagation()
  4279. if (!document.title.startsWith(separatedTweetsTimelineTitle)) {
  4280. // The separated tweets tab belongs to the Following tab
  4281. let isFollowingTabSelected = Boolean($timelineTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  4282. if (!isFollowingTabSelected) {
  4283. log('switching to the Following tab for separated tweets')
  4284. $followingTabLink.click()
  4285. }
  4286. setTitle(separatedTweetsTimelineTitle)
  4287. }
  4288. window.scrollTo({top: 0})
  4289. })
  4290. $followingTabLink.parentElement.insertAdjacentElement('afterend', $newTab)
  4291.  
  4292. // Return to the main timeline view when any other tab is clicked
  4293. $followingTabLink.parentElement.parentElement.addEventListener('click', () => {
  4294. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  4295. log('setting title to Home')
  4296. homeNavigationIsBeingUsed = true
  4297. setTitle(getString('HOME'))
  4298. }
  4299. })
  4300.  
  4301. // Return to the main timeline when the Home nav link is clicked
  4302. let $homeNavLink = await getElement(Selectors.NAV_HOME_LINK, {
  4303. name: 'home nav link',
  4304. stopIf: pathIsNot(currentPath),
  4305. })
  4306. if ($homeNavLink && !$homeNavLink.dataset.tweakNewTwitterListener) {
  4307. $homeNavLink.addEventListener('click', () => {
  4308. homeNavigationIsBeingUsed = true
  4309. if (location.pathname == '/home' && !document.title.startsWith(getString('HOME'))) {
  4310. setTitle(getString('HOME'))
  4311. }
  4312. })
  4313. $homeNavLink.dataset.tweakNewTwitterListener = 'true'
  4314. }
  4315. }
  4316. } else {
  4317. removeMobileTimelineHeaderElements()
  4318. }
  4319. }
  4320.  
  4321. function tweakMobileUserListPage() {
  4322. if (config.twitterBlueChecks == 'ignore') return
  4323.  
  4324. observeUserListTimeline(undefined, currentPath)
  4325. }
  4326.  
  4327. function tweakNotificationsPage() {
  4328. let $navigationTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4329. if ($navigationTabs == null) {
  4330. warn('could not find Notifications tabs')
  4331. return
  4332. }
  4333.  
  4334. if (config.hideVerifiedNotificationsTab) {
  4335. let isVerifiedTabSelected = Boolean($navigationTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a[aria-selected="true"]'))
  4336. if (isVerifiedTabSelected) {
  4337. log('switching to All tab')
  4338. $navigationTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a')?.click()
  4339. }
  4340. }
  4341.  
  4342. if (config.twitterBlueChecks != 'ignore') {
  4343. observeTimeline(currentPage, {
  4344. classifyTweets: false,
  4345. isTabbed: true,
  4346. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  4347. })
  4348. }
  4349. }
  4350.  
  4351. function tweakProfilePage() {
  4352. if (config.twitterBlueChecks != 'ignore') {
  4353. if (mobile) {
  4354. processBlueChecks(document.querySelector(Selectors.MOBILE_TIMELINE_HEADER_NEW))
  4355. }
  4356. processBlueChecks(document.querySelector(Selectors.PRIMARY_COLUMN))
  4357. }
  4358. observeTimeline(currentPage)
  4359. if (desktop && config.hideSidebarContent) {
  4360. observeProfileBlockedStatus(currentPage)
  4361. observeProfileSidebar(currentPage)
  4362. }
  4363. }
  4364.  
  4365. function tweakQuoteTweetsPage() {
  4366. if (config.twitterBlueChecks != 'ignore') {
  4367. observeTimeline(currentPage)
  4368. }
  4369. }
  4370.  
  4371. function tweakSearchPage() {
  4372. let $searchTabs = document.querySelector(`${mobile ? Selectors.MOBILE_TIMELINE_HEADER_NEW : Selectors.PRIMARY_COLUMN} nav`)
  4373. if ($searchTabs != null) {
  4374. if (config.defaultToLatestSearch) {
  4375. let isTopTabSelected = Boolean($searchTabs.querySelector('div[role="tablist"] > div:nth-child(1) > a[aria-selected="true"]'))
  4376. if (isTopTabSelected) {
  4377. log('switching to Latest tab')
  4378. $searchTabs.querySelector('div[role="tablist"] > div:nth-child(2) > a')?.click()
  4379. }
  4380. }
  4381. } else {
  4382. warn('could not find Search tabs')
  4383. }
  4384.  
  4385. observeTimeline(currentPage, {
  4386. hideHeadings: false,
  4387. isTabbed: true,
  4388. tabbedTimelineContainerSelector: 'div[data-testid="primaryColumn"] > div > div:last-child',
  4389. })
  4390. }
  4391. //#endregion
  4392.  
  4393. //#region Main
  4394. async function main() {
  4395. let $settings = /** @type {HTMLScriptElement} */ (document.querySelector('script#tnt_settings'))
  4396. if ($settings) {
  4397. try {
  4398. Object.assign(config, JSON.parse($settings.innerText))
  4399. } catch(e) {
  4400. error('error parsing initial settings', e)
  4401. }
  4402.  
  4403. let settingsChangeObserver = new MutationObserver(() => {
  4404. /** @type {Partial<import("./types").Config>} */
  4405. let configChanges
  4406. try {
  4407. configChanges = JSON.parse($settings.innerText)
  4408. } catch(e) {
  4409. error('error parsing incoming settings change', e)
  4410. return
  4411. }
  4412.  
  4413. if ('debug' in configChanges) {
  4414. log('disabling debug mode')
  4415. debug = configChanges.debug
  4416. log('enabled debug mode')
  4417. configureThemeCss()
  4418. return
  4419. }
  4420.  
  4421. Object.assign(config, configChanges)
  4422. configChanged(configChanges)
  4423. })
  4424. settingsChangeObserver.observe($settings, {childList: true})
  4425. }
  4426.  
  4427. if (config.debug) {
  4428. debug = true
  4429. }
  4430.  
  4431. observeTitle()
  4432.  
  4433. let $loadingStyle
  4434. if (config.replaceLogo) {
  4435. getElement('html', {name: 'html element'}).then(($html) => {
  4436. $loadingStyle = document.createElement('style')
  4437. $loadingStyle.dataset.insertedBy = 'control-panel-for-twitter'
  4438. $loadingStyle.dataset.role = 'loading-logo'
  4439. let logoThemeColor = themeColor || Array.from(THEME_COLORS)[0]
  4440. $loadingStyle.textContent = dedent(`
  4441. ${Selectors.X_LOGO_PATH} {
  4442. fill: ${isSafari ? 'transparent' : logoThemeColor};
  4443. d: path("${Svgs.TWITTER_LOGO_PATH}");
  4444. }
  4445. .tnt_logo {
  4446. fill: ${logoThemeColor};
  4447. }
  4448. `)
  4449. $html.appendChild($loadingStyle)
  4450. })
  4451.  
  4452. if (isSafari) {
  4453. getElement(Selectors.X_LOGO_PATH, {name: 'pre-loading indicator logo', timeout: 1000}).then(($logoPath) => {
  4454. if ($logoPath) {
  4455. twitterLogo($logoPath)
  4456. }
  4457. })
  4458. }
  4459.  
  4460. observeFavicon()
  4461. }
  4462.  
  4463. let $appWrapper = await getElement('#layers + div', {name: 'app wrapper'})
  4464.  
  4465. $html = document.querySelector('html')
  4466. $body = document.body
  4467. $reactRoot = document.querySelector('#react-root')
  4468. lang = $html.lang
  4469. dir = $html.dir
  4470. ltr = dir == 'ltr'
  4471. let lastFlexDirection
  4472.  
  4473. observeElement($appWrapper, () => {
  4474. let flexDirection = getComputedStyle($appWrapper).flexDirection
  4475.  
  4476. mobile = flexDirection == 'column'
  4477. desktop = !mobile
  4478.  
  4479. /** @type {'mobile' | 'desktop'} */
  4480. let version = mobile ? 'mobile' : 'desktop'
  4481.  
  4482. if (version != config.version) {
  4483. log('setting version to', version)
  4484. config.version = version
  4485. // Let the options page know which version is being used
  4486. storeConfigChanges({version})
  4487. }
  4488.  
  4489. if (lastFlexDirection == null) {
  4490. log('initial config', {config, lang, version})
  4491.  
  4492. // One-time setup
  4493. checkReactNativeStylesheet()
  4494. observeBodyBackgroundColor()
  4495. observeColor()
  4496.  
  4497. // Repeatable configuration setup
  4498. configureSeparatedTweetsTimelineTitle()
  4499. configureCss()
  4500. configureThemeCss()
  4501. observeHtmlFontSize()
  4502. observePopups()
  4503. observeSideNavTweetButton()
  4504.  
  4505. // Start taking action on page changes
  4506. observingPageChanges = true
  4507.  
  4508. // Delay removing loading icon styles to avoid Flash of X
  4509. if ($loadingStyle) {
  4510. setTimeout(() => $loadingStyle.remove(), 1000)
  4511. }
  4512. }
  4513. else if (flexDirection != lastFlexDirection) {
  4514. observeHtmlFontSize()
  4515. configChanged({version})
  4516. }
  4517.  
  4518. $body.classList.toggle('Mobile', mobile)
  4519. $body.classList.toggle('Desktop', desktop)
  4520.  
  4521. lastFlexDirection = flexDirection
  4522. }, 'app wrapper class attribute for version changes (mobile ↔ desktop)', {
  4523. attributes: true,
  4524. attributeFilter: ['class']
  4525. })
  4526. }
  4527.  
  4528. /**
  4529. * @param {Partial<import("./types").Config>} changes
  4530. */
  4531. function configChanged(changes) {
  4532. log('config changed', changes)
  4533.  
  4534. configureCss()
  4535. configureFont()
  4536. configureNavFontSizeCss()
  4537. configureThemeCss()
  4538. observeFavicon()
  4539. observePopups()
  4540. observeSideNavTweetButton()
  4541.  
  4542. // Only re-process the current page if navigation wasn't already triggered
  4543. // while applying the following config changes (if there were any).
  4544. let navigationTriggered = (
  4545. configureSeparatedTweetsTimelineTitle() ||
  4546. checkforDisabledHomeTimeline()
  4547. )
  4548. if (!navigationTriggered) {
  4549. processCurrentPage()
  4550. }
  4551. }
  4552.  
  4553. main()
  4554. //#endregion
  4555.  
  4556. }()