Tweak New Twitter

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

目前為 2021-08-19 提交的版本,檢視 最新版本

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