Tabview Youtube

把Youtube Videos中的评论及视频列表制作成Tabs

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

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright (c) 2021-2023 cyfung1031
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name Tabview Youtube
  28. // @name:en Tabview Youtube
  29. // @description Make comments and lists into tabs for YouTube Videos
  30. // @description:en Make comments and lists into tabs for YouTube Videos
  31. // @name:ja Tabview Youtube
  32. // @description:ja YouTube動画のコメントやリストなどをタブに作成します
  33. // @name:ko Tabview Youtube
  34. // @description:ko YouTube 동영상의 댓글 및 목록을 탭으로 만듭니다
  35. // @name:zh-TW Tabview Youtube
  36. // @name:zh-HK Tabview Youtube
  37. // @name:zh-CN Tabview Youtube
  38. // @description:zh-TW 把Youtube Videos中的評論及影片清單製作成Tabs
  39. // @description:zh-HK 把Youtube Videos中的評論及影片清單製作成Tabs
  40. // @description:zh-CN 把Youtube Videos中的评论及视频列表制作成Tabs
  41. // @name:ru Tabview Youtube
  42. // @description:ru Сделайте описание, комментарии и список видео в виде вкладок для видео на YouTube
  43.  
  44. // @name:af Tabview Youtube
  45. // @name:az Tabview Youtube
  46. // @name:id Tabview Youtube
  47. // @name:ms Tabview Youtube
  48. // @name:bs Tabview Youtube
  49. // @name:ca Tabview Youtube
  50. // @name:cs Tabview Youtube
  51. // @name:da Tabview Youtube
  52. // @name:de Tabview Youtube
  53. // @name:et Tabview Youtube
  54. // @name:es Tabview Youtube
  55. // @name:eu Tabview Youtube
  56. // @name:fr Tabview Youtube
  57. // @name:gl Tabview Youtube
  58. // @name:hr Tabview Youtube
  59. // @name:zu Tabview Youtube
  60. // @name:is Tabview Youtube
  61. // @name:it Tabview Youtube
  62. // @name:sw Tabview Youtube
  63. // @name:lv Tabview Youtube
  64. // @name:lt Tabview Youtube
  65. // @name:hu Tabview Youtube
  66. // @name:nl Tabview Youtube
  67. // @name:uz Tabview Youtube
  68. // @name:pl Tabview Youtube
  69. // @name:pt Tabview Youtube
  70. // @name:pt-BR Tabview Youtube
  71. // @name:ro Tabview Youtube
  72. // @name:sq Tabview Youtube
  73. // @name:sk Tabview Youtube
  74. // @name:sl Tabview Youtube
  75. // @name:sr Tabview Youtube
  76. // @name:fi Tabview Youtube
  77. // @name:sv Tabview Youtube
  78. // @name:vi Tabview Youtube
  79. // @name:tr Tabview Youtube
  80. // @name:be Tabview Youtube
  81. // @name:bg Tabview Youtube
  82. // @name:ky Tabview Youtube
  83. // @name:kk Tabview Youtube
  84. // @name:mk Tabview Youtube
  85. // @name:mn Tabview Youtube
  86. // @name:uk Tabview Youtube
  87. // @name:el Tabview Youtube
  88. // @name:hy Tabview Youtube
  89. // @name:ur Tabview Youtube
  90. // @name:ar Tabview Youtube
  91. // @name:fa Tabview Youtube
  92. // @name:ne Tabview Youtube
  93. // @name:mr Tabview Youtube
  94. // @name:hi Tabview Youtube
  95. // @name:as Tabview Youtube
  96. // @name:bn Tabview Youtube
  97. // @name:pa Tabview Youtube
  98. // @name:gu Tabview Youtube
  99. // @name:or Tabview Youtube
  100. // @name:ta Tabview Youtube
  101. // @name:te Tabview Youtube
  102. // @name:kn Tabview Youtube
  103. // @name:ml Tabview Youtube
  104. // @name:si Tabview Youtube
  105. // @name:th Tabview Youtube
  106. // @name:lo Tabview Youtube
  107. // @name:my Tabview Youtube
  108. // @name:ka Tabview Youtube
  109. // @name:am Tabview Youtube
  110. // @name:km Tabview Youtube
  111.  
  112.  
  113. // @description:af Maak kommentaar en lyste as oortjies vir YouTube-video's
  114. // @description:az YouTube Videoları üçün şərhləri və siyahıları tablara çevirin
  115. // @description:id Ubah komentar dan daftar menjadi tab untuk Video YouTube
  116. // @description:ms Ubah komen dan senarai menjadi tab untuk Video YouTube
  117. // @description:bs Pretvorite komentare i liste u kartice za YouTube videozapise
  118. // @description:ca Converteix comentaris i llistes en pestanyes per a Vídeos de YouTube
  119. // @description:cs Převeďte komentáře a seznamy na karty pro YouTube videa
  120. // @description:da Lav kommentarer og lister til faner for YouTube-videoer
  121. // @description:de Machen Sie Kommentare und Listen zu Tabs für YouTube-Videos
  122. // @description:et Muutke kommentaarid ja loendid YouTube'i videote jaoks kaartideks
  123. // @description:es Convierte los comentarios y listas en pestañas para los Videos de YouTube
  124. // @description:eu Egin iruzkinak eta zerrendak YouTube Bideoetarako fitxetan
  125. // @description:fr Transformez les commentaires et les listes en onglets pour les vidéos YouTube
  126. // @description:gl Converte comentarios e listas en lapelas para Vídeos de YouTube
  127. // @description:hr Pretvorite komentare i popise u kartice za YouTube videe
  128. // @description:zu Yenza ukubhala phansi kanye nemingcele ukuba yiithebhu kuVidiyo ze-YouTube
  129. // @description:is Breyttu athugasemdum og listum í flipa fyrir YouTube myndbönd
  130. // @description:it Trasforma commenti e liste in schede per i Video di YouTube
  131. // @description:sw Geuza maoni na orodha kuwa vichupo kwa Video za YouTube
  132. // @description:lv Pārveidojiet komentārus un sarakstus cilnēs YouTube video
  133. // @description:lt Paverčia komentarus ir sąrašus skirtukais YouTube vaizdo įrašams
  134. // @description:hu Alakítsa át a megjegyzéseket és listákat fülekké a YouTube videókhoz
  135. // @description:nl Maak van reacties en lijsten tabs voor YouTube-video's
  136. // @description:uz YouTube videolar uchun sharhlar va ro'yxatlarni ichki oynalar qiling
  137. // @description:pl Przekształć komentarze i listy w karty dla filmów na YouTube
  138. // @description:pt Transforme comentários e listas em abas para Vídeos do YouTube
  139. // @description:pt-BR Transforme comentários e listas em abas para Vídeos do YouTube
  140. // @description:ro Transformă comentariile și listele în file pentru Videoclipuri YouTube
  141. // @description:sq Kthe komentet dhe listat në skeda për Videot në YouTube
  142. // @description:sk Premente komentáre a zoznamy na karty pre YouTube videá
  143. // @description:sl Pretvori komentarje in sezname v zavihke za YouTube videe
  144. // @description:sr Pretvorite komentare i liste u kartice za YouTube videe
  145. // @description:fi Muuta kommentit ja luettelot välilehdiksi YouTube-videoille
  146. // @description:sv Gör kommentarer och listor till flikar för YouTube-videor
  147. // @description:vi Chuyển đổi bình luận và danh sách thành tab cho Video YouTube
  148. // @description:tr Yorumları ve listeleri YouTube Videoları için sekmelere dönüştürün
  149. // @description:be Пераўтварыце каментарыі і спісы ў закладкі для відэа на YouTube
  150. // @description:bg Превърнете коментарите и списъците в раздели за видеоклипове в YouTube
  151. // @description:ky YouTube видеолору үчүн эскертүүлөрдү жана тизмелерди табдыктарга айлантырыңыз
  152. // @description:kk Пікірлер мен тізімдерді YouTube видеолары үшін қоймақтарға айналдырыңыз
  153. // @description:mk Претворете ги коментарите и листите во јазичиња за Видеа на YouTube
  154. // @description:mn YouTube видео дэх сэтгэгдлүүд болон жагсаалтыг табчууд болгоно уу
  155. // @description:uk Зробіть коментарі та списки у вкладки для відео на YouTube
  156. // @description:el Μετατρέψτε τα σχόλια και τις λίστες σε καρτέλες για τα βίντεο του YouTube
  157. // @description:hy Վերածեք մեկնաբանությունները և ցուցակները YouTube տեսանյութերի ներդիրների
  158. // @description:ur YouTube ویڈیوز کے لئے تبصرے اور فہرستوں کو ٹیب میں تبدیل کریں
  159. // @description:ar قم بتحويل التعليقات والقوائم إلى علامات تبويب لفيديوهات YouTube
  160. // @description:fa نظرات و فهرست ها را به زبانه ها برای ویدیوهای YouTube تبدیل کنید
  161. // @description:ne YouTube भिडियोहरूका लागि प्रतिक्रिया र सूचीहरूलाई ट्याबहरूमा परिवर्तन गर्नुहोस्
  162. // @description:mr YouTube व्हिडिओसाठी टिप्पण्या आणि यादीतबांमध्ये करा
  163. // @description:hi YouTube वीडियो के लिए टिप्पणियाँ और सूचियों को टैब में बदलें
  164. // @description:as YouTube ভিডিঅ'ৰ বাবে মন্তব্য আৰু তালিকাসমূহ টেবলত পৰিণত কৰক
  165. // @description:bn YouTube ভিডিওর জন্য মন্তব্য এবং তালিকা ট্যাবে পরিণত করুন
  166. // @description:pa ਯੂਟਿਊਬ ਵੀਡੀਓਜ਼ ਲਈ ਟਿੱਪਣੀਆਂ ਅਤੇ ਸੂਚੀਆਂ ਨੂੰ ਟੈਬਾਂ ਵਿੱਚ ਬਦਲੋ
  167. // @description:gu YouTube વિડિઓ માટે ટિપ્પણીઓ અને યાદીઓ ટૅબમાં બદલો
  168. // @description:or YouTube ଭିଡିଓ ପାଇଁ ମନ୍ତବ୍ୟ ଏବଂ ତାଲିକାଗୁଡ଼ିକ ଟ୍ୟାବମାନେ ପରିବର୍ତ୍ତନ କରନ୍ତୁ
  169. // @description:ta YouTube வீடியோக்கான கருத்துக்கள் மற்றும் பட்டியல்களை தாவல்களாக மாற்றவும்
  170. // @description:te YouTube వీడియోల కోసం వ్యాఖ్యలు మరియు జాబితాలను ట్యాబ్లలుగా మార్చండి
  171. // @description:kn YouTube ವೀಡಿಯೊಗಳಿಗಾಗಿ ಟಿಪ್ಪಣಿಗಳನ್ನು ಮತ್ತು ಪಟ್ಟಿಗಳನ್ನು ಟ್ಯಾಬ್‌ಗಳಾಗಿ ಮಾಡಿ
  172. // @description:ml YouTube വീഡിയോകൾക്കായി അഭിപ്രായങ്ങളും പട്ടികകളും ടാബുകളായി മാറ്റുക
  173. // @description:si YouTube වීඩියෝ සඳහා අදහස් සහ ලැයිස්තු ටැබ් කරන්න
  174. // @description:th ทำให้ความคิดเห็นและรายการเป็นแท็บสำหรับวิดีโอ YouTube
  175. // @description:lo ປ່ຽນຄວາມເຫັນຂອງຄົນເບິ່ງແລະລາຍການເປັນແຖບສໍາລັບວິດີໂອ YouTube
  176. // @description:my YouTube ဗီဒီယိုများအတွက် မှတ်ချက်များနှင့် စာရင်းများကို Tabs အဖြစ် ပြောင်းပါ
  177. // @description:ka გადაიყვანეთ კომენტარები და სიები ჩანართებში YouTube ვიდეოებისთვის
  178. // @description:am አስተያየቶችን እና ዝርዝሮችን YouTube ቪዲዮዎች ለትርጓሜዎች ውስጥ ያስተካክሉ
  179. // @description:km បង្កើតមតិយោបល់និងបញ្ជីទៅជាផ្ទាំងសម្រាប់វីដេអូ YouTube
  180.  
  181. // @version 4.11.2
  182. // @resource contentCSS https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/4114a146bd75d4e5c1819383df56811f148a0953/css/style_content.css
  183. // @resource injectionJS1 https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/4114a146bd75d4e5c1819383df56811f148a0953/js/injection_script_1.js
  184. // @require https://greasyfork.org/scripts/465421-vanilla-js-dialog/code/Vanilla%20JS%20Dialog.js?version=1188332
  185.  
  186. // @namespace http://tampermonkey.net/
  187. // @author CY Fung
  188. // @license MIT
  189. // @supportURL https://github.com/cyfung1031/Tabview-Youtube
  190. // @run-at document-start
  191. // @match https://www.youtube.com/*
  192. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  193. // @icon https://github.com/cyfung1031/Tabview-Youtube/raw/main/images/icon128p.png
  194.  
  195. // @compatible edge Edge [Blink] >= 79; Tampermonkey (Beta) / Violetmonkey
  196. // @compatible chrome Chrome >= 54; Tampermonkey (Beta) / Violetmonkey
  197. // @compatible firefox FireFox / Waterfox (Classic) >= 55; Tampermonkey / Violetmonkey
  198. // @compatible opera Opera >= 41; Tampermonkey (Beta) / Violetmonkey
  199. // @compatible safari Safari >= 12.1
  200.  
  201. // @grant GM_getResourceText
  202. // @grant GM_registerMenuCommand
  203. // @noframes
  204. // ==/UserScript==
  205.  
  206. /* jshint esversion:8 */
  207.  
  208. function main(){
  209. 'use strict';
  210. // MIT License
  211. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  212.  
  213. -(function mainBody() {
  214. 'use strict';
  215.  
  216. function inIframe() {
  217. try {
  218. return window.self !== window.top;
  219. } catch (e) {
  220. return true;
  221. }
  222. }
  223.  
  224. if (inIframe()) return;
  225.  
  226. if(document.documentElement && document.documentElement.hasAttribute('plugin-tabview-youtube')){
  227. console.warn('Multiple instances of Tabview Youtube is attached. [0x7F01]')
  228. return;
  229. }
  230.  
  231. //if (!$) return;
  232.  
  233. /**
  234. * SVG resources:
  235. * <div>Icons made by <a href="https://www.flaticon.com/authors/smashicons" title="Smashicons">Smashicons</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></div>
  236. */
  237.  
  238. const scriptVersionForExternal = '2022/12/04';
  239.  
  240. const isMyScriptInChromeRuntime = () => typeof GM === 'undefined' && typeof ((((window || 0).chrome || 0).runtime || 0).getURL) === 'function';
  241. const isGMAvailable = () => typeof GM !== 'undefined' && !isMyScriptInChromeRuntime();
  242.  
  243. // https://yqnn.github.io/svg-path-editor/
  244. // https://vecta.io/nano
  245.  
  246. const svgComments = `<path d="M80 27H12A12 12 90 0 0 0 39v42a12 12 90 0 0 12 12h12v20a2 2 90 0 0 3.4 2L47 93h33a12
  247. 12 90 0 0 12-12V39a12 12 90 0 0-12-12zM20 47h26a2 2 90 1 1 0 4H20a2 2 90 1 1 0-4zm52 28H20a2 2 90 1 1 0-4h52a2 2 90
  248. 1 1 0 4zm0-12H20a2 2 90 1 1 0-4h52a2 2 90 1 1 0 4zm36-58H40a12 12 90 0 0-12 12v6h52c9 0 16 7 16 16v42h0v4l7 7a2 2 90
  249. 0 0 3-1V71h2a12 12 90 0 0 12-12V17a12 12 90 0 0-12-12z"/>`.trim();
  250.  
  251. const svgVideos = `<path d="M89 10c0-4-3-7-7-7H7c-4 0-7 3-7 7v70c0 4 3 7 7 7h75c4 0 7-3 7-7V10zm-62 2h13v10H27V12zm-9
  252. 66H9V68h9v10zm0-56H9V12h9v10zm22 56H27V68h13v10zm-3-25V36c0-2 2-3 4-2l12 8c2 1 2 4 0 5l-12 8c-2 1-4 0-4-2zm25
  253. 25H49V68h13v10zm0-56H49V12h13v10zm18 56h-9V68h9v10zm0-56h-9V12h9v10z"/>`.trim();
  254.  
  255. const svgInfo = `<path d="M30 0C13.3 0 0 13.3 0 30s13.3 30 30 30 30-13.3 30-30S46.7 0 30 0zm6.2 46.6c-1.5.5-2.6
  256. 1-3.6 1.3a10.9 10.9 0 0 1-3.3.5c-1.7 0-3.3-.5-4.3-1.4a4.68 4.68 0 0 1-1.6-3.6c0-.4.2-1 .2-1.5a20.9 20.9 90 0 1
  257. .3-2l2-6.8c.1-.7.3-1.3.4-1.9a8.2 8.2 90 0 0 .3-1.6c0-.8-.3-1.4-.7-1.8s-1-.5-2-.5a4.53 4.53 0 0 0-1.6.3c-.5.2-1
  258. .2-1.3.4l.6-2.1c1.2-.5 2.4-1 3.5-1.3s2.3-.6 3.3-.6c1.9 0 3.3.6 4.3 1.3s1.5 2.1 1.5 3.5c0 .3 0 .9-.1 1.6a10.4 10.4
  259. 90 0 1-.4 2.2l-1.9 6.7c-.2.5-.2 1.1-.4 1.8s-.2 1.3-.2 1.6c0 .9.2 1.6.6 1.9s1.1.5 2.1.5a6.1 6.1 90 0 0 1.5-.3 9 9 90
  260. 0 0 1.4-.4l-.6 2.2zm-3.8-35.2a1 1 0 010 8.6 1 1 0 010-8.6z"/>`.trim();
  261.  
  262. const svgPlayList = `<path d="M0 3h12v2H0zm0 4h12v2H0zm0 4h8v2H0zm16 0V7h-2v4h-4v2h4v4h2v-4h4v-2z"/>`.trim();
  263.  
  264. const svgDiag1 = `<svg stroke="currentColor" fill="none"><path d="M8 2h2v2M7 5l3-3m-6 8H2V8m0 2l3-3"/></svg>`;
  265. const svgDiag2 = `<svg stroke="currentColor" fill="none"><path d="M7 3v2h2M7 5l3-3M5 9V7H3m-1 3l3-3"/></svg>`;
  266.  
  267. const REMOVE_DUPLICATE_INFO = true;
  268. const REMOVE_DUPLICATE_META_RECOMMENDATION = true; /* https://www.youtube.com/watch?v=kGihxscQCPE */
  269. const MINIVIEW_BROWSER_ENABLE = true;
  270. const DEBUG_LOG = false;
  271. const REPLACE_PIN_ICON = true; /* Some browsers still using the old yt-icon for pin */
  272.  
  273. let _isPageFirstLoaded = true
  274.  
  275. async function makeTytLock() {
  276. let c = 8;
  277. while (!document.documentElement) {
  278. if(--c === 0) return
  279. await new Promise(window.requestAnimationFrame)
  280. }
  281. if (_isPageFirstLoaded) document.documentElement.setAttribute('tyt-lock', '')
  282. }
  283. if (location.pathname === '/watch') makeTytLock()
  284. /*
  285.  
  286. youtube page
  287.  
  288. = Init::browse
  289. yt-page-data-fetched
  290. data-changed...
  291. yt-page-data-updated
  292. yt-navigate-finish
  293. data-changed...
  294. yt-watch-comments-ready
  295. = browse -> watch
  296. yt-player-updated
  297. yt-navigate
  298. yt-navigate-start
  299. yt-page-type-changed
  300. yt-player-updated
  301. yt-page-data-fetched
  302. yt-navigate-finish
  303. data-changed...
  304. yt-page-data-updated
  305. data-changed...
  306. yt-watch-comments-ready
  307. data-changed...
  308.  
  309. = watch -> watch
  310. = click video on meta panel // https://www.youtube.com/watch?v=UY5bp5CNhak; https://www.youtube.com/watch?v=m0WtnU8NVTo
  311. yt-navigate
  312. yt-navigate-start
  313. data-changed
  314. yt-player-updated
  315. yt-page-data-fetched
  316. yt-navigate-finish
  317. data-changed...
  318. yt-page-data-updated
  319. data-changed...
  320. yt-watch-comments-ready
  321. data-changed...
  322.  
  323. = watch -> browse (miniview)
  324. yt-navigate-cache
  325. yt-page-data-fetched
  326. yt-page-type-changed
  327. yt-page-data-updated
  328. yt-navigate-finish
  329.  
  330. = browse (miniview) -> watch (Restore)
  331. yt-navigate-cache
  332. yt-page-data-fetched
  333. yt-navigate-finish
  334. yt-page-type-changed
  335. yt-page-data-updated
  336. data-changed...
  337. yt-watch-comments-ready
  338.  
  339. = watch -> search (miniview)
  340. yt-navigate
  341. yt-navigate-start
  342. data-changed
  343. yt-page-data-fetched
  344. yt-page-type-changed
  345. data-changed
  346. yt-page-data-updated
  347. yt-navigate-finish
  348. data-changed...
  349.  
  350. = Init::search
  351. yt-page-data-fetched
  352. data-changed
  353. yt-page-data-updated
  354. yt-navigate-finish
  355. data-changed...
  356. yt-watch-comments-ready
  357.  
  358. = Init::watch
  359. yt-page-data-fetched
  360. yt-navigate-finish
  361. data-changed...
  362. yt-page-data-updated
  363. data-changed...
  364. yt-watch-comments-ready
  365. yt-player-updated
  366. data-changed...
  367.  
  368. = watch -> watch (history back)
  369. yt-player-updated
  370. yt-page-data-fetched
  371. yt-navigate-finish
  372. data-changed...
  373. yt-page-data-updated
  374. data-changed...
  375. yt-watch-comments-ready
  376.  
  377. = watch -> click video time // https://www.youtube.com/watch?v=UY5bp5CNhak; https://www.youtube.com/watch?v=m0WtnU8NVTo
  378. yt-navigate
  379.  
  380. */
  381.  
  382.  
  383.  
  384. const LAYOUT_VAILD = 1;
  385.  
  386. const LAYOUT_TWO_COLUMNS = 2;
  387. const LAYOUT_THEATER = 4;
  388. const LAYOUT_FULLSCREEN = 8;
  389. const LAYOUT_CHATROOM = 16;
  390. const LAYOUT_CHATROOM_COLLAPSED = 32;
  391. const LAYOUT_TAB_EXPANDED = 64;
  392. const LAYOUT_ENGAGEMENT_PANEL_EXPANDED = 128;
  393. const LAYOUT_CHATROOM_EXPANDED = 256;
  394. const LAYOUT_DONATION_SHELF_EXPANDED = 512;
  395.  
  396. const nonCryptoRandStr_base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  397.  
  398. const nullFunc = function () { };
  399.  
  400.  
  401. const iframeCSS = (() => {
  402. return `
  403. body {
  404. --tabview-msg-cursor: default;
  405. --tabview-msg-pointer-events: none;
  406. --tabview-img-pointer-events: auto;
  407. }
  408. body.tabview-allow-pointer-events {
  409. --tabview-msg-cursor: '-NULL-';
  410. --tabview-msg-pointer-events: '-NULL-';
  411. --tabview-img-pointer-events: '-NULL-';
  412. }
  413. body #input-panel.yt-live-chat-renderer::after {
  414. background: transparent;
  415. }
  416. .style-scope.yt-live-chat-item-list-renderer {
  417. box-sizing: border-box;
  418. }
  419. yt-live-chat-text-message-renderer:nth-last-child(-n+30):hover #menu.yt-live-chat-text-message-renderer {
  420. transition-delay: 87ms;
  421. }
  422. yt-live-chat-text-message-renderer #menu.yt-live-chat-text-message-renderer {
  423. transition-delay: 1ms;
  424. }
  425. #item.style-scope.yt-live-chat-item-list-renderer,
  426. #item-scroller.style-scope.yt-live-chat-item-list-renderer {
  427. transition-delay: 42ms;
  428. }
  429. yt-live-chat-item-list-renderer img[alt] {
  430. pointer-events: auto;
  431. }
  432. body yt-live-chat-item-list-renderer img[alt]~tp-yt-paper-tooltip,
  433. body yt-live-chat-item-list-renderer #image~tp-yt-paper-tooltip {
  434. --paper-tooltip-delay-in: 120ms !important;
  435. white-space: nowrap;
  436. }
  437. #items.style-scope.yt-live-chat-item-list-renderer>yt-live-chat-text-message-renderer.yt-live-chat-item-list-renderer {
  438. --tabview-chat-message-display: block;
  439. --tabview-chat-message-mt: 2px;
  440. --tabview-chat-message-mb: 4px;
  441. }
  442. #message.yt-live-chat-text-message-renderer {
  443. display: var(--tabview-chat-message-display);
  444. margin-top: var(--tabview-chat-message-mt);
  445. margin-bottom: var(--tabview-chat-message-mb);
  446. }
  447. [collapsed] #message.yt-live-chat-text-message-renderer {
  448. --tabview-chat-message-display: 'VOID';
  449. --tabview-chat-message-mt: 'VOID';
  450. --tabview-chat-message-mb: 'VOID';
  451. }
  452. @supports (contain: layout paint style) {
  453.  
  454. /*
  455. contain: layout paint style;
  456. // #item-offset uses transform, it is buggy in Opera 93.0 with contain: layout & paint
  457. */
  458.  
  459. body yt-live-chat-app {
  460. contain: size layout paint style;
  461. /* content-visibility: auto; */
  462. transform: translate3d(0, 0, 0);
  463. overflow: hidden;
  464. }
  465.  
  466. #items.style-scope.yt-live-chat-item-list-renderer{
  467. contain: layout paint style;
  468. }
  469.  
  470. #item-offset.style-scope.yt-live-chat-item-list-renderer {
  471. contain: style;
  472. }
  473.  
  474. #item-scroller.style-scope.yt-live-chat-item-list-renderer {
  475. contain: size style;
  476. }
  477.  
  478. #contents.style-scope.yt-live-chat-item-list-renderer,
  479. #chat.style-scope.yt-live-chat-renderer,
  480. img.style-scope.yt-img-shadow[width][height] {
  481. contain: size layout paint style;
  482. }
  483.  
  484. .style-scope.yt-live-chat-ticker-renderer[role="button"][aria-label],
  485. .style-scope.yt-live-chat-ticker-renderer[role="button"][aria-label]>#container {
  486. contain: layout paint style;
  487. }
  488.  
  489.  
  490. yt-img-shadow#author-photo.style-scope {
  491. contain: layout paint style;
  492. /*
  493. content-visibility: auto;
  494. contain-intrinsic-size: 24px 24px;
  495. */
  496. }
  497.  
  498. yt-live-chat-text-message-renderer:not([author-is-owner]) #author-photo.style-scope.yt-live-chat-text-message-renderer,
  499. yt-live-chat-text-message-renderer:not([author-is-owner]) yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer {
  500. pointer-events: var(--tabview-msg-pointer-events);
  501. }
  502.  
  503. yt-live-chat-text-message-renderer:not([author-is-owner]) span#message.style-scope.yt-live-chat-text-message-renderer>img.emoji.yt-formatted-string.style-scope.yt-live-chat-text-message-renderer {
  504. cursor: var(--tabview-msg-cursor);
  505. }
  506.  
  507.  
  508. yt-live-chat-text-message-renderer:not([author-is-owner]) span#message.style-scope.yt-live-chat-text-message-renderer,
  509. yt-live-chat-paid-message-renderer #message.yt-live-chat-paid-message-renderer,
  510. yt-live-chat-text-message-renderer:not([author-is-owner]) #timestamp.style-scope.yt-live-chat-text-message-renderer,
  511. yt-live-chat-membership-item-renderer #header-content.style-scope.yt-live-chat-membership-item-renderer,
  512. yt-live-chat-membership-item-renderer #timestamp.style-scope.yt-live-chat-membership-item-renderer,
  513. yt-live-chat-paid-message-renderer #header-content.yt-live-chat-paid-message-renderer,
  514. yt-live-chat-paid-message-renderer #timestamp.style-scope.yt-live-chat-paid-message-renderer,
  515. yt-live-chat-paid-sticker-renderer #content.style-scope.yt-live-chat-paid-sticker-renderer,
  516. yt-live-chat-paid-sticker-renderer #timestamp.style-scope.yt-live-chat-paid-sticker-renderer {
  517. cursor: var(--tabview-msg-cursor);
  518. pointer-events: var(--tabview-msg-pointer-events);
  519. }
  520.  
  521. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer,
  522. yt-live-chat-membership-item-renderer.style-scope.yt-live-chat-item-list-renderer,
  523. yt-live-chat-paid-message-renderer.style-scope.yt-live-chat-item-list-renderer,
  524. yt-live-chat-banner-manager.style-scope.yt-live-chat-item-list-renderer {
  525. contain: layout style;
  526. }
  527.  
  528. tp-yt-paper-tooltip[style*="inset"][role="tooltip"] {
  529. contain: layout paint style;
  530. }
  531.  
  532. /*
  533. yt-live-chat-banner-renderer[collapsed] #contents, yt-live-chat-banner-renderer[collapsed] #contents * {
  534.  
  535. content-visibility: visible !important;
  536. contain: none !important;
  537.  
  538. }
  539. */
  540.  
  541. /* YouTube Native Bug - style="height:0px; translateY(0px);" */
  542. yt-live-chat-banner-renderer[collapsed]:has(#contents[style*="0px;"][style*="translateY(0px);"]) #header.yt-live-chat-banner-renderer{
  543. position:absolute;
  544. }
  545.  
  546. yt-live-chat-banner-renderer[collapsed]:has(#contents[style*="0px;"][style*="translateY(0px);"]) #contents.yt-live-chat-banner-renderer{
  547. height:auto !important;
  548. transform:initial !important;
  549. }
  550.  
  551. }
  552. #chat-messages tp-yt-iron-dropdown#dropdown.style-scope.tp-yt-paper-menu-button {
  553. margin-right: var(--ytd-margin-12x);
  554. }
  555.  
  556.  
  557. tp-yt-iron-dropdown.yt-live-chat-app[vertical-align="top"] ytd-menu-popup-renderer.yt-live-chat-app {
  558. max-height: 60vh !important; /* override style */
  559. }
  560.  
  561. /* 2023/05/05 fixed darker-dark-theme thin border on the bottom of chatroom */
  562. html yt-live-chat-renderer[darker-dark-theme] #panel-pages.yt-live-chat-renderer {
  563. border: 0;
  564. }
  565.  
  566. `.trim();
  567. });
  568.  
  569.  
  570. let iframePointEventsAllow = false; // default to discard unnecessary mouse events for iframe
  571.  
  572. let scriptEnable = false;
  573.  
  574. let comments_loader = 0; // for comment count (might omit)
  575.  
  576. let cmTime = 0;
  577. const mTime = Date.now() - 152000000;
  578.  
  579. //let lastScrollFetch = 0;
  580. //let lastOffsetTop = 0;
  581. let mtf_forceCheckLiveVideo_disable = 0;
  582.  
  583. let tabsUiScript_setclick = false;
  584. let pageFetchedData = null; // data object; for future use
  585. let pageFetchedDataVideoId = null; // integer; for comment checking
  586. let pageType = null; // pageType = 'watch', 'browse', 'playlist', ...
  587. let chatroomDetails = null;
  588. let switchTabActivity_lastTab = null
  589.  
  590. let lstTab = null;
  591.  
  592. let storeLastPanel = null; // WeakRef
  593.  
  594.  
  595. let mtf_chatBlockQ = null; // for chat layout status change
  596.  
  597. let enableHoverSliderDetection = false; // for hover slider
  598.  
  599.  
  600. let firstLoadStatus = 2 | 8; // for page init
  601.  
  602.  
  603. let m_last_count = ''; // for comment count
  604.  
  605.  
  606.  
  607. let sVideosITO = null;
  608.  
  609. /** @type {WeakRef | null} */
  610. let ytdFlexy = null; // WeakRef
  611.  
  612. const Q = {}
  613. const SETTING_DEFAULT_TAB_0 = "#tab-videos"
  614. const settings = {
  615. defaultTab: SETTING_DEFAULT_TAB_0
  616. };
  617.  
  618. const STORE_VERSION = 1;
  619. const STORE_key = 'userscript-tabview-settings';
  620. const key_default_tab = 'my-default-tab';
  621.  
  622. let fetchCounts = {
  623. base: null,
  624. new: null,
  625. fetched: false,
  626. count: null,
  627. }
  628.  
  629. let pageLang = 'en';
  630. const langWords = {
  631. 'en': {
  632. //'share':'Share',
  633. 'info': 'Info',
  634. 'videos': 'Videos',
  635. 'playlist': 'Playlist'
  636. },
  637. 'jp': {
  638. //'share':'共有',
  639. 'info': '情報',
  640. 'videos': '動画',
  641. 'playlist': '再生リスト'
  642. },
  643. 'tw': {
  644. //'share':'分享',
  645. 'info': '資訊',
  646. 'videos': '影片',
  647. 'playlist': '播放清單'
  648. },
  649. 'cn': {
  650. //'share':'分享',
  651. 'info': '资讯',
  652. 'videos': '视频',
  653. 'playlist': '播放列表'
  654. },
  655. 'du': {
  656. //'share':'Teilen',
  657. 'info': 'Info',
  658. 'videos': 'Videos',
  659. 'playlist': 'Playlist'
  660. },
  661. 'fr': {
  662. //'share':'Partager',
  663. 'info': 'Info',
  664. 'videos': 'Vidéos',
  665. 'playlist': 'Playlist'
  666. },
  667. 'kr': {
  668. //'share':'공유',
  669. 'info': '정보',
  670. 'videos': '동영상',
  671. 'playlist': '재생목록'
  672. },
  673. 'ru': {
  674. //'share':'Поделиться',
  675. 'info': 'Описание',
  676. 'videos': 'Видео',
  677. 'playlist': 'Плейлист'
  678. }
  679. };
  680.  
  681. const getGMT = () => {
  682. let m = new Date('2023-01-01T00:00:00Z');
  683. return m.getDate() === 1 ? `+${m.getHours()}` : `-${24 - m.getHours()}`;
  684. };
  685.  
  686. function durationInfoTS(durationInfo) {
  687. /**
  688. * @type {{ hrs: number, mins: number, seconds: number }}
  689. */
  690. let _durationInfo = durationInfo
  691. return _durationInfo
  692. }
  693.  
  694. function formatDateReqTS(req) {
  695. /**
  696. * @type {{ bd1: KDate | undefined, bd2: KDate | undefined, isSameDay: number | undefined, durationInfo: object | undefined, formatDates: object | undefined }}
  697. */
  698. let _req = req
  699. return _req
  700. }
  701.  
  702. function liveDurationLocaleEN(durationInfo) {
  703.  
  704. const { hrs, mins, seconds } = durationInfoTS(durationInfo)
  705. let ret = []
  706. ret.push(`Length:`)
  707. if (hrs > 0) ret.push(`${hrs} ${hrs === 1 ? 'hour' : 'hours'}`)
  708. if (mins > 0) ret.push(`${mins} ${mins === 1 ? 'minute' : 'minutes'}`)
  709. if (seconds !== null) ret.push(`${seconds} ${seconds === 1 ? 'second' : 'seconds'}`)
  710. return ret.join(' ')
  711. }
  712.  
  713. /* liveDurationLocaleEN by ChatGPT @ 2023.05.11 */
  714. function liveDurationLocaleJP(durationInfo) {
  715.  
  716. const { hrs, mins, seconds } = durationInfoTS(durationInfo);
  717. let ret = [];
  718. ret.push(`長さ:`);
  719. if (hrs > 0) ret.push(`${hrs}時間`);
  720. if (mins > 0) ret.push(`${mins}分`);
  721. if (seconds !== null) ret.push(`${seconds}秒`);
  722. return ret.join('');
  723. }
  724.  
  725. function formatDateResultEN(type, req) {
  726.  
  727. const { bd1, bd2, durationInfo, formatDates } = formatDateReqTS(req)
  728.  
  729. switch (type) {
  730. case 0x200:
  731. return [
  732. `The livestream was in ${bd1.lokStringDateEN()} from ${bd1.lokStringTime()} to ${bd2.lokStringTime()}. [GMT${getGMT()}]`,
  733. liveDurationLocaleEN(durationInfo)
  734. ].join('\n');
  735. case 0x210:
  736. return [
  737. `The livestream was from ${bd1.lokStringDateEN()} ${bd1.lokStringTime()} to ${bd2.lokStringDateEN()} ${bd2.lokStringTime()}. [GMT${getGMT()}]`,
  738. liveDurationLocaleEN(durationInfo)
  739. ].join('\n');
  740. case 0x300:
  741. return `The livestream started at ${bd1.lokStringTime()} [GMT${getGMT()}] in ${bd1.lokStringDateEN()}.`;
  742. case 0x600:
  743. return `The video was uploaded in ${formatDates.uploadDate} and published in ${formatDates.publishDate}.`;
  744. case 0x610:
  745. return `The video was uploaded in ${formatDates.uploadDate}.`;
  746. case 0x700:
  747. return `The video was published in ${formatDates.publishDate}.`;
  748. }
  749. return '';
  750.  
  751. }
  752.  
  753. /* formatDateResultJP by ChatGPT @ 2023.05.11 */
  754.  
  755. function formatDateResultJP(type, req) {
  756.  
  757. const { bd1, bd2, durationInfo, formatDates } = formatDateReqTS(req);
  758. switch (type) {
  759. case 0x200:
  760. return [
  761. `ライブ配信は${bd1.lokStringDateJP()}の${bd1.lokStringTime()}から開始し、${bd2.lokStringTime()}まで続きました。[GMT${getGMT()}]`,
  762. liveDurationLocaleJP(durationInfo)
  763. ].join('\n');
  764. case 0x210:
  765. return [
  766. `ライブ配信は${bd1.lokStringDateJP()}の${bd1.lokStringTime()}から${bd2.lokStringDateJP()}の${bd2.lokStringTime()}まで行われました。[GMT${getGMT()}]`,
  767. liveDurationLocaleJP(durationInfo)
  768. ].join('\n');
  769. case 0x300:
  770. return `ライブ配信は${bd1.lokStringDateJP()}の${bd1.lokStringTime()}から開始しました。[GMT${getGMT()}]`;
  771. case 0x600:
  772. return `この動画は${formatDates.uploadDate}にアップロードされ、${formatDates.publishDate}に公開されました。`;
  773. case 0x610:
  774. return `この動画は${formatDates.uploadDate}にアップロードされました。`;
  775. case 0x700:
  776. return `この動画は${formatDates.publishDate}に公開されました。`;
  777. }
  778. return '';
  779. }
  780.  
  781. function getFormatDateResultFunc(){
  782. switch(getLang()){
  783. case 'jp':
  784. return formatDateResultJP;
  785. case 'en':
  786. default:
  787. return formatDateResultEN;
  788. }
  789. }
  790.  
  791.  
  792. const S_GENERAL_RENDERERS = ['YTD-TOGGLE-BUTTON-RENDERER', 'YTD-MENU-RENDERER']
  793.  
  794. let globalHook_symbols = [];
  795. let globalHook_hashs = {};
  796.  
  797.  
  798. let singleColumnScrolling_dt = 0;
  799.  
  800. let isStickyHeaderEnabled = false;
  801. let isMiniviewForStickyHeadEnabled = false;
  802.  
  803. let theater_mode_changed_dt = 0;
  804. let detailsTriggerReset = false;
  805.  
  806.  
  807. let isMakeHeaderFloatCalled = false;
  808.  
  809. let _viTimeNum = 200;
  810. let _updateTimeAccum = 0;
  811.  
  812. /** @type {WeakMap<HTMLElement>} */
  813. let loadedCommentsDT = new WeakMap();
  814.  
  815.  
  816.  
  817. // for weakref variable management
  818. const es = {
  819. get ytdFlexy() {
  820. /** @type { HTMLElement | null } */
  821. let res = kRef(ytdFlexy);
  822. return res;
  823. },
  824. get storeLastPanel() {
  825. /** @type { HTMLElement | null } */
  826. let res = kRef(storeLastPanel);
  827. return res;
  828. }
  829. }
  830.  
  831.  
  832. const _console = new Proxy(console, {
  833. get(target, prop, receiver) {
  834. if (!DEBUG_LOG && prop === 'log') {
  835. return nullFunc
  836. }
  837. return Reflect.get(...arguments)
  838. }
  839. });
  840.  
  841. let generalLog901 = !DEBUG_LOG ? 0 : (evt) => {
  842. _console.log(901, evt.type)
  843. }
  844.  
  845. const isPassiveArgSupport = (typeof IntersectionObserver === 'function');
  846. // https://caniuse.com/?search=observer
  847. // https://caniuse.com/?search=addEventListener%20passive
  848.  
  849. const bubblePassive = isPassiveArgSupport ? { capture: false, passive: true } : false;
  850. const capturePassive = isPassiveArgSupport ? { capture: true, passive: true } : true;
  851.  
  852.  
  853. /** @type { (str: string) => (HTMLElement | null) } */
  854. const querySelectorFromAnchor = HTMLElement.prototype.querySelector; // nodeType==1 // since 2022/07/12
  855.  
  856. /** @type { (str: string) => (NodeList) } */
  857. const querySelectorAllFromAnchor = HTMLElement.prototype.querySelectorAll; // nodeType==1 // since 2022/07/12
  858. const closestDOM = HTMLElement.prototype.closest;
  859. //const elementRemove = HTMLElement.prototype.remove;
  860. //const elementContains = HTMLElement.prototype.contains; // since 2022/07/12
  861. const elementAppend = HTMLElement.prototype.appendChild; // necessary for yt custom elements; due to Waterfox classic and https://greasyfork.org/en/scripts/428651-tabview-youtube/discussions/174437
  862.  
  863. const closestDOMX = function (child, parentSelector) {
  864. if (!(child instanceof HTMLElement)) return null;
  865. return closestDOM.call(child, parentSelector) || null;
  866. }
  867.  
  868. /**
  869. *
  870. * @param {number} f bit flag
  871. * @param {number} w bit flag (with)
  872. * @param {number} wo bit flag (without)
  873. * @returns
  874. */
  875. const fT = function (f, w, wo) {
  876. return (f & (w | wo)) === w
  877. }
  878.  
  879. /* globals WeakRef:false */
  880.  
  881. /** @type {(o: Object | null) => WeakRef | null} */
  882. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  883.  
  884. /** @type {(wr: Object | null) => Object | null} */
  885. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  886.  
  887.  
  888. function setTimeout3(f) {
  889. Promise.race([new Promise(r => requestAnimationFrame(r)), new Promise(r => setTimeout(r, 300))]).then(f);
  890. }
  891.  
  892. const timeline = {
  893. // after initialized (initObserver)
  894. cn1: {},
  895. cn2: {},
  896. setTimeout( /** @type {TimerHandler} */ f,/** @type {number} */ d) {
  897. let cid = setTimeout(f, d)
  898. timeline.cn1[cid] = true
  899. return cid;
  900. },
  901. clearTimeout(/** @type {number} */ cid) {
  902. timeline.cn1[cid] = false; return clearTimeout(cid)
  903. },
  904. setInterval(/** @type {TimerHandler} */ f,/** @type {number} */ d) {
  905. let cid = setInterval(f, d);
  906. timeline.cn2[cid] = true
  907. return cid;
  908. },
  909. clearInterval(/** @type {number} */ cid) {
  910. timeline.cn2[cid] = false; return clearInterval(cid)
  911. },
  912. reset() {
  913. for (let cid in timeline.cn1) timeline.cn1[cid] && clearTimeout(cid)
  914. for (let cid in timeline.cn2) timeline.cn2[cid] && clearInterval(cid)
  915. timeline.cn1 = {}
  916. timeline.cn2 = {}
  917. }
  918. }
  919.  
  920.  
  921. // function prettyElm(/** @type {Element} */ elm) {
  922. // if (!elm || !elm.nodeName) return null;
  923. // const eId = elm.id || null;
  924. // const eClsName = elm.className || null;
  925. // return [elm.nodeName.toLowerCase(), typeof eId == 'string' ? "#" + eId : '', typeof eClsName == 'string' ? '.' + eClsName.replace(/\s+/g, '.') : ''].join('').trim();
  926. // }
  927.  
  928. // function extractTextContent(/** @type {Node} */ elm) {
  929. // return elm.textContent.replace(/\s+/g, '').replace(/[^\da-zA-Z\u4E00-\u9FFF\u00C0-\u00FF\u00C0-\u02AF\u1E00-\u1EFF\u0590-\u05FF\u0400-\u052F\u0E00-\u0E7F\u0600-\u06FF\u0750-\u077F\u1100-\u11FF\u3130-\u318F\uAC00-\uD7AF\u3040-\u30FF\u31F0-\u31FF]/g, '')
  930. // }
  931.  
  932. function addScript(/** @type {string} */ scriptText) {
  933. const scriptNode = document.createElement('script');
  934. scriptNode.type = 'text/javascript';
  935. scriptNode.textContent = scriptText;
  936. try {
  937. document.documentElement.appendChild(scriptNode);
  938. } catch (e) {
  939. console.log('addScript Error', e)
  940. }
  941. return scriptNode;
  942. }
  943.  
  944. function addScriptByURL(/** @type {string} */ scriptURL) {
  945. const scriptNode = document.createElement('script');
  946. scriptNode.type = 'text/javascript';
  947. scriptNode.src = scriptURL;
  948. try {
  949. document.documentElement.appendChild(scriptNode);
  950. } catch (e) {
  951. console.log('addScriptByURL Error', e)
  952. }
  953. return scriptNode;
  954. }
  955.  
  956. function addStyle(/** @type {string} */ styleText, /** @type {HTMLElement | Document} */ container) {
  957. const styleNode = document.createElement('style');
  958. //styleNode.type = 'text/css';
  959. styleNode.textContent = styleText;
  960. (container || document.documentElement).appendChild(styleNode);
  961. return styleNode;
  962. }
  963.  
  964.  
  965.  
  966. /*
  967.  
  968. yt-action yt-add-element-to-app yt-autonav-pause-blur yt-autonav-pause-focus
  969. yt-autonav-pause-guide-closed yt-autonav-pause-guide-opened yt-autonav-pause-player
  970. yt-autonav-pause-player-ended yt-autonav-pause-scroll yt-autoplay-on-changed
  971. yt-close-tou-form yt-consent-bump-display-changed yt-focus-searchbox
  972. yt-get-context-provider yt-guide-close yt-guide-hover yt-guide-toggle
  973. yt-history-load yt-history-pop yt-load-invalidation-continuation
  974. yt-load-next-continuation yt-load-reload-continuation yt-load-tou-form
  975. yt-masthead-height-changed yt-navigate yt-navigate-cache yt-navigate-error
  976. yt-navigate-finish yt-navigate-redirect yt-navigate-set-page-offset
  977. yt-navigate-start yt-next-continuation-data-updated yt-open-hotkey-dialog
  978. yt-open-tou-form-loading-state yt-page-data-fetched yt-page-data-updated
  979. yt-page-data-will-update yt-page-manager-navigate-start yt-page-navigate-start
  980. yt-page-type-changed yt-player-attached yt-player-detached yt-player-released
  981. yt-player-requested yt-player-updated yt-popup-canceled yt-popup-closed
  982. yt-popup-opened yt-preconnect-urls yt-register-action yt-report-form-closed
  983. yt-report-form-opened yt-request-panel-mode-change yt-retrieve-location
  984. yt-service-request-completed yt-service-request-error yt-service-request-sent
  985. yt-set-theater-mode-enabled yt-show-survey yt-subscription-changed
  986. yt-swatch-changed yt-theater-mode-allowed yt-unregister-action yt-update-title
  987. yt-update-unseen-notification-count yt-viewport-scanned yt-visibility-refresh
  988.  
  989. */
  990.  
  991.  
  992. _console.log(38489)
  993.  
  994. class Session {
  995. constructor(initValue) {
  996. this.sid = initValue;
  997. }
  998. session() {
  999. let pageSession = this;
  1000. let s = pageSession.sid; // inaccessible from external
  1001. return {
  1002. get isValid() {
  1003. return s === pageSession.sid;
  1004. }
  1005. };
  1006. }
  1007. set(newValue) {
  1008. this.sid = newValue;
  1009. }
  1010. inc() {
  1011. this.sid++;
  1012. }
  1013. }
  1014.  
  1015. class Deferred {
  1016. constructor() {
  1017. this.reset();
  1018. }
  1019. debounce(f) {
  1020. return Promise.race([this.promise]).then(f).catch(console.warn); // avoid promise.then.then.then ...
  1021. }
  1022. d() {
  1023. return Promise.race([this.promise]).catch(console.warn);
  1024. }
  1025. reset() {
  1026. this.resolved = false;
  1027. this.promise = new Promise((resolve, reject) => {
  1028. //this.reject = reject
  1029. this._resolve = resolve
  1030. })
  1031. }
  1032. resolve() {
  1033. if (this._resolve === null) return null;
  1034. if (this.resolved !== false) return false;
  1035. this.resolved = true;
  1036. this._resolve(...arguments);
  1037. return true;
  1038. }
  1039. }
  1040.  
  1041. class Mutex {
  1042.  
  1043. constructor() {
  1044. this.p = Promise.resolve()
  1045. }
  1046.  
  1047. lockWith(f) {
  1048.  
  1049. this.p = this.p.then(() => {
  1050. return new Promise(f)
  1051. }).catch(console.warn)
  1052. }
  1053.  
  1054. }
  1055.  
  1056.  
  1057.  
  1058. /* FireMonkey unable to extend MutationObserver correctly */
  1059. class AttributeMutationObserver extends MutationObserver {
  1060. constructor(flist) {
  1061. super((mutations, observer) => {
  1062. for (const mutation of mutations) {
  1063. if (mutation.type === 'attributes') {
  1064. this.checker(mutation.target, mutation.attributeName)
  1065. }
  1066. }
  1067. })
  1068. this.flist = flist;
  1069. this.res = {}
  1070. }
  1071.  
  1072. takeRecords() {
  1073. super.takeRecords();
  1074. }
  1075. disconnect() {
  1076. this._target = null;
  1077. super.disconnect();
  1078. }
  1079. observe(/** @type {Node} */ target) {
  1080. if (this._target) return;
  1081. //console.log(123124, target)
  1082. this._target = mWeakRef(target);
  1083.  
  1084. //console.log(123125, kRef(this._target))
  1085. const options = {
  1086. attributes: true,
  1087. attributeFilter: Object.keys(this.flist),
  1088. //attributeFilter: [ "status", "username" ],
  1089. attributeOldValue: true
  1090. }
  1091. super.observe(target, options)
  1092. }
  1093. checker(/** @type {Node} */ target,/** @type {string} */ attributeName) {
  1094. let nv = target.getAttribute(attributeName);
  1095. if (this.res[attributeName] !== nv) {
  1096. this.res[attributeName] = nv
  1097. let f = this.flist[attributeName];
  1098. if (f) f(attributeName, nv);
  1099.  
  1100. }
  1101. }
  1102. check(delay = 0) {
  1103. setTimeout(() => {
  1104. let target = kRef(this._target)
  1105. if (target !== null) {
  1106. for (const key of Object.keys(this.flist)) {
  1107. this.checker(target, key)
  1108. }
  1109. } else {
  1110. console.log('target is null') //disconnected??
  1111. }
  1112. target = null;
  1113. }, delay)
  1114. }
  1115. }
  1116.  
  1117. class KDate extends Date {
  1118.  
  1119. constructor(...args) {
  1120. super(...args)
  1121. this.dayBack = false
  1122. }
  1123.  
  1124. browserSupported() {
  1125.  
  1126. }
  1127.  
  1128.  
  1129. lokStringDateEN() {
  1130. const d = this
  1131.  
  1132. let y = d.getFullYear()
  1133. let m = d.getMonth() + 1
  1134. let date = d.getDate()
  1135.  
  1136. let sy = y < 1000 ? (`0000${y}`).slice(-4) : '' + y
  1137.  
  1138. let sm = m < 10 ? '0' + m : '' + m
  1139. let sd = date < 10 ? '0' + date : '' + date
  1140.  
  1141. return `${sy}.${sm}.${sd}`
  1142.  
  1143. }
  1144.  
  1145. lokStringDateJP() {
  1146. const d = this
  1147.  
  1148. let y = d.getFullYear()
  1149. let m = d.getMonth() + 1
  1150. let date = d.getDate()
  1151.  
  1152. let sy = y < 1000 ? (`0000${y}`).slice(-4) : '' + y
  1153.  
  1154. let sm = m < 10 ? '0' + m : '' + m
  1155. let sd = date < 10 ? '0' + date : '' + date
  1156.  
  1157. return `${sy}/${sm}/${sd}`
  1158.  
  1159. }
  1160.  
  1161. lokStringTime() {
  1162. const d = this
  1163.  
  1164. let h = d.getHours()
  1165. let m = d.getMinutes()
  1166.  
  1167. const k = this.dayBack
  1168.  
  1169. if (k) h += 24
  1170.  
  1171. let sh = h < 10 ? '0' + h : '' + h
  1172. let sm = m < 10 ? '0' + m : '' + m
  1173.  
  1174.  
  1175. return `${sh}:${sm}`
  1176.  
  1177. }
  1178.  
  1179.  
  1180.  
  1181.  
  1182. }
  1183.  
  1184. console.assert('browserSupported' in (new KDate()),
  1185. { error: "0x87FF", errorMsg: "Your userscript manager is not supported. FireMonkey is not recommended." }
  1186. );
  1187.  
  1188.  
  1189.  
  1190. let pageSession = new Session(0);
  1191. const tabsDeferred = new Deferred();
  1192. tabsDeferred.resolve();
  1193.  
  1194. let layoutStatusMutex = new Mutex();
  1195.  
  1196. let sliderMutex = new Mutex();
  1197. const renderDeferred = new Deferred(); //pageRendered
  1198. let pageRendered = 0;
  1199. let renderIdentifier = 0;
  1200.  
  1201. const scriptletDeferred = new Deferred();
  1202.  
  1203.  
  1204. function scriptInjector(script_id, url_chrome, response_id) {
  1205.  
  1206. let res = {
  1207. script_id: script_id,
  1208. inject: function () {
  1209.  
  1210. let res = this, script_id = this.script_id;
  1211.  
  1212. if (!document.querySelector(`script#${script_id}`)) {
  1213. if (res.runtime_url) {
  1214. addScriptByURL(res.runtime_url).id = script_id;
  1215. } else {
  1216. addScript(`${res.injection_script}`).id = script_id;
  1217. }
  1218. }
  1219.  
  1220. }
  1221. }
  1222. res.script_id = script_id;
  1223.  
  1224. if (isMyScriptInChromeRuntime()) {
  1225. res.runtime_url = window.chrome.runtime.getURL(url_chrome)
  1226. } else {
  1227. res.injection_script = GM_getResourceText(response_id);
  1228. }
  1229.  
  1230. return res;
  1231.  
  1232.  
  1233. }
  1234.  
  1235. const script_inject_js1 = scriptInjector(
  1236. 'userscript-tabview-injection-1',
  1237. 'js/injection_script_1.js',
  1238. "injectionJS1");
  1239.  
  1240.  
  1241. function nonCryptoRandStr(/** @type {number} */ n) {
  1242. const result = new Array(n);
  1243. const baseStr = nonCryptoRandStr_base;
  1244. const bLen = baseStr.length;
  1245. for (let i = 0; i < n; i++) {
  1246. let t = null
  1247. do {
  1248. t = baseStr.charAt(Math.floor(Math.random() * bLen));
  1249. } while (i === 0 && 10 - t > 0)
  1250. result[i] = t;
  1251. }
  1252. return result.join('');
  1253. }
  1254.  
  1255. const uidMAP = new Map();
  1256.  
  1257. function uidGEN(s) {
  1258. let uid = uidMAP.get(s);
  1259. if (!uid) {
  1260. const uidStore = ObserverRegister.uidStore;
  1261. do {
  1262. uid = nonCryptoRandStr(5);
  1263. } while (uidStore[uid])
  1264. uidMAP.set(s, uid);
  1265. }
  1266. return uid;
  1267. }
  1268.  
  1269. /**
  1270. * Class definition
  1271. * @property {string} propName - propriety description
  1272. * ...
  1273. */
  1274. class ObserverRegister {
  1275.  
  1276. constructor(/** @type {()=>MutationObserver | IntersectionObserver} */ observerCreator) {
  1277. let uid = null;
  1278. const uidStore = ObserverRegister.uidStore;
  1279. do {
  1280. uid = nonCryptoRandStr(5);
  1281. } while (uidStore[uid])
  1282. uidStore[uid] = true;
  1283.  
  1284. /**
  1285. * uid is the unique string for each observer
  1286. * @type {string}
  1287. * @public
  1288. */
  1289. this.uid = uid;
  1290.  
  1291. /**
  1292. * observerCreator is a function to create the observer
  1293. * @type {Function}
  1294. * @public
  1295. */
  1296. this.observerCreator = observerCreator
  1297.  
  1298. /**
  1299. * observer is the actual observer object
  1300. * @type {MutationObserver | IntersectionObserver}
  1301. * @public
  1302. */
  1303. this.observer = null;
  1304. this.bindCount = 0;
  1305. }
  1306. bindElement(/** @type {HTMLElement} */ elm, ...args) {
  1307. if (elm.hasAttribute(`o3r-${this.uid}`)) return false;
  1308. elm.setAttribute(`o3r-${this.uid}`, '')
  1309. this.bindCount++;
  1310. if (this.observer === null) {
  1311. this.observer = this.observerCreator();
  1312. }
  1313. this.observer.observe(elm, ...args)
  1314. return true
  1315. }
  1316. clear(/** @type {boolean} */ flag) {
  1317. if (this.observer !== null) {
  1318. //const uidStore = ObserverRegister.uidStore;
  1319. if (flag === true) {
  1320. this.observer.takeRecords();
  1321. this.observer.disconnect();
  1322. }
  1323. this.observer = null;
  1324. this.bindCount = 0;
  1325. for (const s of document.querySelectorAll(`[o3r-${this.uid}]`)) s.removeAttribute(`o3r-${this.uid}`)
  1326. //uidStore[this.uid]=false;
  1327. //this.uid = null;
  1328. }
  1329. }
  1330. }
  1331.  
  1332. /**
  1333. * 'uidStore' is the static store of strings used.
  1334. * @static
  1335. */
  1336. ObserverRegister.uidStore = {}; //backward compatible with FireFox 55.
  1337.  
  1338.  
  1339. const mtoObservationDetails = new ObserverRegister(() => {
  1340. return new IntersectionObserver(ito_details, {
  1341. root: null,
  1342. rootMargin: "0px"
  1343. })
  1344. });
  1345.  
  1346.  
  1347. const mtoFlexyAttr = new ObserverRegister(() => {
  1348. return new MutationObserver(mtf_attrFlexy)
  1349. });
  1350.  
  1351. const mtoVisibility_EngagementPanel = new ObserverRegister(() => {
  1352. return new MutationObserver(FP.mtf_attrEngagementPanel)
  1353. });
  1354.  
  1355. const mtoVisibility_Playlist = new ObserverRegister(() => {
  1356. return new AttributeMutationObserver({
  1357. "hidden": FP.mtf_attrPlaylist
  1358. })
  1359. })
  1360. const sa_playlist = mtoVisibility_Playlist.uid;
  1361.  
  1362. const mtoVisibility_Comments = new ObserverRegister(() => {
  1363. return new AttributeMutationObserver({
  1364. "hidden": FP.mtf_attrComments
  1365. })
  1366. })
  1367. const sa_comments = mtoVisibility_Comments.uid;
  1368.  
  1369.  
  1370. const mtoVisibility_Chatroom = new ObserverRegister(() => {
  1371. return new AttributeMutationObserver({
  1372. "collapsed": FP.mtf_attrChatroom
  1373. })
  1374. })
  1375. // const sa_chatroom = mtoVisibility_Chatroom.uid;
  1376.  
  1377.  
  1378.  
  1379.  
  1380. function isDOMVisible(/** @type {HTMLElement} */ elem) {
  1381. // jQuery version : https://github.com/jquery/jquery/blob/a684e6ba836f7c553968d7d026ed7941e1a612d8/src/css/hiddenVisibleSelectors.js
  1382. return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
  1383. }
  1384.  
  1385. function isNonEmptyString(s) {
  1386. return typeof s == 'string' && s.length > 0;
  1387. }
  1388.  
  1389. function tabviewDispatchEvent(elmTarget, eventName, detail) {
  1390. if (!elmTarget || typeof elmTarget.nodeType !== 'number' || typeof eventName !== 'string') return;
  1391. if (detail && typeof detail === 'object') {
  1392. elmTarget.dispatchEvent(new CustomEvent(eventName, { detail: detail }))
  1393. } else {
  1394. elmTarget.dispatchEvent(new CustomEvent(eventName))
  1395. }
  1396. }
  1397.  
  1398. async function nativeCall(/** @type {EventTarget} */ dom, /** @type {any[]} */ detail) {
  1399. //console.log(1231)
  1400. dom.dispatchEvent(new CustomEvent("userscript-call-dom", { detail: detail }))
  1401. //console.log(1232)
  1402. }
  1403.  
  1404. async function nativeFunc(/** @type {EventTarget} */ dom, /** @type {string} */ property, /** @type {any} */ args) {
  1405. dom.dispatchEvent(new CustomEvent("userscript-call-dom-func", { detail: { property, args } }))
  1406. }
  1407.  
  1408. // async function nativeValue(dom, property, args) {
  1409. // dom.dispatchEvent(new CustomEvent("userscript-call-dom-value", { detail: { property, args } }))
  1410. // }
  1411. // async function nativeFuncStacked(/** @type {string} */ selector, /** @type {string} */ property, /** @type {any} */ args){
  1412. // document.dispatchEvent(new CustomEvent("userscript-call-dom-func-stacked", { detail: { selector, property, args } }))
  1413. // }
  1414. // async function nativeValueStacked(selector, property, args){
  1415. // document.dispatchEvent(new CustomEvent("userscript-call-dom-value-stacked", { detail: { selector, property, args } }))
  1416. // }
  1417. // async function nativeConstStacked(selector, property, args){
  1418. // document.dispatchEvent(new CustomEvent("userscript-call-dom-const-stacked", { detail: { selector, property, args } }))
  1419. // }
  1420.  
  1421. async function dispatchWindowResize() {
  1422. // for youtube to detect layout resize for adjusting Player tools
  1423. return window.dispatchEvent(new Event('resize'));
  1424. }
  1425.  
  1426. async function dispatchCommentRowResize() {
  1427.  
  1428. if (pageType !== "watch") return;
  1429.  
  1430. const ytdFlexyElm = es.ytdFlexy;
  1431. if (!ytdFlexyElm) return;
  1432. if (ytdFlexyElm.getAttribute('tyt-tab') !== '#tab-comments') return;
  1433.  
  1434. scriptletDeferred.debounce(() => {
  1435. document.dispatchEvent(new CustomEvent('tabview-resize-comments-rows'));
  1436. })
  1437.  
  1438.  
  1439. }
  1440.  
  1441. function enterPIP(video, errorHandler) {
  1442. return new Promise(resolve => {
  1443. if (video && typeof video.requestPictureInPicture === 'function' && typeof document.exitPictureInPicture === 'function') {
  1444. if (isVideoPlaying(video) && document.pictureInPictureElement === null) {
  1445. video.requestPictureInPicture().then(res => {
  1446. resolve(true);
  1447. }).catch((e) => {
  1448. if(errorHandler === undefined) console.warn(e);
  1449. else if(typeof errorHandler == 'function') errorHandler(e);
  1450. resolve(false);
  1451. });
  1452. } else {
  1453. resolve(false);
  1454. }
  1455. } else {
  1456. resolve(null);
  1457. }
  1458. })
  1459. }
  1460.  
  1461. function exitPIP() {
  1462. if (document.pictureInPictureElement !== null && typeof document.exitPictureInPicture === 'function') {
  1463. document.exitPictureInPicture().then(res => {
  1464.  
  1465. }).catch(console.warn)
  1466. }
  1467. }
  1468.  
  1469. function setToggleBtnTxt() {
  1470.  
  1471. if (chatroomDetails) {
  1472. _console.log(124234, 'c=== ')
  1473.  
  1474. let chat = document.querySelector('ytd-live-chat-frame#chat');
  1475. if (!chat) return;
  1476. let txt = querySelectorFromAnchor.call(chat, 'span.yt-core-attributed-string[role="text"]');
  1477. let c = (txt || 0).textContent;
  1478.  
  1479. if (typeof c === 'string' && c.length > 2) {
  1480. if (chat.hasAttribute('collapsed')) {
  1481. _console.log(124234, 'collapsed show expand ', chatroomDetails.txt_expand)
  1482. if (c !== chatroomDetails.txt_expand) {
  1483. txt.textContent = chatroomDetails.txt_expand;
  1484. }
  1485. } else {
  1486. _console.log(124234, 'not collapsed show collapse ', chatroomDetails.txt_collapse)
  1487. if (c !== chatroomDetails.txt_collapse) {
  1488. txt.textContent = chatroomDetails.txt_collapse;
  1489. }
  1490. }
  1491. }
  1492. }
  1493. }
  1494.  
  1495.  
  1496. function handlerTabExpanderClick() {
  1497.  
  1498. async function b() {
  1499.  
  1500. let h1 = document.documentElement.clientHeight;
  1501. let h2 = (document.querySelector('#right-tabs') || 0).clientHeight;
  1502.  
  1503. await Promise.resolve(0);
  1504. if (h1 > 300 && h2 > 300) {
  1505. let ratio = h2 / h1; // positive below 1.0
  1506.  
  1507. return ratio;
  1508. }
  1509. return 0;
  1510. }
  1511.  
  1512. async function a() {
  1513.  
  1514.  
  1515. let secondary = document.querySelector('#secondary.ytd-watch-flexy');
  1516. if (secondary) {
  1517.  
  1518.  
  1519. if (!secondary.classList.contains('tabview-hover-slider-enable')) {
  1520.  
  1521. let secondaryInner = querySelectorFromAnchor.call(secondary, '#secondary-inner.ytd-watch-flexy');
  1522.  
  1523. if (secondaryInner) {
  1524.  
  1525. if (!secondary.classList.contains('tabview-hover-slider')) {
  1526. // without hover
  1527.  
  1528. //let rect = secondary.getBoundingClientRect();
  1529. //let rectI = secondaryInner.getBoundingClientRect();
  1530.  
  1531. secondaryInner.style.setProperty('--tabview-slider-right', `${getSecondaryInnerRight()}px`)
  1532.  
  1533. }
  1534.  
  1535. let ratio = await b();
  1536. if (ratio > 0.0 && ratio <= 1.0) {
  1537.  
  1538. secondaryInner.style.setProperty('--ytd-watch-flexy-sidebar-width-d', `${Math.round(100 * ratio * 10) / 10}vw`);
  1539. secondary.classList.add('tabview-hover-slider');
  1540. secondary.classList.add('tabview-hover-slider-enable');
  1541.  
  1542. let video = document.querySelector('#player video');
  1543. enterPIP(video);
  1544.  
  1545. }
  1546.  
  1547. }
  1548.  
  1549.  
  1550. } else {
  1551.  
  1552.  
  1553. secondary.dispatchEvent(new CustomEvent("tabview-hover-slider-restore"));
  1554. //console.log(1994)
  1555.  
  1556. }
  1557.  
  1558. // no animation event triggered for hover -> enable
  1559. dispatchCommentRowResize();
  1560.  
  1561. }
  1562.  
  1563.  
  1564.  
  1565. }
  1566.  
  1567.  
  1568. a();
  1569.  
  1570.  
  1571. }
  1572.  
  1573. let global_columns_end_ito = null;
  1574.  
  1575. function setupHoverSlider(secondary, columns) {
  1576.  
  1577. if (!secondary || !columns) return;
  1578. let attrName = `o4r-${uidGEN('tabview-hover-slider-restore')}`;
  1579.  
  1580. if (secondary.hasAttribute(attrName)) return;
  1581. secondary.setAttribute(attrName, '');
  1582.  
  1583. let elmB = document.querySelector('tabview-view-secondary-xpander');
  1584. if (!elmB) {
  1585. elmB = document.createElement('tabview-view-secondary-xpander');
  1586. prependTo(elmB, secondary);
  1587. }
  1588.  
  1589. let elmA = document.querySelector('tabview-view-columns-endpos');
  1590. if (elmA) elmA.remove();
  1591. elmA = document.createElement('tabview-view-columns-endpos');
  1592.  
  1593. let itoA = new IntersectionObserver((entries) => {
  1594. let t = null;
  1595. let w = enableHoverSliderDetection
  1596. for (const entry of entries) {
  1597. if (entry.rootBounds === null) continue;
  1598. let bcr = entry.boundingClientRect;
  1599. let rb = entry.rootBounds;
  1600. t = !entry.isIntersecting && (bcr.left > rb.right) && (rb.left <= 0);
  1601. // if entries.length>1 (unlikely); take the last intersecting
  1602. // supplement cond 1. ensure the col element is in the right side
  1603. // supplement cond 2. ensure column is wide enough for overflow checking
  1604. // it can also avoid if the layout change happened but attribute not yet changed during the intersection observation
  1605. }
  1606.  
  1607. let columns = document.querySelector('#columns.style-scope.ytd-watch-flexy');
  1608. if (columns) columns.classList.toggle('tyt-column-overflow', t);
  1609.  
  1610. if (w !== t && t !== null) {
  1611. // t can be true when the layout enters single column mode
  1612. enableHoverSliderDetection = t;
  1613. }
  1614. //console.log(entries, enableHoverSliderDetection, t)
  1615. })
  1616. elementAppend.call(columns, elmA); // append to dom first before observe
  1617. if ((wls.layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) {
  1618. //to trigger observation at the time layout being changed
  1619. itoA.observe(elmA);
  1620. }
  1621. global_columns_end_ito = itoA;
  1622.  
  1623.  
  1624. secondary.addEventListener('tabview-hover-slider-restore', function (evt) {
  1625.  
  1626. let secondary = evt.target;
  1627.  
  1628. if (!secondary.classList.contains('tabview-hover-slider-enable')) return;
  1629.  
  1630. let secondaryInner = querySelectorFromAnchor.call(secondary, '#secondary-inner.ytd-watch-flexy')
  1631.  
  1632. if (!secondaryInner) return;
  1633.  
  1634. if (secondary.classList.contains('tabview-hover-slider-hover')) {
  1635.  
  1636. Promise.resolve(0).then(() => {
  1637. secondaryInner.style.removeProperty('--ytd-watch-flexy-sidebar-width-d');
  1638. }).then(() => {
  1639. secondary.classList.remove('tabview-hover-slider-enable')
  1640. exitPIP();
  1641. })
  1642.  
  1643. } else {
  1644.  
  1645. let secondary = evt.target;
  1646. secondary.classList.remove('tabview-hover-slider')
  1647. secondary.classList.remove('tabview-hover-slider-enable')
  1648.  
  1649. secondaryInner.style.removeProperty('--ytd-watch-flexy-sidebar-width-d');
  1650. secondaryInner.style.removeProperty('--tabview-slider-right')
  1651.  
  1652. exitPIP();
  1653.  
  1654. }
  1655.  
  1656. setTimeout(() => {
  1657. updateFloatingSlider()
  1658. }, 30);
  1659.  
  1660. }, false);
  1661.  
  1662. }
  1663.  
  1664. function addTabExpander(tabContent) {
  1665.  
  1666. if (!tabContent) return null;
  1667. let id = tabContent.id;
  1668. if (!id || typeof id !== 'string') return null;
  1669.  
  1670. if (querySelectorFromAnchor.call(tabContent, `#${id} > tabview-view-tab-expander`)) return false;
  1671.  
  1672. let elm = document.createElement('tabview-view-tab-expander')
  1673. prependTo(elm, tabContent);
  1674. elm.innerHTML = `<div>${svgElm(16, 16, 12, 12, svgDiag1, 'svg-expand')}${svgElm(16, 16, 12, 12, svgDiag2, 'svg-collapse')}</div>`
  1675. elm.addEventListener('click', handlerTabExpanderClick, false);
  1676. return true;
  1677.  
  1678. }
  1679.  
  1680. function getColumnOverflowWidth() {
  1681.  
  1682. let screenWidth = document.documentElement.getBoundingClientRect().width;
  1683.  
  1684. let posElm1 = document.querySelector('#secondary.style-scope.ytd-watch-flexy + tabview-view-columns-endpos');
  1685.  
  1686. if (posElm1) {
  1687.  
  1688. let offset = posElm1.getBoundingClientRect().x - screenWidth;
  1689. return offset
  1690.  
  1691. }
  1692. return null
  1693. }
  1694.  
  1695. function getSecondaryInnerRight() {
  1696.  
  1697. let posElm1 = document.querySelector('#secondary.style-scope.ytd-watch-flexy + tabview-view-columns-endpos');
  1698.  
  1699. let posElm2 = document.querySelector('#secondary.style-scope.ytd-watch-flexy > tabview-view-secondary-xpander');
  1700.  
  1701. if (posElm1 && posElm2) {
  1702.  
  1703. let offset = posElm1.getBoundingClientRect().x - posElm2.getBoundingClientRect().right;
  1704. return offset
  1705.  
  1706. }
  1707. return null
  1708.  
  1709. }
  1710.  
  1711. const setFloatingSliderOffset = (secondaryInner) => {
  1712.  
  1713.  
  1714. let posElm1 = document.querySelector('#secondary.style-scope.ytd-watch-flexy + tabview-view-columns-endpos');
  1715.  
  1716. let posElm2 = document.querySelector('#secondary.style-scope.ytd-watch-flexy > tabview-view-secondary-xpander');
  1717.  
  1718. if (posElm1 && posElm2) {
  1719.  
  1720. let offset = getColumnOverflowWidth();
  1721.  
  1722. let k = 1.0
  1723. if (offset >= 125) {
  1724. k = 1.0
  1725. } else if (offset >= 75) {
  1726. k = 1.0;
  1727. } else if (offset >= 25) {
  1728. k = 0.25;
  1729. } else {
  1730. k = 0.0
  1731. }
  1732. secondaryInner.style.setProperty('--tabview-slider-offset-k2', `${k}`);
  1733. secondaryInner.style.setProperty('--tabview-slider-offset', `${offset}px`) // unnecessary
  1734.  
  1735. let oriWidth = posElm2.getBoundingClientRect().width;
  1736. secondaryInner.style.setProperty('--tabview-slider-ow', `${oriWidth}px`)
  1737.  
  1738. let s1 = 'var(--ytd-watch-flexy-sidebar-width-d)';
  1739. // new width
  1740.  
  1741. let s2 = `var(--tabview-slider-ow)`;
  1742. // ori width - youtube changing the code -> not reliable to use css prop.
  1743.  
  1744. let s3 = `${offset}px`;
  1745. // how many px wider than the page
  1746.  
  1747. secondaryInner.style.setProperty('--tabview-slider-offset-actual', `calc(${s1} - ${s2} + ${s3})`)
  1748.  
  1749. }
  1750.  
  1751. }
  1752.  
  1753. async function updateFloatingSlider_A(secondaryInner) {
  1754.  
  1755. // [is-extra-wide-video_]
  1756.  
  1757. await new Promise(r => setTimeout(r, 30)); // time allowed for dom changes and value change of enableHoverSliderDetection
  1758.  
  1759. let secondary = secondaryInner.parentNode;
  1760. if (!secondary) return;
  1761.  
  1762. if (secondary.classList.contains('tabview-hover-slider-enable')) {
  1763. return;
  1764. }
  1765.  
  1766. if (!secondary.matches('#columns.ytd-watch-flexy #primary.ytd-watch-flexy ~ #secondary.ytd-watch-flexy')) {
  1767. return;
  1768. }
  1769.  
  1770. const bool = enableHoverSliderDetection === true;
  1771. const hasClassHover = secondary.classList.contains('tabview-hover-slider-hover') === true;
  1772.  
  1773. if (bool || hasClassHover) {
  1774. } else {
  1775. return;
  1776. }
  1777.  
  1778. await Promise.resolve(0);
  1779.  
  1780. secondary.classList.add('tabview-hover-final')
  1781.  
  1782. if (hasClassHover && !bool) {
  1783. secondaryInner.style.removeProperty('--tabview-slider-right')
  1784. secondaryInner.style.removeProperty('--tabview-slider-offset')
  1785. } else {
  1786.  
  1787. if (!hasClassHover) {
  1788. secondaryInner.style.setProperty('--tabview-slider-right', `${getSecondaryInnerRight()}px`)
  1789. }
  1790.  
  1791. setFloatingSliderOffset(secondaryInner);
  1792. }
  1793.  
  1794. if (bool ^ hasClassHover) {
  1795. secondary.classList.toggle('tabview-hover-slider', bool)
  1796. secondary.classList.toggle('tabview-hover-slider-hover', bool)
  1797. }
  1798.  
  1799. await Promise.resolve(0);
  1800.  
  1801.  
  1802. setTimeout(() => {
  1803. secondary.classList.remove('tabview-hover-final')
  1804. }, 350)
  1805.  
  1806.  
  1807. }
  1808.  
  1809.  
  1810. function updateFloatingSlider() {
  1811.  
  1812. let secondaryInner = document.querySelector('ytd-watch-flexy[flexy][is-two-columns_] #secondary-inner.ytd-watch-flexy')
  1813.  
  1814. if (!secondaryInner) return;
  1815.  
  1816. let secondary = secondaryInner.parentNode;
  1817. if (!secondary) return;
  1818.  
  1819. if (secondary.classList.contains('tabview-hover-slider-enable')) {
  1820. return;
  1821. }
  1822.  
  1823. let t = document.documentElement.clientWidth; //integer
  1824.  
  1825. sliderMutex.lockWith(unlock => {
  1826.  
  1827. let v = document.documentElement.clientWidth; //integer
  1828.  
  1829. if (t === v && secondaryInner.matches('body ytd-watch-flexy[flexy][is-two-columns_] #secondary-inner.ytd-watch-flexy')) {
  1830.  
  1831. updateFloatingSlider_A(secondaryInner).then(unlock);
  1832. } else {
  1833. unlock();
  1834. }
  1835.  
  1836. })
  1837.  
  1838. }
  1839.  
  1840.  
  1841. function setToActiveTab(defaultTab) {
  1842. if (isTheater() && isWideScreenWithTwoColumns()) return;
  1843. const jElm = document.querySelector(`a[tyt-tab-content="${switchTabActivity_lastTab}"]:not(.tab-btn-hidden)`) ||
  1844. document.querySelector(`a[tyt-tab-content="${(defaultTab || settings.defaultTab)}"]:not(.tab-btn-hidden)`) ||
  1845. document.querySelector(`a[tyt-tab-content="${(SETTING_DEFAULT_TAB_0)}"]:not(.tab-btn-hidden)`) ||
  1846. document.querySelector("a[tyt-tab-content]:not(.tab-btn-hidden)") ||
  1847. null;
  1848.  
  1849. switchTabActivity(jElm);
  1850. return !!jElm;
  1851. }
  1852.  
  1853. let enableLivePopupCheck = false
  1854.  
  1855. function layoutStatusChanged(/** @type {number} */ old_layoutStatus, /** @type {number} */ new_layoutStatus) {
  1856.  
  1857.  
  1858. if ((new_layoutStatus & LAYOUT_TWO_COLUMNS) === 0) makeHeaderFloat();
  1859.  
  1860. //if (old_layoutStatus === new_layoutStatus) return;
  1861.  
  1862. const cssElm = es.ytdFlexy;
  1863.  
  1864. if (!cssElm) return;
  1865.  
  1866.  
  1867. const BF_TWOCOL_N_THEATER = LAYOUT_TWO_COLUMNS | LAYOUT_THEATER
  1868.  
  1869. let new_isExpandedChat = !!(new_layoutStatus & LAYOUT_CHATROOM_EXPANDED)
  1870. let new_isCollapsedChat = !!(new_layoutStatus & LAYOUT_CHATROOM_COLLAPSED) && !!(new_layoutStatus & LAYOUT_CHATROOM)
  1871.  
  1872. let new_isTabExpanded = !!(new_layoutStatus & LAYOUT_TAB_EXPANDED);
  1873. let new_isFullScreen = !!(new_layoutStatus & LAYOUT_FULLSCREEN);
  1874. let new_isExpandedEPanel = !!(new_layoutStatus & LAYOUT_ENGAGEMENT_PANEL_EXPANDED);
  1875. let new_isExpandedDonationShelf = !!(new_layoutStatus & LAYOUT_DONATION_SHELF_EXPANDED);
  1876.  
  1877.  
  1878. function showTabOrChat() {
  1879.  
  1880. layoutStatusMutex.lockWith(unlock => {
  1881.  
  1882. if (lstTab.lastPanel == '#chatroom') {
  1883.  
  1884. if (new_isTabExpanded) switchTabActivity(null)
  1885. if (!new_isExpandedChat) ytBtnExpandChat();
  1886.  
  1887. } else if (lstTab.lastPanel && lstTab.lastPanel.indexOf('#engagement-panel-') == 0) {
  1888.  
  1889. if (new_isTabExpanded) switchTabActivity(null)
  1890. if (!new_isExpandedEPanel) ytBtnOpenEngagementPanel(lstTab.lastPanel);
  1891.  
  1892. } else if (lstTab.lastPanel == '#donation-shelf') {
  1893.  
  1894. if (new_isTabExpanded) switchTabActivity(null)
  1895. if (!new_isExpandedDonationShelf) openDonationShelf();
  1896.  
  1897. } else {
  1898.  
  1899. if (new_isExpandedChat) ytBtnCollapseChat()
  1900. if (!new_isTabExpanded) setToActiveTab();
  1901.  
  1902. }
  1903.  
  1904. timeline.setTimeout(unlock, 40);
  1905.  
  1906. })
  1907. }
  1908.  
  1909. function hideTabAndChat() {
  1910.  
  1911. layoutStatusMutex.lockWith(unlock => {
  1912.  
  1913. if (new_isTabExpanded) switchTabActivity(null)
  1914. if (new_isExpandedChat) ytBtnCollapseChat()
  1915. if (new_isExpandedEPanel) ytBtnCloseEngagementPanels();
  1916. if (new_isExpandedDonationShelf) closeDonationShelf();
  1917.  
  1918.  
  1919. timeline.setTimeout(unlock, 40);
  1920.  
  1921. })
  1922.  
  1923. }
  1924.  
  1925. const statusCollapsedFalse = !!(new_layoutStatus & (LAYOUT_TAB_EXPANDED | LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED | LAYOUT_CHATROOM_EXPANDED))
  1926. const statusCollapsedTrue = !statusCollapsedFalse
  1927.  
  1928. let changes = (old_layoutStatus & LAYOUT_VAILD) ? old_layoutStatus ^ new_layoutStatus : 0;
  1929.  
  1930. let chat_collapsed_changed = !!(changes & LAYOUT_CHATROOM_COLLAPSED)
  1931. let chat_expanded_changed = !!(changes & LAYOUT_CHATROOM_EXPANDED)
  1932. let tab_expanded_changed = !!(changes & LAYOUT_TAB_EXPANDED)
  1933. let theater_mode_changed = !!(changes & LAYOUT_THEATER)
  1934. let column_mode_changed = !!(changes & LAYOUT_TWO_COLUMNS)
  1935. let fullscreen_mode_changed = !!(changes & LAYOUT_FULLSCREEN)
  1936. let epanel_expanded_changed = !!(changes & LAYOUT_ENGAGEMENT_PANEL_EXPANDED)
  1937. let ds_expanded_changed = !!(changes & LAYOUT_DONATION_SHELF_EXPANDED)
  1938.  
  1939. _console.log(8221, 1, chat_collapsed_changed, chat_expanded_changed, tab_expanded_changed, theater_mode_changed, column_mode_changed, fullscreen_mode_changed, epanel_expanded_changed)
  1940.  
  1941.  
  1942. //console.log(169, 1, chat_collapsed_changed, tab_expanded_changed)
  1943. //console.log(169, 2, new_isExpandedChat, new_isCollapsedChat, new_isTabExpanded)
  1944.  
  1945. let BF_LayoutCh_Panel = (changes & (LAYOUT_TAB_EXPANDED | LAYOUT_CHATROOM_EXPANDED | LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED))
  1946. let tab_change = BF_LayoutCh_Panel;
  1947. let isChatOrTabExpandTriggering = !!((new_layoutStatus) & BF_LayoutCh_Panel);
  1948. let isChatOrTabCollaspeTriggering = !!((~new_layoutStatus) & BF_LayoutCh_Panel);
  1949.  
  1950.  
  1951. const moreThanOneShown = (new_isTabExpanded + new_isExpandedChat + new_isExpandedEPanel + new_isExpandedDonationShelf) > 1
  1952.  
  1953.  
  1954. const base_twoCol_NoTheather_chatExpand_a = LAYOUT_TWO_COLUMNS | LAYOUT_THEATER | LAYOUT_CHATROOM | LAYOUT_CHATROOM_COLLAPSED
  1955. const base_twoCol_NoTheather_chatExpand_b = LAYOUT_TWO_COLUMNS | 0 | LAYOUT_CHATROOM | 0
  1956.  
  1957. // two column; not theater; tab collapse; chat expand; ep expand
  1958. const IF_01a = base_twoCol_NoTheather_chatExpand_a | LAYOUT_TAB_EXPANDED | LAYOUT_ENGAGEMENT_PANEL_EXPANDED;
  1959. const IF_01b = base_twoCol_NoTheather_chatExpand_b | 0 | LAYOUT_ENGAGEMENT_PANEL_EXPANDED;
  1960.  
  1961. // two column; not theater; tab collapse; chat expand; ep expand
  1962. const IF_07a = base_twoCol_NoTheather_chatExpand_a | LAYOUT_TAB_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED;
  1963. const IF_07b = base_twoCol_NoTheather_chatExpand_b | 0 | LAYOUT_DONATION_SHELF_EXPANDED;
  1964.  
  1965.  
  1966. // two column; not theater;
  1967. const IF_02a = BF_TWOCOL_N_THEATER;
  1968. const IF_02b = LAYOUT_TWO_COLUMNS;
  1969.  
  1970. // two column; not theater; tab expand; chat expand;
  1971. const IF_03a = base_twoCol_NoTheather_chatExpand_a | LAYOUT_TAB_EXPANDED;
  1972. const IF_03b = base_twoCol_NoTheather_chatExpand_b | LAYOUT_TAB_EXPANDED;
  1973.  
  1974.  
  1975. // two column; tab expand; chat expand;
  1976. const IF_06a = LAYOUT_TWO_COLUMNS | LAYOUT_TAB_EXPANDED | LAYOUT_CHATROOM | LAYOUT_CHATROOM_COLLAPSED;
  1977. const IF_06b = LAYOUT_TWO_COLUMNS | LAYOUT_TAB_EXPANDED | LAYOUT_CHATROOM | 0;
  1978.  
  1979.  
  1980. // two column; theater;
  1981. const IF_04a = BF_TWOCOL_N_THEATER;
  1982. const IF_04b = BF_TWOCOL_N_THEATER;
  1983.  
  1984. // not fullscreen; two column; not theater; not tab expand; not EP expand; not expand chat; not donation shelf
  1985. const IF_05a = LAYOUT_FULLSCREEN | LAYOUT_TWO_COLUMNS | LAYOUT_THEATER | LAYOUT_TAB_EXPANDED | LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED | LAYOUT_CHATROOM_EXPANDED;
  1986. const IF_05b = 0 | LAYOUT_TWO_COLUMNS | 0 | 0 | 0 | 0 | 0;
  1987.  
  1988. let _isChatPopupedF = null
  1989. let isChatPopupedF = ()=>{
  1990. return _isChatPopupedF===null ? ( _isChatPopupedF = cssElm.classList.contains('tyt-chat-popup') ) : _isChatPopupedF
  1991. }
  1992.  
  1993. if (new_isFullScreen) {
  1994.  
  1995.  
  1996. if (tab_change == LAYOUT_CHATROOM_EXPANDED && (new_layoutStatus & IF_06a) === IF_06b && statusCollapsedFalse && !column_mode_changed) {
  1997.  
  1998. // two column; tab expand; chat expand;
  1999.  
  2000. switchTabActivity(null);
  2001.  
  2002. }
  2003.  
  2004. if (!!(tab_change & LAYOUT_CHATROOM_EXPANDED) && new_isExpandedChat) {
  2005. //tab_change = LAYOUT_CHATROOM_EXPANDED
  2006. //tab_change = LAYOUT_CHATROOM_EXPANDED|LAYOUT_TAB_EXPANDED
  2007.  
  2008.  
  2009. timeline.setTimeout(() => {
  2010. let scrollElement = document.querySelector('ytd-app[scrolling]')
  2011. if (!scrollElement) return;
  2012. // single column view; click button; scroll to tab content area 100%
  2013. let chatFrame = document.querySelector('ytd-live-chat-frame#chat');
  2014. if (chatFrame && isChatExpand()) {
  2015. _console.log(7290, 1)
  2016. chatFrame.scrollIntoView(true);
  2017. }
  2018. }, 60)
  2019.  
  2020. }
  2021.  
  2022. if (!!(tab_change & LAYOUT_ENGAGEMENT_PANEL_EXPANDED) && new_isExpandedEPanel) {
  2023.  
  2024. timeline.setTimeout(() => {
  2025. let scrollElement = document.querySelector('ytd-app[scrolling]')
  2026. if (!scrollElement) return;
  2027. // single column view; click button; scroll to tab content area 100%
  2028. let epPanel = document.querySelector('ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility][visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"]:not([hidden])');
  2029. if (epPanel) {
  2030. _console.log(7290, 2)
  2031.  
  2032. let pi = 50;
  2033. let cid = setInterval(() => {
  2034. if (--pi) epPanel.scrollIntoView(true); else clearInterval(cid)
  2035. }, 17)
  2036. //
  2037. }
  2038. }, 60)
  2039.  
  2040. }
  2041.  
  2042.  
  2043. } else if (fullscreen_mode_changed) {
  2044.  
  2045. // new_isFullScreen: false
  2046. // fullscreen_mode_changed: true
  2047.  
  2048. if (!new_isFullScreen && statusCollapsedTrue && isWideScreenWithTwoColumns() && !isTheater()) {
  2049. showTabOrChat();
  2050. } else if (!new_isFullScreen && statusCollapsedFalse && isWideScreenWithTwoColumns() && isTheater()) {
  2051.  
  2052. if(cisChatPopupedF()){
  2053. }else{
  2054.  
  2055. ytBtnCancelTheater();
  2056.  
  2057. }
  2058. }
  2059.  
  2060. } else if ((new_layoutStatus & IF_01a) === IF_01b && !column_mode_changed && (tab_change == LAYOUT_CHATROOM_EXPANDED || tab_change == LAYOUT_ENGAGEMENT_PANEL_EXPANDED)) {
  2061.  
  2062. // new_isFullScreen: false
  2063. // fullscreen_mode_changed: false
  2064.  
  2065. // two column; not theater; tab collapse; chat expand; ep expand
  2066.  
  2067. if (epanel_expanded_changed) {
  2068. layoutStatusMutex.lockWith(unlock => {
  2069. ytBtnCollapseChat();
  2070. setTimeout(unlock, 13)
  2071. })
  2072. } else if (chat_collapsed_changed) {
  2073. layoutStatusMutex.lockWith(unlock => {
  2074. ytBtnCloseEngagementPanels();
  2075. setTimeout(unlock, 13)
  2076. })
  2077.  
  2078. }
  2079.  
  2080. } else if ((new_layoutStatus & IF_07a) === IF_07b && !column_mode_changed && (tab_change == LAYOUT_CHATROOM_EXPANDED || tab_change == LAYOUT_DONATION_SHELF_EXPANDED)) {
  2081.  
  2082. // new_isFullScreen: false
  2083. // fullscreen_mode_changed: false
  2084.  
  2085. // two column; not theater; tab collapse; chat expand; ds expand
  2086.  
  2087. if (ds_expanded_changed) {
  2088. layoutStatusMutex.lockWith(unlock => {
  2089. ytBtnCollapseChat();
  2090. setTimeout(unlock, 13)
  2091. })
  2092. } else if (chat_collapsed_changed) {
  2093. layoutStatusMutex.lockWith(unlock => {
  2094. closeDonationShelf();
  2095. setTimeout(unlock, 13)
  2096. })
  2097.  
  2098. }
  2099.  
  2100. } else if (!tab_change && column_mode_changed && (new_layoutStatus & IF_02a) === IF_02b && moreThanOneShown) {
  2101.  
  2102. // new_isFullScreen: false
  2103. // fullscreen_mode_changed: false
  2104.  
  2105. // two column; not theater;
  2106. // moreThanOneShown
  2107.  
  2108. showTabOrChat();
  2109.  
  2110. } else if (tab_change == LAYOUT_CHATROOM_EXPANDED && (new_layoutStatus & IF_03a) === IF_03b && statusCollapsedFalse && !column_mode_changed) {
  2111.  
  2112. // new_isFullScreen: false
  2113. // fullscreen_mode_changed: false
  2114.  
  2115. // two column; not theater; tab expand; chat expand;
  2116.  
  2117. switchTabActivity(null);
  2118.  
  2119. } else if (isChatOrTabExpandTriggering && (new_layoutStatus & IF_04a) === IF_04b && statusCollapsedFalse && (changes & BF_TWOCOL_N_THEATER) === 0) {
  2120.  
  2121. // new_isFullScreen: false
  2122. // fullscreen_mode_changed: false
  2123.  
  2124. ytBtnCancelTheater();
  2125.  
  2126. } else if ((new_layoutStatus & IF_04a) === IF_04b && statusCollapsedFalse) {
  2127.  
  2128. // new_isFullScreen: false
  2129. // fullscreen_mode_changed: false
  2130.  
  2131. if (isChatPopupedF()) {
  2132.  
  2133. } else {
  2134.  
  2135. hideTabAndChat();
  2136. }
  2137.  
  2138. } else if (isChatOrTabCollaspeTriggering && (new_layoutStatus & IF_02a) === IF_02b && statusCollapsedTrue && !column_mode_changed) {
  2139.  
  2140. // new_isFullScreen: false
  2141. // fullscreen_mode_changed: false
  2142.  
  2143. if (tab_change == LAYOUT_ENGAGEMENT_PANEL_EXPANDED) {
  2144.  
  2145. lstTab.lastPanel = null;
  2146.  
  2147. if (new_isFullScreen) {
  2148.  
  2149. } else {
  2150. showTabOrChat();
  2151. }
  2152. } else if (tab_change == LAYOUT_DONATION_SHELF_EXPANDED) {
  2153.  
  2154. lstTab.lastPanel = null;
  2155.  
  2156. if (new_isFullScreen) {
  2157.  
  2158. } else {
  2159. showTabOrChat();
  2160. }
  2161. } else if (tab_change == LAYOUT_CHATROOM_EXPANDED) {
  2162.  
  2163. lstTab.lastPanel = null;
  2164.  
  2165. if (new_isFullScreen) {
  2166.  
  2167. } else {
  2168. showTabOrChat();
  2169. }
  2170. } else {
  2171.  
  2172.  
  2173. if (new_isFullScreen) {
  2174.  
  2175. } else {
  2176.  
  2177. ytBtnSetTheater();
  2178.  
  2179. }
  2180.  
  2181. }
  2182.  
  2183. } else if (!tab_change && !!(changes & BF_TWOCOL_N_THEATER) && (new_layoutStatus & IF_02a) === IF_02b && statusCollapsedTrue) {
  2184.  
  2185. // new_isFullScreen: false
  2186. // fullscreen_mode_changed: false
  2187.  
  2188. showTabOrChat();
  2189.  
  2190. } else if ((new_layoutStatus & IF_05a) === IF_05b) {
  2191. // bug fix for restoring from mini player
  2192.  
  2193. layoutStatusMutex.lockWith(unlock => {
  2194. setToActiveTab();
  2195. timeline.setTimeout(unlock, 40);
  2196. });
  2197.  
  2198. }
  2199.  
  2200. if (theater_mode_changed) {
  2201. let tdt = Date.now();
  2202. theater_mode_changed_dt = tdt
  2203. setTimeout(() => {
  2204. if (theater_mode_changed_dt !== tdt) return;
  2205. updateFloatingSlider();
  2206. }, 130)
  2207. }
  2208.  
  2209. let secondary = null;
  2210. if (secondary = document.querySelector('.tabview-hover-slider-enable')) {
  2211. secondary.dispatchEvent(new CustomEvent('tabview-hover-slider-restore'))
  2212. //console.log(1996)
  2213. }
  2214.  
  2215.  
  2216. if (fullscreen_mode_changed) {
  2217. detailsTriggerReset = true;
  2218. setTimeout(() => {
  2219. setHiddenStateForDesc();
  2220. }, 80);
  2221. }
  2222.  
  2223. // resize => is-two-columns_
  2224. if (column_mode_changed) {
  2225.  
  2226. Promise.resolve(0).then(() => {
  2227.  
  2228. if (moreThanOneShown && (new_layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) {
  2229. layoutStatusMutex.lockWith(unlock => {
  2230. if (new_isTabExpanded && lstTab.lastPanel === null) {
  2231. if (new_isExpandedChat) ytBtnCollapseChat();
  2232. if (new_isExpandedEPanel) ytBtnCloseEngagementPanels();
  2233. if (new_isExpandedDonationShelf) closeDonationShelf();
  2234. } else if (lstTab.lastPanel) {
  2235. let lastPanel = lstTab.lastPanel || '';
  2236. if (typeof lastPanel !== 'string') lastPanel = '';
  2237. if (new_isExpandedChat && lastPanel !== '#chatroom') ytBtnCollapseChat();
  2238. if (new_isExpandedEPanel && lastPanel.indexOf('#engagement-panel-') < 0) ytBtnCloseEngagementPanels();
  2239. if (new_isExpandedDonationShelf && lastPanel !== '#donation-shelf') closeDonationShelf();
  2240. switchTabActivity(null);
  2241. }
  2242. timeline.setTimeout(unlock, 40);
  2243. });
  2244. }
  2245.  
  2246. pageCheck();
  2247. if (global_columns_end_ito !== null) {
  2248. //to trigger observation at the time layout being changed
  2249. if ((new_layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) {
  2250. let endpos = document.querySelector('tabview-view-columns-endpos')
  2251. if (endpos !== null) {
  2252. global_columns_end_ito.observe(endpos)
  2253. }
  2254. } else {
  2255. global_columns_end_ito.disconnect();
  2256. }
  2257. }
  2258. setTimeout3(() => {
  2259. singleColumnScrolling(true); //initalize sticky
  2260. });
  2261. })
  2262. }
  2263.  
  2264. if (enableLivePopupCheck === true) {
  2265.  
  2266. const new_isTwoColumnsTheater = fT(new_layoutStatus, LAYOUT_TWO_COLUMNS | LAYOUT_THEATER, 0)
  2267.  
  2268. let currentIsTheaterPopupChat = new_isTwoColumnsTheater && new_isExpandedChat && isChatPopupedF()
  2269. if (!currentIsTheaterPopupChat) {
  2270. enableLivePopupCheck = false
  2271. document.dispatchEvent(new CustomEvent("tyt-close-popup"))
  2272. }
  2273.  
  2274. }
  2275.  
  2276.  
  2277. }
  2278.  
  2279. function fixLayoutStatus(x) {
  2280. const new_isExpandedChat = !(x & LAYOUT_CHATROOM_COLLAPSED) && (x & LAYOUT_CHATROOM)
  2281. return new_isExpandedChat ? (x | LAYOUT_CHATROOM_EXPANDED) : (x & ~LAYOUT_CHATROOM_EXPANDED);
  2282. }
  2283.  
  2284. const wls = new Proxy({
  2285. /** @type {number | null} */
  2286. layoutStatus: undefined
  2287. }, {
  2288. get: function (target, prop) {
  2289. return target[prop];
  2290. },
  2291. set: function (target, prop, value) {
  2292. if (prop == 'layoutStatus') {
  2293.  
  2294. if (value === 0) {
  2295. target[prop] = value;
  2296. return true;
  2297. } else if (target[prop] === value) {
  2298. return true;
  2299. } else {
  2300. if (!target.layoutStatus_pending) {
  2301. target.layoutStatus_pending = true;
  2302. const old_layoutStatus = target[prop];
  2303. target[prop] = value;
  2304. layoutStatusMutex.lockWith(unlock => {
  2305. target.layoutStatus_pending = false;
  2306. let new_layoutStatus = target[prop];
  2307. if (old_layoutStatus !== new_layoutStatus) {
  2308. layoutStatusChanged(old_layoutStatus, new_layoutStatus);
  2309. timeline.setTimeout(unlock, 40)
  2310. } else {
  2311. unlock();
  2312. }
  2313. })
  2314. return true;
  2315. }
  2316. }
  2317. }
  2318. target[prop] = value;
  2319. return true;
  2320. },
  2321. has: function (target, prop) {
  2322. return (prop in target);
  2323. }
  2324. });
  2325.  
  2326. const svgElm = (w, h, vw, vh, p, m) => `<svg${m ? ` class=${m}` : ''} width="${w}" height="${h}" viewBox="0 0 ${vw} ${vh}" preserveAspectRatio="xMidYMid meet">${p}</svg>`
  2327.  
  2328. function isVideoPlaying(video) {
  2329. return video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  2330. }
  2331.  
  2332. function wAttr(elm, attr, kv) {
  2333. if (elm) {
  2334. if (kv === true) {
  2335. elm.setAttribute(attr, '');
  2336. } else if (kv === false) {
  2337. elm.removeAttribute(attr);
  2338. } else if (kv === null) {
  2339. //;
  2340. } else if (typeof kv == 'string') {
  2341. elm.setAttribute(attr, kv);
  2342. }
  2343. }
  2344. }
  2345.  
  2346. function hideTabBtn(tabBtn) {
  2347. //console.log('hideTabBtn', tabBtn)
  2348. let isActiveBefore = tabBtn.classList.contains('active');
  2349. tabBtn.classList.add("tab-btn-hidden");
  2350. if (isActiveBefore) {
  2351. setToActiveTab();
  2352. }
  2353. }
  2354.  
  2355. // function hasAttribute(obj, key) {
  2356. // return obj && obj.hasAttribute(key);
  2357. // }
  2358.  
  2359. function isTheater() {
  2360. const cssElm = es.ytdFlexy;
  2361. return (cssElm && cssElm.hasAttribute('theater'))
  2362. }
  2363.  
  2364. function isFullScreen() {
  2365. const cssElm = es.ytdFlexy;
  2366. return (cssElm && cssElm.hasAttribute('fullscreen'))
  2367. }
  2368.  
  2369. function isChatExpand() {
  2370. const cssElm = es.ytdFlexy;
  2371. return cssElm && (cssElm.getAttribute('tyt-chat') || '').charAt(0) === '+'
  2372. }
  2373.  
  2374. function isWideScreenWithTwoColumns() {
  2375. const cssElm = es.ytdFlexy;
  2376. return (cssElm && cssElm.hasAttribute('is-two-columns_'))
  2377. }
  2378.  
  2379. function isAnyActiveTab() {
  2380. return document.querySelector('#right-tabs .tab-btn.active') !== null
  2381. }
  2382. // function isAnyActiveTab2() {
  2383. // return document.querySelectorAll('#right-tabs .tab-btn.active').length > 0
  2384. // }
  2385.  
  2386. function isEngagementPanelExpanded() { //note: not checking the visual elements
  2387. const cssElm = es.ytdFlexy;
  2388. return (cssElm && +cssElm.getAttribute('tyt-ep-visible') > 0)
  2389. }
  2390.  
  2391. function isDonationShelfExpanded() {
  2392. const cssElm = es.ytdFlexy;
  2393. return (cssElm && cssElm.hasAttribute('tyt-donation-shelf'))
  2394. }
  2395.  
  2396. const engagementIdMap = new Map();
  2397. let engagementIdNext = 1; // max 1 << 62
  2398.  
  2399. function engagement_panels_() {
  2400.  
  2401. let res = [];
  2402. // let shownRes = [];
  2403.  
  2404. let v = 0;
  2405. // let k = 1;
  2406. // let count = 0;
  2407.  
  2408. for (const ePanel of document.querySelectorAll(
  2409. `ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility]:not([hidden])`
  2410. )) {
  2411. let targetId = ePanel.getAttribute('target-id')
  2412. if (typeof targetId !== 'string') continue;
  2413. let eId = engagementIdMap.get(targetId)
  2414. if (!eId) {
  2415. engagementIdMap.set(targetId, eId = engagementIdNext)
  2416. if (engagementIdNext === (1 << 62)) {
  2417. engagementIdNext = 1;
  2418. console.warn('engagementId reached 1 << 62')
  2419. } else {
  2420. engagementIdNext = engagementIdNext << 1;
  2421. }
  2422. }
  2423. // console.log(55,eId, targetId)
  2424.  
  2425. let visibility = ePanel.getAttribute('visibility') //ENGAGEMENT_PANEL_VISIBILITY_EXPANDED //ENGAGEMENT_PANEL_VISIBILITY_HIDDEN
  2426.  
  2427. let k = eId
  2428. switch (visibility) {
  2429. case 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED':
  2430. v |= k;
  2431. // count++;
  2432. // shownRes.push(ePanel)
  2433. res.push({ ePanel, k, visible: true });
  2434. break;
  2435. case 'ENGAGEMENT_PANEL_VISIBILITY_HIDDEN':
  2436. res.push({ ePanel, k, visible: false });
  2437. break;
  2438. default:
  2439. res.push({ ePanel, k, visible: false });
  2440. }
  2441.  
  2442. //k = k << 1;
  2443.  
  2444. }
  2445. return { list: res, value: v };
  2446. // return { list: res, value: v, count: count, shownRes };
  2447. }
  2448.  
  2449.  
  2450. function ytBtnOpenEngagementPanel(/** @type {number | string} */ panel_id) {
  2451.  
  2452. // console.log(panel_id)
  2453. if (typeof panel_id == 'string') {
  2454. panel_id = panel_id.replace('#engagement-panel-', '');
  2455. panel_id = parseInt(panel_id);
  2456. }
  2457. if (panel_id >= 0) { } else return false;
  2458.  
  2459. let panels = engagement_panels_();
  2460. // console.log(panels)
  2461.  
  2462. let actions = []
  2463. for (const { ePanel, k, visible } of panels.list) {
  2464. if ((panel_id & k) === k) {
  2465. if (!visible) {
  2466. actions.push({
  2467. panelId: ePanel.getAttribute('target-id'),
  2468. toShow: true
  2469. })
  2470. }
  2471. } else {
  2472. if (visible) {
  2473. actions.push({
  2474. panelId: ePanel.getAttribute('target-id'),
  2475. toHide: true
  2476. })
  2477. }
  2478. }
  2479. }
  2480.  
  2481. if (actions.length > 0) {
  2482. // console.log(4545,actions)
  2483. scriptletDeferred.debounce(() => {
  2484. document.dispatchEvent(new CustomEvent('tyt-engagement-panel-visibility-change', {
  2485. detail: actions
  2486. }))
  2487. actions = null
  2488. })
  2489. }
  2490.  
  2491. }
  2492.  
  2493. function ytBtnCloseEngagementPanel(/** @type {HTMLElement} */ s) {
  2494. //ePanel.setAttribute('visibility',"ENGAGEMENT_PANEL_VISIBILITY_HIDDEN");
  2495.  
  2496. let panelId = s.getAttribute('target-id')
  2497. scriptletDeferred.debounce(() => {
  2498. document.dispatchEvent(new CustomEvent('tyt-engagement-panel-visibility-change', {
  2499. detail: {
  2500. panelId,
  2501. toHide: true
  2502. }
  2503. }))
  2504. })
  2505.  
  2506. }
  2507.  
  2508. function ytBtnCloseEngagementPanels() {
  2509. if (isEngagementPanelExpanded()) {
  2510. for (const s of document.querySelectorAll(
  2511. `ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility]:not([hidden])`
  2512. )) {
  2513. if (s.getAttribute('visibility') == "ENGAGEMENT_PANEL_VISIBILITY_EXPANDED") ytBtnCloseEngagementPanel(s);
  2514. }
  2515. }
  2516. }
  2517.  
  2518. function openDonationShelf() {
  2519. if (!isDonationShelfExpanded()){
  2520. let btn = document.querySelector('#tyt-donation-shelf-toggle-btn')
  2521. if(btn){
  2522. btn.click();
  2523. return true;
  2524. }
  2525. }
  2526. return false;
  2527. }
  2528. function closeDonationShelf() {
  2529. if (isDonationShelfExpanded()){
  2530. let btn = document.querySelector('#tyt-donation-shelf-toggle-btn')
  2531. if(btn){
  2532. btn.click();
  2533. return true;
  2534. }
  2535. }
  2536. return false;
  2537. }
  2538.  
  2539. function ytBtnSetTheater() {
  2540. if (!isTheater()) {
  2541. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  2542. if (sizeBtn) sizeBtn.click();
  2543. }
  2544. }
  2545.  
  2546. function ytBtnCancelTheater() {
  2547. if (isTheater()) {
  2548. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  2549. if (sizeBtn) sizeBtn.click();
  2550. }
  2551. }
  2552.  
  2553. function ytBtnExpandChat() {
  2554. let button = document.querySelector('ytd-live-chat-frame#chat[collapsed] > .ytd-live-chat-frame#show-hide-button')
  2555. if (button) {
  2556. button =
  2557. querySelectorFromAnchor.call(button, 'div.yt-spec-touch-feedback-shape') ||
  2558. querySelectorFromAnchor.call(button, 'ytd-toggle-button-renderer');
  2559. if (button) button.click();
  2560. }
  2561. }
  2562.  
  2563. function ytBtnCollapseChat() {
  2564. let button = document.querySelector('ytd-live-chat-frame#chat:not([collapsed]) > .ytd-live-chat-frame#show-hide-button')
  2565. if (button) {
  2566. button =
  2567. querySelectorFromAnchor.call(button, 'div.yt-spec-touch-feedback-shape') ||
  2568. querySelectorFromAnchor.call(button, 'ytd-toggle-button-renderer');
  2569. if (button) button.click();
  2570. }
  2571. }
  2572.  
  2573.  
  2574. async function makeVideosAutoLoad2() {
  2575. let sVideosList = document.querySelector('ytd-watch-flexy #tab-videos [placeholder-videos]');
  2576.  
  2577. if (!sVideosList) return null;
  2578.  
  2579. //let ab = sVideosList.getAttribute('tabview-videos-autoload')
  2580. await Promise.resolve(0);
  2581.  
  2582. let endPosDOM = document.querySelector('tabview-view-videos-endpos')
  2583. if (endPosDOM) endPosDOM.remove(); // just in case
  2584. endPosDOM = document.createElement('tabview-view-videos-endpos')
  2585. insertAfterTo(endPosDOM, sVideosList);
  2586.  
  2587. await Promise.resolve(0);
  2588.  
  2589.  
  2590. //sVideosList.setAttribute('tabview-videos-autoload', '1')
  2591.  
  2592. _console.log(9333)
  2593. if (!sVideosITO) {
  2594.  
  2595. sVideosITO = new IntersectionObserver((entries) => {
  2596.  
  2597. if ((wls.layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) return;
  2598.  
  2599. _console.log(9334, entries)
  2600. if (entries.length !== 1) return;
  2601. if (entries[0].isIntersecting !== true) return;
  2602. let elm = ((entries[0] || 0).target || 0);
  2603. if (!elm) return;
  2604. elm = null;
  2605. entries = null;
  2606.  
  2607. new Promise(resolve => {
  2608.  
  2609. // compatibile with Search While Watching Video
  2610. let isSearchGeneratedWithHiddenContinuation = !!document.querySelector('#related.style-scope.ytd-watch-flexy ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy ytd-compact-video-renderer.yt-search-generated.style-scope.ytd-item-section-renderer ~ ytd-continuation-item-renderer.style-scope.ytd-item-section-renderer[hidden]');
  2611. if (isSearchGeneratedWithHiddenContinuation) return;
  2612.  
  2613. // native YouTube coding use different way to handle custom videos, unknown condition for the continutation loading.
  2614. let isOtherChipSelected = !!document.querySelector('ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy yt-chip-cloud-renderer.style-scope.yt-related-chip-cloud-renderer yt-chip-cloud-chip-renderer.style-scope.yt-chip-cloud-renderer[aria-selected="false"] ~ [aria-selected="true"]')
  2615. if (isOtherChipSelected) return;
  2616.  
  2617. setTimeout(resolve, 30); // delay required to allow YouTube generate the continuation elements
  2618.  
  2619.  
  2620. }).then(() => {
  2621.  
  2622. let res = setVideosTwoColumns(2 | 4, true)
  2623.  
  2624. _console.log(9335, res)
  2625.  
  2626. if (res.m2 && res.m3) {
  2627. let m4 = closestDOM.call(res.m2, 'ytd-continuation-item-renderer');
  2628. let m5, m6;
  2629.  
  2630. _console.log(9336, m4)
  2631. if (m4) {
  2632. m5 = querySelectorFromAnchor.call(m4, 'ytd-button-renderer.style-scope.ytd-continuation-item-renderer, yt-button-renderer.style-scope.ytd-continuation-item-renderer');
  2633.  
  2634. // YouTube coding bug - correct is 'ytd-button-renderer'. If the page is redirected under single column mode, the tag become 'yt-button-renderer'
  2635. // under 'yt-button-renderer', the
  2636.  
  2637. if (m5)
  2638. m6 = querySelectorFromAnchor.call(m5, 'button.yt-spec-button-shape-next--call-to-action'); // main
  2639.  
  2640. _console.log(9337, m4, m5, m6)
  2641.  
  2642. if (m6) {
  2643. m6.click() // generic solution
  2644. } else if (m5) {
  2645. m5.click(); // not sure
  2646. } else {
  2647. m4.dispatchEvent(new Event('yt-service-request-sent-button-renderer')); // only for correct YouTube coding
  2648. }
  2649. }
  2650. m4 = null;
  2651. m5 = null;
  2652. m6 = null;
  2653. }
  2654. res = null;
  2655.  
  2656. });
  2657.  
  2658. }, {
  2659. rootMargin: `0px`, // refer to css margin-top:-30vh
  2660. threshold: [0]
  2661. })
  2662. sVideosITO.observe(endPosDOM);
  2663. } else {
  2664. sVideosITO.disconnect();
  2665. sVideosITO.observe(endPosDOM);
  2666. }
  2667.  
  2668.  
  2669. }
  2670.  
  2671.  
  2672. function fixTabs() {
  2673.  
  2674. if (!scriptEnable) return;
  2675.  
  2676. let queryElement = document.querySelector('*:not(#tab-videos) > #related.ytd-watch-flexy > ytd-watch-next-secondary-results-renderer');
  2677.  
  2678. let isRelocated = !!queryElement;
  2679.  
  2680. if (isRelocated) {
  2681.  
  2682. _console.log(3202, 2)
  2683.  
  2684. let relatedElm = closestDOM.call(queryElement, '#related.ytd-watch-flexy'); // NOT NULL
  2685.  
  2686. let right_tabs = document.querySelector('#right-tabs'); // can be NULL
  2687.  
  2688. let tab_videos = right_tabs ? querySelectorFromAnchor.call(right_tabs, "#tab-videos") : null; // can be NULL
  2689.  
  2690. if (tab_videos !== null) {
  2691.  
  2692. _console.log(3202, 4)
  2693.  
  2694. let target_container = document.querySelector('ytd-watch-flexy:not([is-two-columns_]) #primary-inner.ytd-watch-flexy, ytd-watch-flexy[is-two-columns_] #secondary-inner.ytd-watch-flexy')
  2695. if (target_container) elementAppend.call(target_container, right_tabs) // last-child
  2696.  
  2697. elementAppend.call(tab_videos, relatedElm);
  2698. // no any other element set these attr. only init / relocation
  2699. relatedElm.setAttribute('placeholder-for-youtube-play-next-queue', '')
  2700. relatedElm.setAttribute('placeholder-videos', '')
  2701.  
  2702. makeVideosAutoLoad2();
  2703.  
  2704. }
  2705.  
  2706. }
  2707.  
  2708.  
  2709. /** @type {HTMLElement | null} */
  2710. let chatroom = null;
  2711. if (chatroom = document.querySelector('*:not([data-positioner="before|#chat"]) + ytd-live-chat-frame#chat, ytd-live-chat-frame#chat:first-child')) {
  2712.  
  2713. let pHolderElm = document.querySelector('tabview-view-pholder[data-positioner="before|#chat"]');
  2714. if (pHolderElm) pHolderElm.remove();
  2715.  
  2716. if (document.querySelector('.YouTubeLiveFilledUpView')) {
  2717. // no relocation
  2718. } else {
  2719.  
  2720. let rightTabs = document.querySelector('#right-tabs');
  2721. if (rightTabs) {
  2722. insertBeforeTo(chatroom, rightTabs);
  2723. }
  2724.  
  2725. }
  2726.  
  2727. if (!pHolderElm) {
  2728. pHolderElm = document.createElement('tabview-view-pholder');
  2729. pHolderElm.setAttribute('data-positioner', 'before|#chat');
  2730. }
  2731.  
  2732. insertBeforeTo(pHolderElm, chatroom)
  2733.  
  2734. }
  2735.  
  2736.  
  2737. }
  2738.  
  2739. async function isDocumentInFullScreenMode() {
  2740. return document.fullscreenElement !== null;
  2741. }
  2742. async function energizedByVideoTimeUpdate() {
  2743.  
  2744. const isFullscreen = await isDocumentInFullScreenMode();
  2745. if (isFullscreen) return;
  2746.  
  2747. // force browser to load the videostream during playing (primarily for music videos)
  2748. // both background and foreground
  2749.  
  2750. _updateTimeAccum++;
  2751.  
  2752. if ((_updateTimeAccum + _viTimeNum) % 11 === 0) {
  2753. // console.log(document.querySelector('video').currentTime) // 2.55, 2.64, 3.12, ...
  2754. // about 2.66s
  2755.  
  2756. if (_viTimeNum > 211) {
  2757. // around 30.9s ~ 31.9s
  2758. _viTimeNum = 200;
  2759. _updateTimeAccum = (_updateTimeAccum % 8) + 1; // reset to 1 ~ 8
  2760. postMessage({ tabviewEnergized: true }, 'https://www.youtube.com'); // post message to make alive
  2761. }
  2762.  
  2763. document.head.dataset.viTime = `${_viTimeNum + 1}`;
  2764. await Promise.resolve(0)
  2765. _viTimeNum = +document.head.dataset.viTime || 0;
  2766. }
  2767.  
  2768.  
  2769. }
  2770.  
  2771. function autoCompletePosCreate(){
  2772. let positioner = document.createElement("tabview-view-autocomplete-pos");
  2773. let oldPositioner = document.querySelector("tabview-view-autocomplete-pos");
  2774. if(oldPositioner) oldPositioner.remove();
  2775. return positioner
  2776. }
  2777.  
  2778. function handlerAutoCompleteExist() {
  2779. // Youtube - Search While Watching Video
  2780.  
  2781. /** @type {HTMLElement} */
  2782. let searchBox, autoComplete;
  2783. searchBox = this;
  2784. this.removeEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false)
  2785. let domId = this.getAttribute('data-autocomplete-results-id')
  2786.  
  2787. autoComplete = document.querySelector(`[data-autocomplete-input-id="${domId}"]`)
  2788.  
  2789. if (!domId || !searchBox) return;
  2790.  
  2791. let positioner = searchBox.nextSibling;
  2792. if (positioner) {
  2793. if (positioner.nodeName.toLowerCase() !== "tabview-view-autocomplete-pos") {
  2794. positioner = autoCompletePosCreate();
  2795. insertAfterTo(positioner, searchBox);
  2796. }
  2797. } else {
  2798. positioner = autoCompletePosCreate();
  2799. prependTo(positioner, searchBox.parentNode);
  2800. }
  2801. prependTo(autoComplete, positioner);
  2802.  
  2803. setupSearchBox(searchBox, positioner);
  2804.  
  2805.  
  2806. }
  2807.  
  2808. async function setupSearchBox(searchBox, positioner) {
  2809.  
  2810. let mb = getComputedStyle(searchBox).marginBottom
  2811. let h = searchBox.offsetHeight + 'px'
  2812.  
  2813. positioner.style.setProperty('--tyt-swwv-searchbox-mb', mb)
  2814. positioner.style.setProperty('--tyt-swwv-searchbox-h', h)
  2815.  
  2816. mtf_autocomplete_search()
  2817.  
  2818. }
  2819.  
  2820. function mtf_autocomplete_search() {
  2821. // Youtube - Search While Watching Video
  2822.  
  2823. /** @type {HTMLElement | null} */
  2824. const ytdFlexyElm = es.ytdFlexy;
  2825. if (!scriptEnable || !ytdFlexyElm) return;
  2826.  
  2827. const autocomplete = querySelectorFromAnchor.call(ytdFlexyElm, '[placeholder-for-youtube-play-next-queue] input#suggestions-search + tabview-view-autocomplete-pos > .autocomplete-suggestions[data-autocomplete-input-id]:not([position-fixed-by-tabview-youtube])')
  2828.  
  2829. if (autocomplete) {
  2830.  
  2831. const searchBox = document.querySelector('[placeholder-for-youtube-play-next-queue] input#suggestions-search')
  2832.  
  2833.  
  2834. if (searchBox) {
  2835.  
  2836. const rAutoComplete = mWeakRef(autocomplete);
  2837.  
  2838. function setVisible(autocomplete, b) {
  2839. autocomplete.style.display = (b ? 'block' : 'none');
  2840. }
  2841.  
  2842. function isContentNotEmpty(searchbox, autocomplete) {
  2843. return (searchbox.value || '').length > 0 && (autocomplete.textContent || '').length > 0;
  2844. }
  2845.  
  2846. autocomplete.parentNode.setAttribute('position-fixed-by-tabview-youtube', '');
  2847. autocomplete.setAttribute('position-fixed-by-tabview-youtube', '');
  2848. autocomplete.setAttribute('userscript-scrollbar-render', '')
  2849.  
  2850. //let cancelClickToggle = false;
  2851.  
  2852. if (!searchBox.hasAttribute('is-set-click-to-toggle')) {
  2853. searchBox.setAttribute('is-set-click-to-toggle', '')
  2854.  
  2855. searchBox.addEventListener('click', function () {
  2856.  
  2857. Promise.resolve(0).then(() => {
  2858.  
  2859. const autocomplete = kRef(rAutoComplete);
  2860.  
  2861. if (!autocomplete) return;
  2862.  
  2863. const isNotEmpty = isContentNotEmpty(this, autocomplete);
  2864.  
  2865. if (isNotEmpty) {
  2866.  
  2867. let elmVisible = isDOMVisible(autocomplete);
  2868.  
  2869. if (elmVisible) {
  2870. setVisible(autocomplete, false)
  2871. }
  2872. else {
  2873. setVisible(autocomplete, true)
  2874. }
  2875.  
  2876. }
  2877.  
  2878. })
  2879.  
  2880. }, bubblePassive)
  2881.  
  2882. let cacheScrollIntoView = null;
  2883. let rafID = 0;
  2884. searchBox.addEventListener('keydown', function (evt) {
  2885. //cancelClickToggle = true;
  2886. switch (evt.code) {
  2887. case 'ArrowUp':
  2888. case 'ArrowDown':
  2889.  
  2890. let t = Date.now();
  2891. if (rafID === 0) {
  2892. rafID = requestAnimationFrame(() => {
  2893. rafID = 0;
  2894. let d = Date.now();
  2895. if (d - t > 300) return;
  2896.  
  2897. const autocomplete = kRef(rAutoComplete);
  2898.  
  2899. let selected = querySelectorFromAnchor.call(autocomplete, '.autocomplete-suggestion.selected');
  2900. let bool = selected && selected !== cacheScrollIntoView;
  2901. cacheScrollIntoView = selected;
  2902. if (bool) {
  2903.  
  2904. try {
  2905. selected.scrollIntoView({ block: "nearest", inline: "nearest" });
  2906. } catch (e) { }
  2907.  
  2908. }
  2909.  
  2910. })
  2911. }
  2912. default:
  2913. //
  2914. }
  2915.  
  2916.  
  2917. }, bubblePassive)
  2918.  
  2919. searchBox.addEventListener('tyt-autocomplete-suggestions-change', function (evt) {
  2920.  
  2921. //cancelClickToggle = true;
  2922. if (evt.target !== document.activeElement) return;
  2923. setTimeout(() => {
  2924. const autocomplete = document.querySelector(`.autocomplete-suggestions[data-autocomplete-input-id="${this.getAttribute('data-autocomplete-results-id')}"]`);
  2925. if (!autocomplete) return;
  2926. const isNotEmpty = isContentNotEmpty(this, autocomplete);
  2927. if (isNotEmpty) {
  2928. // dont detect visibility; just set to visible
  2929. setVisible(autocomplete, true);
  2930. }
  2931. }, 20);
  2932.  
  2933. }, bubblePassive)
  2934.  
  2935. }
  2936.  
  2937. }
  2938.  
  2939. }
  2940.  
  2941. }
  2942.  
  2943. const insertBeforeTo = HTMLElement.prototype.before ? (elm, target) => {
  2944. if (!target || !elm) return null;
  2945. // using before
  2946. HTMLElement.prototype.before.call(target, elm);
  2947. return true;
  2948. } : (elm, target) => {
  2949. if (!target || !elm) return null;
  2950. // using insertBefore
  2951. try {
  2952. HTMLElement.prototype.insertBefore.call(target.parentNode, elm, target);
  2953. return true;
  2954. } catch (e) {
  2955. console.log('element insert failed in old browser CE')
  2956. }
  2957. return false;
  2958. }
  2959.  
  2960. const insertAfterTo = HTMLElement.prototype.after ? (elm, target) => {
  2961. if (!target || !elm) return null;
  2962. // using after
  2963. HTMLElement.prototype.after.call(target, elm);
  2964. return true;
  2965. } : (elm, target) => {
  2966. if (!target || !elm) return null;
  2967. // using insertBefore
  2968. try {
  2969. HTMLElement.prototype.insertBefore.call(target.parentNode, elm, target.nextSibling);
  2970. return true;
  2971. } catch (e) {
  2972. console.log('element insert failed in old browser CE')
  2973. }
  2974. return false;
  2975. }
  2976.  
  2977. const prependTo = HTMLElement.prototype.prepend ? (elm, target) => {
  2978. if (!target || !elm) return null;
  2979. // using prepend
  2980. HTMLElement.prototype.prepend.call(target, elm);
  2981. return true;
  2982. } : (elm, target) => {
  2983. if (!target || !elm) return null;
  2984. // using insertBefore
  2985. try {
  2986. HTMLElement.prototype.insertBefore.call(target, elm, target.firstChild);
  2987. return true;
  2988. } catch (e) {
  2989. console.log('element insert failed in old browser CE')
  2990. }
  2991. return false;
  2992. }
  2993.  
  2994. const appends = HTMLElement.prototype.append ? (target, ...args) => {
  2995. HTMLElement.prototype.append.call(target, ...args);
  2996. return true;
  2997. } : (target, ...args) => {
  2998. for (const s of args) {
  2999. target.appendChild(s)
  3000. }
  3001. return true;
  3002. }
  3003.  
  3004.  
  3005. // css animation check for element relocation
  3006. function mtf_liveChatBtnF(node) {
  3007.  
  3008. if (!node || node.nodeType !== 1) return;
  3009.  
  3010. /** @type {HTMLElement | null} */
  3011. const ytdFlexyElm = es.ytdFlexy;
  3012. if (!scriptEnable || !ytdFlexyElm) return;
  3013.  
  3014. let button = node;
  3015.  
  3016. if (button) {
  3017. prependTo(button, button.parentNode);
  3018. }
  3019.  
  3020.  
  3021. }
  3022.  
  3023.  
  3024. function getWrapper(wrapperId) {
  3025. let wrapper = document.getElementById(wrapperId);
  3026. if (!wrapper) {
  3027. wrapper = document.createElement('div');
  3028. wrapper.id = wrapperId;
  3029. }
  3030. return wrapper;
  3031. }
  3032.  
  3033. // continuous check for element relocation
  3034. // fired at begining & window resize, etc
  3035. // might moved to #primary
  3036. function mtf_append_playlist(/** @type {HTMLElement | null} */ playlist) {
  3037.  
  3038. if (playlist === null) {
  3039. playlist = document.querySelector('ytd-watch-flexy[playlist] *:not(#tabview-playlist-wrapper) > ytd-playlist-panel-renderer.style-scope.ytd-watch-flexy#playlist:not(.ytd-miniplayer)');
  3040. // this playlist is highly possible to have '#items'
  3041. if (!playlist) return;
  3042. }
  3043.  
  3044. /** @type {HTMLElement | null} */
  3045. const ytdFlexyElm = es.ytdFlexy;
  3046. if (!scriptEnable || !ytdFlexyElm) return;
  3047.  
  3048. let items = querySelectorFromAnchor.call(playlist, "*:not(#tabview-playlist-wrapper) > ytd-playlist-panel-renderer#playlist:not(.ytd-miniplayer) #items.ytd-playlist-panel-renderer:not(:empty)");
  3049.  
  3050. if (items !== null && playlist.nodeName.toUpperCase() === 'YTD-PLAYLIST-PANEL-RENDERER') {
  3051.  
  3052. let tab_list = document.querySelector("#tab-list");
  3053.  
  3054. if (!tab_list) return;
  3055.  
  3056. let w = getWrapper("tabview-playlist-wrapper");
  3057. let docFrag = new DocumentFragment();
  3058. // avoid immediate reflow for append playlist before append to tab_list
  3059. elementAppend.call(docFrag, w);
  3060. elementAppend.call(w, playlist);
  3061. elementAppend.call(tab_list, docFrag);
  3062. docFrag = null;
  3063. w = null;
  3064.  
  3065. }
  3066. }
  3067.  
  3068.  
  3069. function getCountHText(elm) {
  3070. return `${pageFetchedDataVideoId || 0}...${elm.textContent}`
  3071. }
  3072.  
  3073. // content fix - info & playlist
  3074. // fired at begining, and keep for in case any change
  3075. function mtf_fix_details() {
  3076.  
  3077. if (!scriptEnable) return Promise.resolve(0); // in case
  3078.  
  3079. return Promise.all([
  3080. new Promise(resolve => {
  3081.  
  3082.  
  3083. let contentToggleBtn = document.querySelector('ytd-watch-flexy #tab-info ytd-expander tp-yt-paper-button#less.ytd-expander:not([hidden]), #tab-info ytd-expander tp-yt-paper-button#more.ytd-expander:not([hidden])');
  3084.  
  3085. if (contentToggleBtn) {
  3086.  
  3087. (() => {
  3088. const domElement = contentToggleBtn;
  3089. contentToggleBtn = null;
  3090. // if(!domElement.parentElement) return; // not working in pseudo custom element - parentNode = documentFragment
  3091. const expander = closestDOM.call(domElement, 'ytd-watch-flexy #tab-info ytd-expander')
  3092.  
  3093. if (!expander || expander.nodeType !== 1) return; // checking whether it is still on the page
  3094.  
  3095. if (expander.style.getPropertyValue('--ytd-expander-collapsed-height')) {
  3096. expander.style.setProperty('--ytd-expander-collapsed-height', '')
  3097. }
  3098. nativeCall(expander, [
  3099. { 'property': 'canToggleJobId', 'value': 1 }, // false disable calculateCanCollapse in childrenChanged
  3100. { 'property': 'alwaysToggleable', 'value': false }, // this is checked in childrenChanged
  3101. { 'property': 'recomputeOnResize', 'value': false }, // no need to check toggleable
  3102. { 'property': 'isToggled', 'value': true }, // show full content
  3103. { 'property': 'canToggle', 'value': false }, // hide show more or less btn
  3104. { 'property': 'collapsedHeight', 'value': 999999 } // disable collapsed height check
  3105. ])
  3106.  
  3107. })();
  3108. }
  3109.  
  3110. resolve();
  3111.  
  3112.  
  3113. }),
  3114.  
  3115. new Promise(resolve => {
  3116.  
  3117.  
  3118. let strcturedInfo = document.querySelector('ytd-watch-flexy #tab-info ytd-structured-description-content-renderer.style-scope.ytd-video-secondary-info-renderer[hidden]')
  3119. if (strcturedInfo) {
  3120.  
  3121. (() => {
  3122.  
  3123. strcturedInfo.removeAttribute('hidden');
  3124.  
  3125.  
  3126. setTimeout(() => {
  3127.  
  3128.  
  3129. let e = closestDOM.call(strcturedInfo, 'ytd-watch-flexy #tab-info ytd-expander');
  3130.  
  3131. if (!e) return;
  3132. let s = querySelectorAllFromAnchor.call(e, '#tab-info .more-button.style-scope.ytd-video-secondary-info-renderer[role="button"]');
  3133. if (s.length === 1) {
  3134. let sp = s[0].parentNode
  3135. if (sp.nodeName.toUpperCase() === 'TP-YT-PAPER-BUTTON') {
  3136.  
  3137. sp.click();
  3138. }
  3139. }
  3140.  
  3141. }, 300)
  3142.  
  3143. })();
  3144. }
  3145.  
  3146.  
  3147. resolve();
  3148.  
  3149. }),
  3150.  
  3151. new Promise(resolve => {
  3152.  
  3153.  
  3154. // just in case the playlist is collapsed
  3155. let playlist = document.querySelector('#tab-list ytd-playlist-panel-renderer#playlist')
  3156. if (playlist && playlist.matches('[collapsed], [collapsible]')) {
  3157.  
  3158. (() => {
  3159.  
  3160. const domElement = playlist;
  3161. playlist = null;
  3162. // if(!domElement.parentElement || domElement.nodeType!==1) return; // not working in pseudo custom element - parentNode = documentFragment
  3163. const tablist = closestDOM.call(domElement, 'ytd-watch-flexy #tab-list')
  3164.  
  3165. if (!tablist || tablist.nodeType !== 1) return; // checking whether it is still on the page
  3166.  
  3167. if (domElement.hasAttribute('collapsed')) wAttr(domElement, 'collapsed', false);
  3168. if (domElement.hasAttribute('collapsible')) wAttr(domElement, 'collapsible', false);
  3169. })();
  3170. }
  3171.  
  3172. resolve();
  3173.  
  3174.  
  3175. }),
  3176.  
  3177. new Promise(resolve => {
  3178.  
  3179.  
  3180. let subscribersCount = document.querySelector('#primary.ytd-watch-flexy #below ytd-watch-metadata #owner #owner-sub-count');
  3181.  
  3182. if (subscribersCount) {
  3183. if (!subscribersCount.hasAttribute('title')) {
  3184. // assume YouTube native coding would not implement [title]
  3185.  
  3186. let ytdWatchMetaDataElm = closestDOM.call(subscribersCount, 'body #primary.ytd-watch-flexy #below ytd-watch-metadata:not([tabview-uploader-hover])');
  3187. if (ytdWatchMetaDataElm) {
  3188. ytdWatchMetaDataElm.setAttribute('tabview-uploader-hover', '')
  3189. let _h = 0;
  3190. ytdWatchMetaDataElm.addEventListener('transitionend', function (evt) {
  3191. // no css selector rule required; no delay js function call required
  3192.  
  3193. let selection = evt.propertyName === 'background-position-y' ? 1 : evt.propertyName === 'background-position-x' ? 2 : 0;
  3194. if(selection && evt.target){
  3195. let cssRoot = this; // no querySelector is required
  3196. if(cssRoot.classList.contains('tabview-uploader-hover')){
  3197. if(evt.target.id!=='owner') return;
  3198. cssRoot.classList.toggle('tabview-uploader-hover', false);
  3199. }
  3200. }
  3201.  
  3202. if (selection === 1) { // string comparision only
  3203.  
  3204. // If the cursor initially stayed at the owner info area,
  3205. // the mechanism will be broken
  3206. // so implement the true leave detection at their parent
  3207.  
  3208. let isHover = evt.elapsedTime < 0.03; // 50ms @normal; 10ms @hover;
  3209.  
  3210. let cssRoot = this; // no querySelector is required
  3211. if (!isHover) {
  3212. // 50ms is slowest than sub element leave effect
  3213. if (_h > 0) cssRoot.classList.toggle('tabview-uploader-hover', false) // even the order is incorrect, removal of class is safe.
  3214. _h = 0; // in case
  3215. } else if (isHover) {
  3216. // 10ms is faster than sub element hover effect
  3217. // no removal of class in case browser's transition implemention order is incorrect
  3218. _h = 0; // in case
  3219. }
  3220.  
  3221. } else if (selection === 2) { // string comparision only
  3222.  
  3223. //from one element to another element; hover effect of 2nd element transition end first.
  3224. // _h: 0 -> 1 -> 2 -> 1
  3225.  
  3226. let isHover = evt.elapsedTime < 0.03; // 40ms @normal; 20ms @hover;
  3227. if (isHover) _h++; else _h--;
  3228. let cssRoot = this; // no querySelector is required
  3229. if (_h <= 0) {
  3230. cssRoot.classList.toggle('tabview-uploader-hover', false)
  3231. _h = 0; // in case
  3232. } else if (_h === 1) {
  3233. cssRoot.classList.toggle('tabview-uploader-hover', true)
  3234. }
  3235.  
  3236. }
  3237.  
  3238. }, capturePassive) // capture the hover effect inside the cssRoot
  3239. }
  3240.  
  3241. }
  3242. subscribersCount.setAttribute('title', subscribersCount.textContent); // set at every page update
  3243.  
  3244. }
  3245.  
  3246. resolve();
  3247.  
  3248. })
  3249.  
  3250.  
  3251. ]);
  3252.  
  3253.  
  3254. }
  3255.  
  3256.  
  3257. const innerCommentsFuncs = [
  3258. // comments
  3259. function () {
  3260.  
  3261. let elm = kRef(this.elm);
  3262. _console.log(2907, 1, !!elm)
  3263. if (!elm) return;
  3264.  
  3265. let span = document.querySelector("span#tyt-cm-count")
  3266. let r = '0';
  3267. let txt = elm.textContent
  3268. if (typeof txt == 'string') {
  3269. let m = txt.match(/[\d\,\.\s]+/)
  3270. if (m) {
  3271. let d = +m[0].replace(/\D+/g,'');
  3272. let ds = d.toLocaleString(document.documentElement.lang);
  3273. let rtxt = txt.replace(ds, '')
  3274. if(rtxt !== txt && !/\d/.test(rtxt)){
  3275. r = ds;
  3276. }
  3277. }
  3278. }
  3279.  
  3280. if (span) {
  3281. let tab_btn = closestDOM.call(span, '.tab-btn[tyt-tab-content="#tab-comments"]')
  3282. if (tab_btn) tab_btn.setAttribute('loaded-comment', 'normal')
  3283. span.textContent = r;
  3284. }
  3285.  
  3286. setCommentSection(1);
  3287. m_last_count = getCountHText(elm);
  3288. _console.log(2907, 2, m_last_count)
  3289. return true;
  3290. },
  3291. // message
  3292. function () {
  3293.  
  3294. let elm = kRef(this.elm);
  3295. _console.log(2907, 2, !!elm)
  3296. if (!elm) return;
  3297.  
  3298. let span = document.querySelector("span#tyt-cm-count")
  3299. if (span) {
  3300. let tab_btn = closestDOM.call(span, '.tab-btn[tyt-tab-content="#tab-comments"]')
  3301. if (tab_btn) tab_btn.setAttribute('loaded-comment', 'message')
  3302. span.textContent = '\u200B';
  3303. }
  3304.  
  3305. setCommentSection(1);
  3306. m_last_count = getCountHText(elm);
  3307. _console.log(2907, 2, m_last_count)
  3308. return true;
  3309. }
  3310. ]
  3311.  
  3312.  
  3313. let innerDOMCommentsCountTextCache = null;
  3314. /**
  3315. *
  3316. * @param {boolean} [requireResultCaching]
  3317. * @returns
  3318. */
  3319. function innerDOMCommentsCountLoader(requireResultCaching) {
  3320. // independent of tabs initialization
  3321. // f() is executed after tabs being ready
  3322.  
  3323. /** @type {HTMLElement | null} */
  3324. const ytdFlexyElm = es.ytdFlexy;
  3325. if (!scriptEnable || !ytdFlexyElm) return;
  3326.  
  3327. _console.log(3434, pageType)
  3328. if (pageType !== 'watch') return;
  3329.  
  3330.  
  3331. /** @type {Array<HTMLElement>} */
  3332. let qmElms = [...document.querySelectorAll('ytd-comments#comments #count.ytd-comments-header-renderer, ytd-comments#comments ytd-item-section-renderer.ytd-comments#sections #header ~ #contents > ytd-message-renderer.ytd-item-section-renderer')]
  3333.  
  3334.  
  3335. const eTime = +`${Date.now() - mTime}00`;
  3336.  
  3337. let res = new Array(qmElms.length);
  3338. res.newFound = false;
  3339.  
  3340.  
  3341. let ci = 0;
  3342. let latest = -1;
  3343.  
  3344. let retrival = cmTime;
  3345. cmTime = eTime;
  3346.  
  3347. for (const qmElm of qmElms) {
  3348.  
  3349. let mgz = 0
  3350. if (qmElm.id === 'count') {
  3351. //#count.ytd-comments-header-renderer
  3352. mgz = 1;
  3353.  
  3354. } else if ((qmElm.textContent || '').trim()) {
  3355. //ytd-message-renderer.ytd-item-section-renderer
  3356. mgz = 2;
  3357. // it is possible to get the message before the header generation.
  3358. // sample link - https://www.youtube.com/watch?v=PVUZ8Nvr1ic
  3359. // sample link - https://www.youtube.com/watch?v=yz8AiQc1Bk8
  3360. }
  3361.  
  3362. if (mgz > 0) {
  3363.  
  3364.  
  3365. let lastUpdate = loadedCommentsDT.get(qmElm) || 0;
  3366. let diff = retrival - lastUpdate
  3367. _console.log(2907, diff)
  3368. let isNew = (diff > 4 || diff < -4);
  3369. if (!isNew) {
  3370. loadedCommentsDT.set(qmElm, eTime);
  3371. } else {
  3372. loadedCommentsDT.set(qmElm, eTime + 1);
  3373. res.newFound = true;
  3374. latest = ci;
  3375. }
  3376.  
  3377. res[ci] = {
  3378. elm: mWeakRef(qmElm),
  3379. isNew: isNew,
  3380. isLatest: false, //set afterwards
  3381. f: innerCommentsFuncs[mgz - 1]
  3382. }
  3383.  
  3384. if (DEBUG_LOG) {
  3385. res[ci].status = mgz;
  3386. res[ci].text = qmElm.textContent;
  3387. }
  3388.  
  3389. ci++;
  3390.  
  3391. }
  3392.  
  3393. }
  3394. if (res.length > ci) res.length = ci;
  3395.  
  3396. if (latest >= 0) {
  3397.  
  3398. res[latest].isLatest = true;
  3399.  
  3400.  
  3401. let elm = kRef(res[latest].elm);
  3402. if (elm)
  3403. innerDOMCommentsCountTextCache = elm.textContent;
  3404.  
  3405. } else if (res.length === 1) {
  3406.  
  3407. let qmElm = kRef(res[0].elm);
  3408. let t = null;
  3409. if (qmElm) {
  3410.  
  3411. let t = qmElm.textContent;
  3412. if (t !== innerDOMCommentsCountTextCache) {
  3413.  
  3414.  
  3415. loadedCommentsDT.set(qmElm, eTime + 1);
  3416. res.newFound = true;
  3417.  
  3418. res[0].isNew = true;
  3419. latest = 0;
  3420.  
  3421. res[latest].isLatest = true;
  3422.  
  3423. }
  3424.  
  3425. innerDOMCommentsCountTextCache = t;
  3426.  
  3427.  
  3428. }
  3429.  
  3430.  
  3431. }
  3432.  
  3433.  
  3434. _console.log(2908, res, Q.comments_section_loaded)
  3435.  
  3436. _console.log(696, res.map(e => ({
  3437.  
  3438. text: kRef(e.elm).textContent,
  3439. isNew: e.isNew,
  3440. isLatest: e.isLatest
  3441.  
  3442. })))
  3443.  
  3444. if(requireResultCaching) {
  3445. resultCommentsCountCaching(res);
  3446. }
  3447.  
  3448. return res;
  3449.  
  3450. }
  3451.  
  3452. function restoreFetching() {
  3453.  
  3454.  
  3455. if (mtf_forceCheckLiveVideo_disable === 2) return;
  3456.  
  3457.  
  3458. const ytdFlexyElm = es.ytdFlexy;
  3459. if (!ytdFlexyElm) return;
  3460.  
  3461. _console.log(2901)
  3462.  
  3463. if ((ytdFlexyElm.getAttribute('tyt-comments') || '').indexOf('K') >= 0) return;
  3464.  
  3465. _console.log(2902)
  3466.  
  3467. let visibleComments = querySelectorFromAnchor.call(ytdFlexyElm, 'ytd-comments#comments:not([hidden])')
  3468. if (!visibleComments) return;
  3469.  
  3470. _console.log(2903)
  3471.  
  3472.  
  3473. ytdFlexyElm.setAttribute('tyt-comments', 'Kz');
  3474.  
  3475. const tabBtn = document.querySelector('[tyt-tab-content="#tab-comments"]');
  3476. let span = querySelectorFromAnchor.call(tabBtn, 'span#tyt-cm-count');
  3477. tabBtn.removeAttribute('loaded-comment')
  3478. span.innerHTML = '';
  3479.  
  3480. if (tabBtn) {
  3481. tabBtn.classList.remove("tab-btn-hidden")
  3482. }
  3483.  
  3484. _console.log(2905)
  3485.  
  3486.  
  3487. }
  3488.  
  3489. function checkAndMakeNewCommentFetch(){
  3490. if (renderDeferred.resolved && Q.comments_section_loaded === 0 && fetchCounts.new && !fetchCounts.fetched) {
  3491. fetchCounts.new.f();
  3492. fetchCounts.fetched = true;
  3493. fetchCommentsFinished();
  3494. _console.log(9972, 'fetched = true')
  3495. }
  3496. }
  3497. function onCommentsReady(){
  3498. if (mtf_forceCheckLiveVideo_disable !== 2) {
  3499. if (document.querySelector(`ytd-comments#comments`).hasAttribute('hidden')) {
  3500. // unavailable but not due to live chat
  3501. _disableComments();
  3502. } else if (Q.comments_section_loaded === 0) {
  3503. getFinalComments();
  3504. }
  3505. }
  3506. }
  3507.  
  3508. const resultCommentsCountCaching = (res) => {
  3509. // update fetchCounts by res
  3510. // indepedent of previous state of fetchCounts
  3511. _console.log(2908, 10, res)
  3512. if (!res) return;
  3513. fetchCounts.count = res.length;
  3514. //if(fetchCounts.new && !document.documentElement.contains(fetchCounts.new.elm)) fetchCounts.new = null;
  3515. //if(fetchCounts.base && !document.documentElement.contains(fetchCounts.base.elm)) fetchCounts.base = null;
  3516. if (fetchCounts.new) return;
  3517. let newFound = res.newFound;
  3518. if (!newFound) {
  3519. if (res.length === 1) {
  3520. fetchCounts.base = res[0];
  3521. return false;
  3522. }
  3523. } else if (res.length === 1) {
  3524. fetchCounts.new = res[0];
  3525. return true;
  3526. } else if (res.length > 1) {
  3527. for (const entry of res) {
  3528. if (entry.isLatest === true && entry.isNew) {
  3529. fetchCounts.new = entry;
  3530. return true;
  3531. }
  3532. }
  3533. }
  3534. }
  3535.  
  3536. const domInit_comments = () => {
  3537.  
  3538.  
  3539. let comments = document.querySelector(`ytd-comments#comments:not([o3r-${sa_comments}])`);
  3540. if (!comments) return;
  3541.  
  3542. // once per {ytd-comments#comments} detection
  3543.  
  3544. const ytdFlexyElm = es.ytdFlexy;
  3545. if (!scriptEnable || !ytdFlexyElm) return;
  3546.  
  3547. _console.log(3901)
  3548.  
  3549. if (mtoVisibility_Comments.bindElement(comments)) {
  3550. mtoVisibility_Comments.observer.check(9);
  3551. }
  3552.  
  3553.  
  3554. };
  3555.  
  3556.  
  3557. const FP = {
  3558.  
  3559. mtf_attrPlaylist: (attrName, newValue) => {
  3560. //attr mutation checker - {ytd-playlist-panel-renderer#playlist} \single
  3561. //::attr ~ hidden
  3562. //console.log(1210)
  3563.  
  3564. _console.log(21311)
  3565. if (!scriptEnable) return;
  3566. if (pageType !== 'watch') return;
  3567. /** @type {HTMLElement|null} */
  3568. let cssElm = es.ytdFlexy;
  3569. if (!cssElm) return;
  3570.  
  3571. _console.log(21312)
  3572.  
  3573. let playlist = document.querySelector('#tab-list ytd-playlist-panel-renderer#playlist'); // can be null if it is manually triggered
  3574. let isAnyPlaylistExist = playlist && !playlist.hasAttribute('hidden');
  3575. const tabBtn = document.querySelector('[tyt-tab-content="#tab-list"]');
  3576. //console.log(1212.2, isPlaylistHidden, playlist.getAttribute('hidden'))
  3577. if (tabBtn) {
  3578. //console.log('attr playlist changed')
  3579. let isPlaylistTabHidden = tabBtn.classList.contains('tab-btn-hidden')
  3580. if (isPlaylistTabHidden && isAnyPlaylistExist) {
  3581. //console.log('attr playlist changed - no hide')
  3582. tabBtn.classList.remove("tab-btn-hidden");
  3583. } else if (!isPlaylistTabHidden && !isAnyPlaylistExist) {
  3584. //console.log('attr playlist changed - add hide')
  3585. hideTabBtn(tabBtn);
  3586. }
  3587. }
  3588. /* visible layout for triggering hidden removal */
  3589.  
  3590. },
  3591. mtf_attrComments: (attrName, newValue) => {
  3592. //attr mutation checker - {ytd-comments#comments} \single
  3593. //::attr ~ hidden
  3594.  
  3595. // *** consider this can happen immediately after pop state. timeout / interval might clear out.
  3596.  
  3597. renderDeferred.resolved && innerDOMCommentsCountLoader(true);
  3598. // this is triggered by mutationobserver, the comment count update might have ouccred
  3599.  
  3600. if (pageType !== 'watch') return;
  3601.  
  3602. let comments = document.querySelector('ytd-comments#comments')
  3603. const tabBtn = document.querySelector('[tyt-tab-content="#tab-comments"]');
  3604. if (!comments || !tabBtn) return;
  3605. let isCommentHidden = comments.hasAttribute('hidden')
  3606. //console.log('attr comments changed')
  3607.  
  3608.  
  3609. const ytdFlexyElm = es.ytdFlexy;
  3610. if (!scriptEnable || !ytdFlexyElm) return;
  3611.  
  3612. if (mtf_forceCheckLiveVideo_disable === 2) {
  3613.  
  3614. } else if (!isCommentHidden) {
  3615.  
  3616. ytdFlexyElm.setAttribute('tyt-comments', 'Kv');
  3617. if (!fetchCounts.fetched) {
  3618. emptyCommentSection();
  3619. }
  3620. //_console.log(9360, 71);
  3621. tabBtn.classList.remove("tab-btn-hidden") //if contains
  3622.  
  3623. } else if (isCommentHidden) {
  3624.  
  3625. ytdFlexyElm.setAttribute('tyt-comments', 'Kh');
  3626. if (pageType === 'watch' && Q.comments_section_loaded === 1) {
  3627. emptyCommentSection();
  3628. _console.log(9360, 72);
  3629. }
  3630.  
  3631. }
  3632.  
  3633.  
  3634. },
  3635.  
  3636. mtf_attrChatroom: (attrName, newValue) => {
  3637. //attr mutation checker - {ytd-live-chat-frame#chat} \single
  3638. //::attr ~ collapsed
  3639.  
  3640. const ytdFlexyElm = es.ytdFlexy;
  3641. if (!scriptEnable || !ytdFlexyElm) return;
  3642. if (pageType !== 'watch') return;
  3643.  
  3644. setToggleBtnTxt();
  3645.  
  3646. layoutStatusMutex.lockWith(unlock => {
  3647.  
  3648. const chatBlock = document.querySelector('ytd-live-chat-frame#chat')
  3649. /** @type {HTMLElement | null} */
  3650. const cssElm = es.ytdFlexy;
  3651.  
  3652. if (!chatBlock || !cssElm) {
  3653. unlock();
  3654. return;
  3655. }
  3656.  
  3657. if (pageType !== 'watch') {
  3658. unlock();
  3659. return;
  3660. }
  3661.  
  3662. let newAttrV = '';
  3663. //mtf_attrChatroom => chat exist => tyt-chat non-null
  3664.  
  3665. let isCollapsed = !!chatBlock.hasAttribute('collapsed');
  3666.  
  3667. let currentAttr = cssElm.getAttribute('tyt-chat');
  3668.  
  3669. if (currentAttr !== null) { //string // [+-]?[az]+[az\$]+
  3670. let isPlusMinus = currentAttr.charCodeAt(0) < 46; // 43 OR 45
  3671. if (isPlusMinus) newAttrV = currentAttr.substring(1);
  3672. }
  3673.  
  3674. if (isCollapsed) newAttrV = `-${newAttrV}`;
  3675. if (!isCollapsed) newAttrV = `+${newAttrV}`;
  3676.  
  3677. wAttr(cssElm, 'tyt-chat', newAttrV);
  3678.  
  3679.  
  3680. if (typeof newAttrV === 'string' && !isCollapsed) lstTab.lastPanel = '#chatroom';
  3681.  
  3682. if (!isCollapsed && isAnyActiveTab() && isWideScreenWithTwoColumns() && !isTheater()) {
  3683. switchTabActivity(null);
  3684. timeline.setTimeout(unlock, 40);
  3685. } else {
  3686. unlock();
  3687. }
  3688.  
  3689. if (isCollapsed) {
  3690. chatBlock.removeAttribute('tyt-iframe-loaded');
  3691. // console.log(922,1)
  3692. // buggy; this section might not be correctly executed.
  3693. // guess no collaspe change but still iframe will distory and reload.
  3694. let btn = document.querySelector('tyt-iframe-popup-btn')
  3695. if(btn) btn.remove();
  3696. }
  3697.  
  3698. })
  3699.  
  3700.  
  3701. },
  3702.  
  3703. mtf_attrEngagementPanel: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  3704. //attr mutation checker - {ytd-engagement-panel-section-list-renderer} \mutiple
  3705. //::attr ~ visibility
  3706.  
  3707. const cssElm = es.ytdFlexy;
  3708. if (!scriptEnable || !cssElm) return;
  3709. let found = null
  3710. if (mutations === 9) {
  3711. found = observer
  3712. } else {
  3713. if (document.querySelector('ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"]:not([hidden])')) {
  3714. // do nothing
  3715. } else {
  3716. mtoVisibility_EngagementPanel.clear(true)
  3717. storeLastPanel = null;
  3718. wAttr(cssElm, 'tyt-ep-visible', false);
  3719. }
  3720. return
  3721. }
  3722. let nextValue = engagement_panels_().value;
  3723. let previousValue = +cssElm.getAttribute('tyt-ep-visible') || 0;
  3724. if (nextValue === 0 || previousValue === nextValue) return
  3725. cssElm.setAttribute('tyt-ep-visible', nextValue);
  3726. lstTab.lastPanel = `#engagement-panel-${nextValue}`;
  3727. storeLastPanel = mWeakRef(found)
  3728. let tabsDeferredSess = pageSession.session();
  3729. if (!scriptEnable && tabsDeferred.resolved) { }
  3730. else tabsDeferred.debounce(() => {
  3731. if (!tabsDeferredSess.isValid) return;
  3732. tabsDeferredSess = null;
  3733. if (es.storeLastPanel !== found) return
  3734. layoutStatusMutex.lockWith(unlock => {
  3735. if (es.storeLastPanel === found && whenEngagemenetPanelVisible()) {
  3736. timeline.setTimeout(unlock, 40);
  3737. } else {
  3738. unlock();
  3739. }
  3740. })
  3741. })
  3742. }
  3743.  
  3744. }
  3745.  
  3746.  
  3747. function variableResets() {
  3748.  
  3749. // reset variables when it is confirmed a new page is loaded
  3750.  
  3751. lstTab =
  3752. {
  3753. lastTab: null, //tab-xxx
  3754. lastPanel: null,
  3755. last: null
  3756. };
  3757.  
  3758. scriptEnable = false;
  3759. ytdFlexy = null;
  3760. wls.layoutStatus = 0;
  3761.  
  3762. mtoVisibility_Playlist.clear(true)
  3763. mtoVisibility_Comments.clear(true)
  3764.  
  3765. mtoVisibility_Chatroom.clear(true)
  3766. mtoFlexyAttr.clear(true)
  3767.  
  3768.  
  3769. for (const elem of document.querySelectorAll('ytd-expander[tabview-expander-checked]')) {
  3770. elem.removeAttribute('tabview-expander-checked');
  3771. }
  3772.  
  3773. mtf_chatBlockQ = null;
  3774.  
  3775. }
  3776.  
  3777.  
  3778. function getWord(tag) {
  3779. return langWords[pageLang][tag] || langWords['en'][tag] || '';
  3780. }
  3781.  
  3782.  
  3783. function getTabsHTML() {
  3784.  
  3785. const sTabBtnVideos = `${svgElm(16, 16, 90, 90, svgVideos)}<span>${getWord('videos')}</span>`;
  3786. const sTabBtnInfo = `${svgElm(16, 16, 60, 60, svgInfo)}<span>${getWord('info')}</span>`;
  3787. const sTabBtnPlayList = `${svgElm(16, 16, 20, 20, svgPlayList)}<span>${getWord('playlist')}</span>`;
  3788.  
  3789. let str1 = `
  3790. <paper-ripple class="style-scope yt-icon-button">
  3791. <div id="background" class="style-scope paper-ripple" style="opacity:0;"></div>
  3792. <div id="waves" class="style-scope paper-ripple"></div>
  3793. </paper-ripple>
  3794. `;
  3795.  
  3796. let str_fbtns = `
  3797. <div class="font-size-right">
  3798. <div class="font-size-btn font-size-plus" tyt-di="8rdLQ">
  3799. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  3800. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  3801. <path d="M12 25H38M25 12V38"/>
  3802. </svg>
  3803. </div><div class="font-size-btn font-size-minus" tyt-di="8rdLQ">
  3804. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  3805. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  3806. <path d="M12 25h26"/>
  3807. </svg>
  3808. </div>
  3809. </div>
  3810. `.replace(/[\r\n]+/g, '');
  3811.  
  3812. const str_tabs = [
  3813. `<a id="tab-btn1" tyt-di="q9Kjc" tyt-tab-content="#tab-info" class="tab-btn">${sTabBtnInfo}${str1}${str_fbtns}</a>`,
  3814. `<a id="tab-btn3" tyt-di="q9Kjc" tyt-tab-content="#tab-comments" class="tab-btn">${svgElm(16, 16, 120, 120, svgComments)}<span id="tyt-cm-count"></span>${str1}${str_fbtns}</a>`,
  3815. `<a id="tab-btn4" tyt-di="q9Kjc" tyt-tab-content="#tab-videos" class="tab-btn">${sTabBtnVideos}${str1}${str_fbtns}</a>`,
  3816. `<a id="tab-btn5" tyt-di="q9Kjc" tyt-tab-content="#tab-list" class="tab-btn tab-btn-hidden">${sTabBtnPlayList}${str1}${str_fbtns}</a>`
  3817. ].join('');
  3818.  
  3819. let addHTML = `
  3820. <div id="right-tabs">
  3821. <tabview-view-pos-thead></tabview-view-pos-thead>
  3822. <header>
  3823. <div id="material-tabs">
  3824. ${str_tabs}
  3825. </div>
  3826. </header>
  3827. <div class="tab-content">
  3828. <div id="tab-info" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  3829. <div id="tab-comments" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  3830. <div id="tab-videos" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  3831. <div id="tab-list" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  3832. </div>
  3833. </div>
  3834. `;
  3835.  
  3836. return addHTML;
  3837.  
  3838. }
  3839.  
  3840. function getLang() {
  3841.  
  3842. let lang = 'en';
  3843. let htmlLang = ((document || 0).documentElement || 0).lang || '';
  3844. switch (htmlLang) {
  3845. case 'en':
  3846. case 'en-GB':
  3847. lang = 'en';
  3848. break;
  3849. case 'de':
  3850. case 'de-DE':
  3851. lang = 'du';
  3852. break;
  3853. case 'fr':
  3854. case 'fr-CA':
  3855. case 'fr-FR':
  3856. lang = 'fr';
  3857. break;
  3858. case 'zh-Hant':
  3859. case 'zh-Hant-HK':
  3860. case 'zh-Hant-TW':
  3861. lang = 'tw';
  3862. break;
  3863. case 'zh-Hans':
  3864. case 'zh-Hans-CN':
  3865. lang = 'cn';
  3866. break;
  3867. case 'ja':
  3868. case 'ja-JP':
  3869. lang = 'jp';
  3870. break;
  3871. case 'ko':
  3872. case 'ko-KR':
  3873. lang = 'kr';
  3874. break;
  3875. case 'ru':
  3876. case 'ru-RU':
  3877. lang = 'ru';
  3878. break;
  3879. default:
  3880. lang = 'en';
  3881. }
  3882. return lang;
  3883.  
  3884. }
  3885.  
  3886. function getLangForPage() {
  3887.  
  3888. let lang = getLang();
  3889.  
  3890. if (langWords[lang]) pageLang = lang; else pageLang = 'en';
  3891.  
  3892. }
  3893.  
  3894. // function checkEvtTarget(evt, nodeNames) {
  3895. // return nodeNames.includes((((evt || 0).target || 0).nodeName || 0));
  3896. // }
  3897.  
  3898. function pageCheck() {
  3899. // yt-player-updated
  3900. // yt-page-data-updated
  3901. // yt-watch-comments-ready - omitted
  3902. // [is-two-columns_] attr changed => layout changed
  3903.  
  3904. /** @type {HTMLElement | null} */
  3905. const ytdFlexyElm = es.ytdFlexy;
  3906. if (!scriptEnable || !ytdFlexyElm) return;
  3907.  
  3908. let comments = querySelectorFromAnchor.call(ytdFlexyElm, '#primary.ytd-watch-flexy ytd-watch-metadata ~ ytd-comments#comments');
  3909. if (comments) {
  3910. let tabComments = document.querySelector('#tab-comments');
  3911. if (tabComments) {
  3912. elementAppend.call(tabComments, comments);
  3913. }
  3914. }
  3915.  
  3916. mtf_append_playlist(null); // playlist relocated after layout changed
  3917.  
  3918. fixTabs();
  3919.  
  3920. mtf_autocomplete_search();
  3921.  
  3922. }
  3923.  
  3924. function globalHook(eventType, func) {
  3925. if (!func) return;
  3926.  
  3927. const count = (globalHook_hashs[eventType] || 0) + 1;
  3928.  
  3929. globalHook_hashs[eventType] = count;
  3930.  
  3931. const s = globalHook_symbols[count - 1] || (globalHook_symbols[count - 1] = Symbol());
  3932.  
  3933. document.addEventListener(eventType, function (evt) {
  3934. if (evt[s]) return;
  3935. evt[s] = true;
  3936. new Promise(() => {
  3937. func(evt);
  3938. })
  3939.  
  3940. }, capturePassive)
  3941.  
  3942. }
  3943.  
  3944. async function makeHeaderFloat() {
  3945. if (isMakeHeaderFloatCalled) return;
  3946. isMakeHeaderFloatCalled = true;
  3947. await Promise.resolve(0);
  3948.  
  3949.  
  3950. const [header, headerP, navElm] = await Promise.all([
  3951. new Promise(f => f(document.querySelector("#right-tabs header"))),
  3952.  
  3953. new Promise(f => f(document.querySelector("#right-tabs tabview-view-pos-thead"))),
  3954.  
  3955. new Promise(f => f(document.querySelector('#masthead-container, #masthead')))
  3956.  
  3957. ]);
  3958.  
  3959. let ito_dt = 0;
  3960. let ito = new IntersectionObserver((entries) => {
  3961.  
  3962. let xyStatus = null;
  3963.  
  3964. //console.log(entries);
  3965.  
  3966. let xRect = null;
  3967. let rRect = null;
  3968.  
  3969. for (const entry of entries) {
  3970. if (!entry.boundingClientRect || !entry.rootBounds) continue; // disconnected from DOM tree
  3971. if (!entry.isIntersecting && entry.boundingClientRect.y <= entry.rootBounds.top && entry.boundingClientRect.y < entry.rootBounds.bottom) {
  3972. xyStatus = 2;
  3973. xRect = entry.boundingClientRect;
  3974. rRect = entry.rootBounds;
  3975. } else if (entry.isIntersecting && entry.boundingClientRect.y >= entry.rootBounds.top && entry.boundingClientRect.y < entry.rootBounds.bottom) {
  3976. xyStatus = 1;
  3977. xRect = entry.boundingClientRect;
  3978. rRect = entry.rootBounds;
  3979. }
  3980. }
  3981. let p = wls.layoutStatus;
  3982. //console.log(document.documentElement.clientWidth)
  3983. if (xyStatus !== null) {
  3984.  
  3985. if (xyStatus === 2 && isStickyHeaderEnabled === true) {
  3986.  
  3987. } else if (xyStatus === 1 && isStickyHeaderEnabled === false) {
  3988.  
  3989. } else {
  3990. singleColumnScrolling2(xyStatus, xRect.width, {
  3991. left: xRect.left,
  3992. right: rRect.width - xRect.right
  3993. });
  3994. }
  3995.  
  3996. }
  3997.  
  3998. let tdt = Date.now();
  3999. ito_dt = tdt;
  4000. setTimeout(() => {
  4001. if (ito_dt !== tdt) return;
  4002. if (p !== wls.layoutStatus) singleColumnScrolling();
  4003. }, 300)
  4004.  
  4005. },
  4006. {
  4007. rootMargin: `0px 0px 0px 0px`,
  4008. threshold: [0]
  4009. })
  4010.  
  4011. ito.observe(headerP)
  4012.  
  4013. }
  4014.  
  4015. function checkPlaylistForInitialization() {
  4016. // if the page url is with playlist; renderer event might not occur.
  4017.  
  4018. // playlist already added to dom; this is to set the visibility event and change hidden status
  4019.  
  4020. let m_playlist = document.querySelector(`#tab-list ytd-playlist-panel-renderer#playlist:not([o3r-${sa_playlist}])`)
  4021.  
  4022. // once per {ytd-playlist-panel-renderer#playlist} detection
  4023.  
  4024. _console.log(3902, !!m_playlist)
  4025.  
  4026. const ytdFlexyElm = es.ytdFlexy;
  4027. if (!scriptEnable || !ytdFlexyElm) { }
  4028. else if (m_playlist) {
  4029.  
  4030. if (mtoVisibility_Playlist.bindElement(m_playlist)) {
  4031. mtoVisibility_Playlist.observer.check(9); //delay check required for browser bug - hidden changed not triggered
  4032. }
  4033. let playlist_wr = mWeakRef(m_playlist);
  4034. scriptletDeferred.debounce(() => {
  4035. let m_playlist = kRef(playlist_wr);
  4036. playlist_wr = null;
  4037. if (m_playlist) {
  4038. m_playlist.dispatchEvent(new CustomEvent("tabview-playlist-data-re-assign"));
  4039. }
  4040. m_playlist = null;
  4041. })
  4042. m_playlist = null;
  4043.  
  4044. }
  4045.  
  4046. FP.mtf_attrPlaylist();
  4047.  
  4048. Promise.resolve(0).then(() => {
  4049. // ['tab-btn', 'tab-btn', 'tab-btn active', 'tab-btn tab-btn-hidden']
  4050. // bug
  4051. const ytdFlexyElm = es.ytdFlexy;
  4052. if (!scriptEnable || !ytdFlexyElm) return;
  4053. if (!switchTabActivity_lastTab && (ytdFlexyElm.getAttribute('tyt-tab') + '').indexOf('#tab-') === 0 && /https\:\/\/www\.youtube\.com\/watch.*[\?\&]list=[\w\-\_]+/.test(location.href)) {
  4054. if (setToActiveTab('#tab-list')) switchTabActivity_lastTab = '#tab-list';
  4055. }
  4056. })
  4057.  
  4058. }
  4059.  
  4060.  
  4061. const _pageBeingInit = function () {
  4062.  
  4063. pageSession.inc();
  4064. if (pageSession.sid > 9e9) pageSession.sid = 9;
  4065.  
  4066. fetchCounts = {
  4067. base: null,
  4068. new: null,
  4069. fetched: false,
  4070. count: null
  4071. }
  4072. pageFetchedData = null;
  4073. pageFetchedDataVideoId = null;
  4074. chatroomDetails = null;
  4075. }
  4076.  
  4077. const pageBeingInit = function () {
  4078.  
  4079. if(_isPageFirstLoaded && location.pathname==='/watch') document.documentElement.setAttribute('tyt-lock', '')
  4080.  
  4081. // call regardless pageType
  4082. // run once on / before pageSeq2
  4083.  
  4084. let action = 0;
  4085. if (tabsDeferred.resolved) {
  4086. action = 1;
  4087. } else if (renderDeferred.resolved) {
  4088. // in case , rarely, tabsDeferred not yet resolved but animateLoadDeferred resolved
  4089. action = 2;
  4090. }
  4091. renderIdentifier++;
  4092. if (renderIdentifier > 1e9) renderIdentifier = 9;
  4093. renderDeferred.reset();
  4094.  
  4095. if (action === 1) {
  4096. comments_loader = 1;
  4097. tabsDeferred.reset();
  4098. if ((firstLoadStatus & 8) === 0) {
  4099. innerDOMCommentsCountLoader(false); //ensure the previous record is saved
  4100. // no need to cache to the rendering state
  4101. _pageBeingInit();
  4102. } else if ((firstLoadStatus & 2) === 2) {
  4103. firstLoadStatus -= 2;
  4104. script_inject_js1.inject();
  4105. }
  4106. _console.log('pageBeingInit', firstLoadStatus)
  4107. }
  4108.  
  4109. if (pageRendered === 2) {
  4110. pageRendered = 0;
  4111. let elmPL = document.querySelector('tabview-view-ploader');
  4112. if (elmPL) elmPL.remove();
  4113. pageRendered = 0;
  4114. }
  4115.  
  4116. if (!scriptletDeferred.resolved) {
  4117. // just in case, should not happen this.
  4118. // this is to clear the pending queue if scriptlet is not ready.
  4119. scriptletDeferred.reset();
  4120. }
  4121.  
  4122. };
  4123.  
  4124. const advanceFetch = async function () {
  4125. if (pageType === 'watch' && !fetchCounts.new && !fetchCounts.fetched) {
  4126. renderDeferred.resolved && innerDOMCommentsCountLoader(true);
  4127. if (renderDeferred.resolved && !fetchCounts.new) {
  4128. window.dispatchEvent(new Event("scroll"));
  4129. }
  4130. }
  4131. };
  4132.  
  4133. function getFinalComments() {
  4134.  
  4135. if ((comments_loader & 3) === 3) { } else return;
  4136. comments_loader = 0;
  4137.  
  4138. let ei = 0;
  4139.  
  4140. function execute() {
  4141. //sync -> animateLoadDeferred.resolved always true
  4142.  
  4143. if (!renderDeferred.resolved) return;
  4144.  
  4145. _console.log(2323)
  4146.  
  4147. if (Q.comments_section_loaded !== 0) return;
  4148. if (fetchCounts.fetched) return;
  4149.  
  4150.  
  4151. let ret = innerDOMCommentsCountLoader(true);
  4152.  
  4153. if (fetchCounts.new && !fetchCounts.fetched) {
  4154. if (fetchCounts.new.f()) {
  4155. fetchCounts.fetched = true;
  4156. fetchCommentsFinished();
  4157. _console.log(9972, 'fetched = true')
  4158. }
  4159. return;
  4160. }
  4161.  
  4162.  
  4163. ei++;
  4164.  
  4165. if (fetchCounts.base && !fetchCounts.new && !fetchCounts.fetched && fetchCounts.count === 1) {
  4166.  
  4167.  
  4168. let elm = kRef(fetchCounts.base.elm);
  4169. let txt = elm ? getCountHText(elm) : null;
  4170. let condi1 = ei > 7;
  4171. let condi2 = txt === m_last_count;
  4172. if (condi1 || condi2) {
  4173.  
  4174. if (fetchCounts.base.f()) {
  4175. fetchCounts.fetched = true;
  4176. fetchCommentsFinished();
  4177. _console.log(9972, 'fetched = true')
  4178. }
  4179.  
  4180. }
  4181.  
  4182. }
  4183.  
  4184. if (!fetchCounts.fetched) {
  4185. if (ei > 7) {
  4186. let elm = ret.length === 1 ? kRef(ret[0].elm) : null;
  4187. let txt = elm ? getCountHText(elm) : null;
  4188. if (elm && txt !== m_last_count) {
  4189. fetchCounts.base = null;
  4190. fetchCounts.new = ret[0];
  4191. fetchCounts.new.f();
  4192. fetchCounts.fetched = true;
  4193. _console.log(9979, 'fetched = true')
  4194. fetchCommentsFinished();
  4195. }
  4196. return;
  4197. }
  4198. return true;
  4199. }
  4200.  
  4201. }
  4202.  
  4203.  
  4204. async function alCheckFn(ks) {
  4205.  
  4206. let alCheckCount = 9;
  4207. let alCheckInterval = 420;
  4208.  
  4209. do {
  4210.  
  4211. if (renderIdentifier !== ks) break;
  4212. if (alCheckCount === 0) break;
  4213. if (execute() !== true) break;
  4214. --alCheckCount;
  4215.  
  4216. await new Promise(r => setTimeout(r, alCheckInterval));
  4217.  
  4218. } while (true)
  4219.  
  4220. }
  4221. let ks = renderIdentifier;
  4222. renderDeferred.debounce(() => {
  4223. if (ks !== renderIdentifier) return
  4224. alCheckFn(ks);
  4225.  
  4226. });
  4227.  
  4228.  
  4229. }
  4230.  
  4231.  
  4232. let g_check_detail_A = 0;
  4233. let checkDuplicateRes = null;
  4234. function setHiddenStateForDesc(){
  4235. let ytdFlexyElm = es.ytdFlexy
  4236. if (!ytdFlexyElm) return
  4237. let hiddenBool = !document.fullscreenElement ? ytdFlexyElm.classList.contains('tabview-info-duplicated') : false
  4238. let elm
  4239. elm = document.querySelector('.tabview-info-duplicated-checked[flexy] ytd-text-inline-expander#description-inline-expander #plain-snippet-text')
  4240. if (elm) {
  4241. wAttr(elm, 'hidden', hiddenBool)
  4242. }
  4243. elm = document.querySelector('.tabview-info-duplicated-checked[flexy] ytd-text-inline-expander#description-inline-expander #formatted-snippet-text')
  4244. if (elm) {
  4245. wAttr(elm, 'hidden', hiddenBool)
  4246. }
  4247. }
  4248. function checkDuplicatedInfo_then(isCheck, checkDuplicateRes) {
  4249.  
  4250. const ytdFlexyElm = es.ytdFlexy;
  4251. if (!ytdFlexyElm) return; //unlikely
  4252.  
  4253. let cssbool_c1 = false, cssbool_c2 = false;
  4254. if (isCheck === 5) {
  4255.  
  4256. if (ytdFlexyElm.matches('.tabview-info-duplicated[flexy]')) {
  4257. cssbool_c1 = !!querySelectorFromAnchor.call(ytdFlexyElm, '#description.style-scope.ytd-watch-metadata > #description-inner:only-child');
  4258. cssbool_c2 = !!querySelectorFromAnchor.call(ytdFlexyElm, '#tab-info ytd-expander #description.ytd-video-secondary-info-renderer');
  4259. }
  4260.  
  4261. if (typeof checkDuplicateRes === 'boolean') {
  4262. setHiddenStateForDesc();
  4263. }
  4264. }
  4265.  
  4266. ytdFlexyElm.setAttribute('tyt-has', `${cssbool_c1 ? 'A' : 'a'}${cssbool_c2 ? 'B' : 'b'}`);
  4267.  
  4268. }
  4269.  
  4270.  
  4271. async function checkDuplicatedInfoMay2023() {
  4272. const firstElementSelector = "ytd-text-inline-expander#description-inline-expander";
  4273. const secondElementSelector = "#tab-info ytd-expander #description";
  4274.  
  4275. const firstElement = document.querySelector(firstElementSelector);
  4276. const secondElement = document.querySelector(secondElementSelector);
  4277.  
  4278. if(!firstElement || !secondElement) return false;
  4279. if(firstElement.hasAttribute('hidden') || secondElement.hasAttribute('hidden')) return false;
  4280.  
  4281. const asyncGetContent = async (n)=>{
  4282. return n.textContent;
  4283. }
  4284.  
  4285. const getTextContentArr = async (element) => {
  4286. let contentArray = [];
  4287.  
  4288. for (let currentNode = element.firstChild; currentNode; currentNode = currentNode.nextSibling) {
  4289.  
  4290. if (currentNode.nodeType === Node.ELEMENT_NODE) {
  4291. if (currentNode.hasAttribute("hidden")) {
  4292. continue;
  4293. }
  4294. if (currentNode.id === "snippet") {
  4295. let allHidden = true;
  4296. for (let child = currentNode.firstChild; child; child = child.nextSibling) {
  4297. if (child.hasAttribute("hidden")) {
  4298. continue;
  4299. }
  4300. let trimmedTextContent = await asyncGetContent(child);
  4301. trimmedTextContent = trimmedTextContent.trim();
  4302. if (trimmedTextContent.length === 0) continue;
  4303. allHidden = false;
  4304. break;
  4305. }
  4306. if (allHidden) {
  4307. continue;
  4308. }
  4309. }
  4310.  
  4311. if (currentNode.matches('#collapse[role="button"]:not([hidden])')) {
  4312. // break;
  4313. continue;
  4314. }
  4315.  
  4316.  
  4317. } else if (currentNode.nodeType === Node.TEXT_NODE) {
  4318. } else {
  4319. continue;
  4320. }
  4321.  
  4322. let trimmedTextContent = await asyncGetContent(currentNode);
  4323. trimmedTextContent = trimmedTextContent.trim();
  4324. if (trimmedTextContent.length > 0) {
  4325. contentArray.push(trimmedTextContent);
  4326. }
  4327.  
  4328. }
  4329.  
  4330. return contentArray;
  4331. };
  4332.  
  4333. const [firstElementTextArr, secondElementTextArr] = await Promise.all([getTextContentArr(firstElement), getTextContentArr(secondElement)]);
  4334.  
  4335. function isSubset(arr1, arr2) {
  4336. const set = new Set(arr2);
  4337. const r = arr1.every(item => set.has(item));
  4338. set.clear();
  4339. return r;
  4340. }
  4341.  
  4342. return isSubset(firstElementTextArr, secondElementTextArr);
  4343. }
  4344.  
  4345.  
  4346.  
  4347.  
  4348.  
  4349. async function checkDuplicatedInfo() {
  4350.  
  4351. const ytdFlexyElm = es.ytdFlexy;
  4352. if (!ytdFlexyElm) return; //unlikely
  4353.  
  4354. const targetDuplicatedInfoPanel = document.querySelector('ytd-text-inline-expander#description-inline-expander:not([hidden])');
  4355. if (targetDuplicatedInfoPanel && !targetDuplicatedInfoPanel.closest('[hidden]')) { } else {
  4356. return; // the layout is not required to have this checking.
  4357. }
  4358.  
  4359. let t = Date.now();
  4360. g_check_detail_A = t;
  4361.  
  4362. ytdFlexyElm.classList.toggle('tabview-info-duplicated', true) // hide first;
  4363. let infoDuplicated = false;
  4364.  
  4365. try {
  4366. await new Promise(resolve => setTimeout(resolve, 1)); // mcrcr might be not yet initalized
  4367.  
  4368.  
  4369. if (g_check_detail_A !== t) return;
  4370.  
  4371.  
  4372. let clicked = false;
  4373. await Promise.all([...document.querySelectorAll('ytd-text-inline-expander#description-inline-expander #expand[role="button"]:not([hidden])')].map(button => {
  4374. return new Promise(r => {
  4375. button.click();
  4376. clicked = true;
  4377. r();
  4378. });
  4379. }));
  4380.  
  4381. await Promise.resolve(0);
  4382.  
  4383. infoDuplicated = await checkDuplicatedInfoMay2023();
  4384.  
  4385. if(infoDuplicated === false && clicked){
  4386.  
  4387. await Promise.all([...document.querySelectorAll('ytd-text-inline-expander#description-inline-expander #collapse[role="button"]:not([hidden])')].map(button => {
  4388. return new Promise(r => {
  4389. button.click();
  4390. r();
  4391. });
  4392. }));
  4393. }
  4394.  
  4395. } catch (e) {
  4396.  
  4397. ytdFlexyElm.classList.toggle('tabview-info-duplicated', false) // error => unhide
  4398. }
  4399.  
  4400. console.debug('[tyt] Have any details with duplicated information been found?', (infoDuplicated ? 'Yes' : 'No'));
  4401.  
  4402. if (g_check_detail_A !== t) return;
  4403.  
  4404. //ytdFlexyElm.classList.toggle('tabview-info-duplicated', infoDuplicated)
  4405. checkDuplicateRes = infoDuplicated;
  4406.  
  4407. return 5; // other than 5, duplicated check = false
  4408.  
  4409. };
  4410.  
  4411. function setupChatFrameDOM(node) {
  4412. // this function calls 3 times per each new video page
  4413.  
  4414. // 'tyt-chat' is initialized in setupChatFrameDisplayState1()
  4415.  
  4416. if (!chatroomDetails) return;
  4417. let liveChatFrame = node || document.querySelector('ytd-live-chat-frame#chat')
  4418. if (liveChatFrame) {
  4419.  
  4420. // every per [new] {ytd-live-chat-frame#chat} detection - reset after mini-playview
  4421.  
  4422. let ytdFlexyElm = es.ytdFlexy;
  4423. if (scriptEnable && ytdFlexyElm) {
  4424. if (mtoVisibility_Chatroom.bindElement(liveChatFrame)) {
  4425. mtoVisibility_Chatroom.observer.check(9)
  4426. }
  4427. }
  4428.  
  4429. liveChatFrame = null;
  4430. ytdFlexyElm = null;
  4431.  
  4432. setToggleBtnTxt(); // immediate update when page changed
  4433.  
  4434. if (node !== null) {
  4435. // button might not yet be rendered
  4436. requestAnimationFrame(setToggleBtnTxt); // bool = true must be front page
  4437. } else {
  4438.  
  4439. // this is due to page change
  4440. let incorrectChat = document.querySelector('ytd-watch-flexy[is-two-columns_][theater] ytd-live-chat-frame#chat:not([collapsed])')
  4441. if (incorrectChat) {
  4442. incorrectChat.setAttribute('collapsed', '')
  4443. }
  4444.  
  4445. }
  4446.  
  4447. }
  4448.  
  4449. }
  4450.  
  4451. function whenEngagemenetPanelVisible() {
  4452.  
  4453. const layoutStatus = wls.layoutStatus;
  4454. if ((layoutStatus & (LAYOUT_TWO_COLUMNS | LAYOUT_THEATER)) === LAYOUT_TWO_COLUMNS) {
  4455.  
  4456. if (layoutStatus & LAYOUT_TAB_EXPANDED) {
  4457. switchTabActivity(null);
  4458. return true;
  4459. } else if (layoutStatus & LAYOUT_CHATROOM_EXPANDED) {
  4460. ytBtnCollapseChat();
  4461. return true;
  4462. }
  4463.  
  4464. }
  4465.  
  4466. return false;
  4467.  
  4468. }
  4469.  
  4470.  
  4471. function removeFocusOnLeave(evt) {
  4472. let node = (evt || 0).target || 0
  4473. let activeElement = document.activeElement || 0
  4474. if (node.nodeType === 1 && activeElement.nodeType === 1) {
  4475. new Promise(() => {
  4476. if (node.contains(activeElement)) {
  4477. activeElement.blur();
  4478. }
  4479. })
  4480. }
  4481. }
  4482.  
  4483. async function setupVideo(node){
  4484. // this can be fired even in background without tabs rendered
  4485. const attrKey = 'gM7Cp'
  4486. let video = querySelectorFromAnchor.call(node, `#movie_player video[src]:not([${attrKey}])`);
  4487. if (video) {
  4488. video.setAttribute(attrKey, '')
  4489.  
  4490. video.addEventListener('timeupdate', (evt) => {
  4491. energizedByVideoTimeUpdate();
  4492. }, bubblePassive);
  4493.  
  4494. video.addEventListener('ended', (evt) => {
  4495. // scrollIntoView => auto start next video
  4496. // otherwise it cannot auto paly next
  4497. if (pageType === 'watch') {
  4498. let elm = evt.target;
  4499. Promise.resolve(elm).then((elm) => {
  4500. if (pageType === 'watch') {
  4501. let scrollElm = closestDOM.call(elm, '#player') || closestDOM.call(elm, '#ytd-player') || elm;
  4502. // background applicable
  4503. scrollElm.scrollIntoView(false);
  4504. scrollElm = null
  4505. }
  4506. elm = null
  4507. });
  4508. }
  4509.  
  4510. }, bubblePassive)
  4511.  
  4512. }
  4513. }
  4514.  
  4515.  
  4516. globalHook('yt-player-updated', (evt) => {
  4517.  
  4518. const node = ((evt || 0).target) || 0
  4519.  
  4520. if (node.nodeType !== 1) return;
  4521.  
  4522. const nodeName = node.nodeName.toUpperCase();
  4523.  
  4524. _console.log(evt.target.nodeName, 904, evt.type);
  4525.  
  4526. if (nodeName !== 'YTD-PLAYER') return
  4527.  
  4528. setupVideo(node)
  4529.  
  4530.  
  4531. let tabsDeferredSess = pageSession.session();
  4532. if (!scriptEnable && tabsDeferred.resolved) { }
  4533. else tabsDeferred.debounce(() => {
  4534.  
  4535. if (!tabsDeferredSess.isValid) return;
  4536. tabsDeferredSess = null;
  4537.  
  4538.  
  4539. if (!scriptEnable) return
  4540.  
  4541. checkAndMakeNewCommentFetch();
  4542.  
  4543. _console.log(2178, 4)
  4544. pageCheck();
  4545.  
  4546. domInit_comments();
  4547. setupChatFrameDOM(null);
  4548.  
  4549.  
  4550. });
  4551.  
  4552.  
  4553. });
  4554.  
  4555. function ytMicroEventsInit() {
  4556.  
  4557. _console.log(902)
  4558.  
  4559. /** @type {Map<string, Function>} */
  4560. let handleDOMAppearFN = new Map();
  4561. function handleDOMAppear( /** @type {string} */ fn, /** @type { listener: (this: Document, ev: AnimationEvent ) => any } */ func) {
  4562. if (handleDOMAppearFN.size === 0) {
  4563. document.addEventListener('animationstart', (evt) => {
  4564. let func = handleDOMAppearFN.get(evt.animationName);
  4565. if (func) func(evt);
  4566. }, capturePassive)
  4567. } else {
  4568. if (handleDOMAppearFN.has(fn)) return;
  4569. }
  4570. handleDOMAppearFN.set(fn, func);
  4571. }
  4572.  
  4573. handleDOMAppear('videosDOMAppended', function (evt) {
  4574. videosDeferred.resolve();
  4575. })
  4576.  
  4577. handleDOMAppear('liveChatFrameDOMAppended', (evt) => {
  4578.  
  4579. let node = evt.target;
  4580. if (!node) return;
  4581.  
  4582. let tabsDeferredSess = pageSession.session();
  4583. if (!scriptEnable && tabsDeferred.resolved) { }
  4584. else tabsDeferred.debounce(() => {
  4585.  
  4586. // P.S. avoid immediately dom change
  4587. // time delay to avoid attribute set after dom appended.
  4588.  
  4589. if (!tabsDeferredSess.isValid) return;
  4590. tabsDeferredSess = null;
  4591.  
  4592. setupChatFrameDOM(node); // front page
  4593. node = null;
  4594.  
  4595. })
  4596.  
  4597. });
  4598.  
  4599. handleDOMAppear('pageLoaderAnimation', (evt) => {
  4600. pageRendered = 2;
  4601. renderDeferred.resolve();
  4602. console
  4603. console.debug('[tyt] pageRendered')
  4604.  
  4605. scriptletDeferred.debounce(() => {
  4606. document.dispatchEvent(new CustomEvent('tabview-page-rendered'))
  4607. })
  4608.  
  4609. });
  4610.  
  4611.  
  4612. handleDOMAppear('chatFrameToggleBtnAppended1', (evt) => {
  4613.  
  4614. _console.log(5099, 'chatFrameToggleBtnAppended', evt)
  4615.  
  4616. Promise.resolve(0).then(() => { // avoid immediately dom change
  4617.  
  4618. let tabsDeferredSess = pageSession.session();
  4619. if (!scriptEnable && tabsDeferred.resolved) { }
  4620. else tabsDeferred.debounce(() => {
  4621.  
  4622. if (!tabsDeferredSess.isValid) return;
  4623. tabsDeferredSess = null;
  4624.  
  4625. mtf_liveChatBtnF(evt.target);
  4626.  
  4627. })
  4628.  
  4629. })
  4630.  
  4631. });
  4632.  
  4633.  
  4634. DEBUG_LOG && handleDOMAppear('chatFrameToggleBtnAppended2', (evt) => {
  4635.  
  4636. _console.log(5099, 'chatFrameToggleBtnAppended', evt)
  4637.  
  4638.  
  4639. });
  4640.  
  4641.  
  4642. handleDOMAppear('epDOMAppended', async (evt) => {
  4643. try {
  4644. let node = evt.target;
  4645.  
  4646. let eps = document.querySelectorAll('ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"]:not([hidden])')
  4647.  
  4648. if (eps && eps.length > 0) {
  4649.  
  4650. if (eps.length > 1) {
  4651. let p = 0;
  4652. for (const ep of eps) {
  4653. if (ep !== node) {
  4654. ytBtnCloseEngagementPanel(ep)
  4655. p++
  4656. }
  4657. }
  4658. if (p > 0) {
  4659. await Promise.resolve(0)
  4660. }
  4661. }
  4662.  
  4663. FP.mtf_attrEngagementPanel(9, node);
  4664.  
  4665. new Promise(() => {
  4666.  
  4667. mtoVisibility_EngagementPanel.bindElement(node, {
  4668. attributes: true,
  4669. attributeFilter: ['visibility'],
  4670. attributeOldValue: true
  4671. })
  4672.  
  4673. node.removeEventListener('mouseleave', removeFocusOnLeave, false)
  4674. node.addEventListener('mouseleave', removeFocusOnLeave, false)
  4675.  
  4676. })
  4677.  
  4678. }
  4679.  
  4680.  
  4681. } catch (e) { }
  4682.  
  4683. })
  4684.  
  4685. let _tabviewSiderAnimated = false;
  4686.  
  4687. handleDOMAppear('tabviewSiderAnimation', (evt) => {
  4688. if (!_tabviewSiderAnimated) {
  4689. _tabviewSiderAnimated = true;
  4690. dispatchCommentRowResize();
  4691. }
  4692. })
  4693.  
  4694. handleDOMAppear('tabviewSiderAnimationNone', (evt) => {
  4695. if (_tabviewSiderAnimated) {
  4696. _tabviewSiderAnimated = false;
  4697. dispatchCommentRowResize();
  4698. }
  4699. })
  4700.  
  4701. handleDOMAppear('SearchWhileWatchAutocomplete', (evt) => { // Youtube - Search While Watching Video
  4702. let elm = evt.target;
  4703. elm.addEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false)
  4704. scriptletDeferred.debounce(() => {
  4705. elm.dispatchEvent(new CustomEvent('tabview-fix-autocomplete'));
  4706. elm = null;
  4707. })
  4708. })
  4709.  
  4710. handleDOMAppear('oldYtIconPinAppeared', (evt) => {
  4711. /* added in May 2023 - 2023.05.19 */
  4712. /*
  4713. from
  4714. <svg style="pointer-events: none; display: block; width: 100%; height: 100%;" focusable="false" width="24" viewBox="0 0 24 24" height="24"><path d="M16 11V3h1V2H7v1h1v8l-2 2v2h5v6l1 1 1-1v-6h5v-2l-2-2zm1 3H7v-.59l1.71-1.71.29-.29V3h6v8.41l.29.29L17 13.41V14z"></path></svg>
  4715.  
  4716. to
  4717. <svg viewBox="0 0 12 12" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon"><path d="M8,2V1H3v1h1v3.8L3,7h2v2.5L5.5,10L6,9.5V7h2L7,5.8V2H8z M6,6H5V2h1V6z" class="style-scope yt-icon"></path></g></svg>
  4718.  
  4719. */
  4720.  
  4721. let svg = evt.target;
  4722. let p = document.createElement('template');
  4723. p.innerHTML = '<svg viewBox="0 0 12 12" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon"><path d="M8,2V1H3v1h1v3.8L3,7h2v2.5L5.5,10L6,9.5V7h2L7,5.8V2H8z M6,6H5V2h1V6z" class="style-scope yt-icon"></path></g></svg>';
  4724. svg.replaceWith(p.content.firstChild);
  4725.  
  4726.  
  4727. })
  4728.  
  4729. const renderStamperFunc = {
  4730. 'YTD-PLAYLIST-PANEL-RENDERER': (node) => {
  4731. mtf_append_playlist(node); // the true playlist is appended to the #tab-list
  4732. checkPlaylistForInitialization();
  4733. },
  4734. 'YTD-COMMENTS-HEADER-RENDERER': (node) => {
  4735. comments_loader = comments_loader | 4;
  4736. getFinalComments();
  4737. }
  4738. }
  4739.  
  4740. globalHook('yt-rendererstamper-finished', (evt) => {
  4741.  
  4742. if (!scriptEnable && tabsDeferred.resolved) { return }
  4743. // might occur before initialization
  4744.  
  4745. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  4746.  
  4747. let node = evt.target;
  4748. const nodeName = node.nodeName.toUpperCase();
  4749. const func = renderStamperFunc[nodeName];
  4750.  
  4751. if (typeof func !== 'function') {
  4752. return;
  4753. }
  4754.  
  4755.  
  4756. let tabsDeferredSess = pageSession.session();
  4757. if (!scriptEnable && tabsDeferred.resolved) { }
  4758. else tabsDeferred.debounce(() => {
  4759.  
  4760. if (!tabsDeferredSess.isValid) return;
  4761. tabsDeferredSess = null;
  4762.  
  4763. func(node);
  4764. node = null;
  4765.  
  4766. });
  4767.  
  4768.  
  4769. });
  4770.  
  4771. async function triggerMenuItemResizing(){
  4772. /*
  4773. const menus = document.querySelectorAll('ytd-menu-renderer[has-flexible-items]');
  4774. for(const menu of menus){
  4775. }
  4776. let promises;
  4777. promises = menus.map(menu=>{
  4778. return new Promise(r=>{
  4779. r(menu.offsetHeight);
  4780. });
  4781. });
  4782. let heights = await Promise.all(promises);
  4783. promises = menus.map((menu,idx)=>{
  4784. return new Promise(r=>{
  4785. menu.setAttribute
  4786. r(menu.offsetHeight);
  4787. });
  4788. });
  4789. */
  4790. }
  4791.  
  4792.  
  4793. globalHook('yt-page-data-updated', (evt) => {
  4794.  
  4795. if (!scriptEnable && tabsDeferred.resolved) { return }
  4796. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  4797.  
  4798. _console.log(evt.target.nodeName, 904, evt.type);
  4799.  
  4800. advanceFetch();
  4801.  
  4802. let tabsDeferredSess = pageSession.session();
  4803. if (!scriptEnable && tabsDeferred.resolved) { }
  4804. else tabsDeferred.debounce(() => {
  4805.  
  4806. if (!tabsDeferredSess.isValid) return;
  4807. tabsDeferredSess = null;
  4808.  
  4809. if (!scriptEnable) return;
  4810.  
  4811. checkAndMakeNewCommentFetch();
  4812.  
  4813.  
  4814. // if the page is navigated by history back-and-forth, not all engagement panels can be catched in rendering event.
  4815.  
  4816.  
  4817.  
  4818. _console.log(2178, 3)
  4819. pageCheck();
  4820. setupChatFrameDOM(null);
  4821.  
  4822. let expander = document.querySelector('#meta-contents ytd-expander:not([tabview-expander-checked])');
  4823. if (expander) {
  4824.  
  4825. // once per $$native-info-description$$ {#meta-contents ytd-expander} detection
  4826. // append the detailed meta contents to the tab-info
  4827.  
  4828. expander.setAttribute('tabview-expander-checked', '');
  4829. let tabInfo = document.querySelector("#tab-info");
  4830. if (tabInfo) {
  4831. elementAppend.call(tabInfo, expander);
  4832. }
  4833.  
  4834. }
  4835.  
  4836.  
  4837. if (REMOVE_DUPLICATE_INFO) {
  4838.  
  4839.  
  4840. checkDuplicateRes = null;
  4841. async function alCheckFn(ks) {
  4842.  
  4843. let alCheckCount = 4;
  4844. let alCheckInterval = 270;
  4845.  
  4846. checkDuplicateRes = null;
  4847. let descExpandState = null;
  4848. let descMetaExpander = closestDOMX(document.querySelector('ytd-text-inline-expander#description-inline-expander'), 'ytd-watch-metadata');
  4849. let descToggleBtn = null;
  4850. let descMetaLines = null;
  4851. if (descMetaExpander) {
  4852.  
  4853. // ytd-text-inline-expander#description-inline-expander.style-scope.ytd-watch-metadata
  4854. descMetaLines = querySelectorFromAnchor.call(descMetaExpander, 'ytd-text-inline-expander#description-inline-expander.style-scope.ytd-watch-metadata')
  4855. if (descMetaLines) {
  4856.  
  4857. descToggleBtn = querySelectorFromAnchor.call(descMetaLines, '#collapse[role="button"]:not([hidden]), #expand[role="button"]:not([hidden])');
  4858. if (descToggleBtn) {
  4859. if (descMetaExpander.hasAttribute('description-collapsed') && descToggleBtn.id === 'expand') {
  4860. descExpandState = false;
  4861. } else if (!descMetaExpander.hasAttribute('description-collapsed') && descToggleBtn.id === 'collapse') {
  4862. descExpandState = true;
  4863. }
  4864. }
  4865. }
  4866.  
  4867. }
  4868. if (descMetaExpander) {
  4869. descMetaExpander.classList.add('tyt-tmp-hide-metainfo');
  4870. }
  4871.  
  4872. try{
  4873.  
  4874.  
  4875. do {
  4876.  
  4877. if (renderIdentifier !== ks) break;
  4878. if (alCheckCount === 0) break;
  4879. if (checkDuplicateRes === true) break;
  4880. checkDuplicateRes = null;
  4881.  
  4882. let res = await checkDuplicatedInfo(); //async
  4883. if (res === 5) {
  4884.  
  4885. const ytdFlexyElm = es.ytdFlexy;
  4886. if (ytdFlexyElm) {
  4887. if (checkDuplicateRes === true || (checkDuplicateRes === false && alCheckCount === 1)) {
  4888. ytdFlexyElm.classList.toggle('tabview-info-duplicated', checkDuplicateRes)
  4889. ytdFlexyElm.classList.toggle('tabview-info-duplicated-checked', true)
  4890. checkDuplicatedInfo_then(res, checkDuplicateRes);
  4891. }
  4892. }
  4893.  
  4894. }
  4895. --alCheckCount;
  4896.  
  4897. if (checkDuplicateRes === true) break;
  4898.  
  4899. await new Promise(r => setTimeout(r, alCheckInterval));
  4900.  
  4901. } while (true)
  4902.  
  4903. await Promise.resolve(0)
  4904.  
  4905. descToggleBtn = descMetaLines ? querySelectorFromAnchor.call(descMetaLines, '#collapse[role="button"]:not([hidden]), #expand[role="button"]:not([hidden])') : null;
  4906. if (descToggleBtn) {
  4907.  
  4908. let isCollapsed = descMetaExpander.hasAttribute('description-collapsed')
  4909. let id = descToggleBtn.id
  4910. let b1 = descExpandState === true && isCollapsed && id === 'expand';
  4911. let b2 = descExpandState === false && !isCollapsed && id === 'collapse';
  4912.  
  4913. if (b1 || b2) {
  4914. descToggleBtn.click();
  4915. }
  4916.  
  4917. }
  4918.  
  4919.  
  4920.  
  4921. }catch(e){
  4922.  
  4923. console.warn(e)
  4924.  
  4925. }
  4926.  
  4927. if (descMetaExpander) {
  4928. descMetaExpander.classList.remove('tyt-tmp-hide-metainfo');
  4929.  
  4930. await Promise.resolve(0)
  4931.  
  4932. let detailsIntersectioner = querySelectorFromAnchor.call(descMetaExpander, '#info-container.style-scope.ytd-watch-metadata');
  4933. if (detailsIntersectioner) {
  4934. Promise.resolve(detailsIntersectioner).then(detailsIntersectioner => {
  4935. let dom = detailsIntersectioner;
  4936. if (dom) mtoObservationDetails.bindElement(dom);
  4937. })
  4938. }
  4939.  
  4940. }
  4941.  
  4942.  
  4943.  
  4944. }
  4945. let ks = renderIdentifier;
  4946. renderDeferred.debounce(() => {
  4947. if (ks !== renderIdentifier) return
  4948. alCheckFn(ks);
  4949.  
  4950. });
  4951.  
  4952. } else {
  4953.  
  4954. checkDuplicatedInfo_then(0, null);
  4955.  
  4956. }
  4957.  
  4958. function contentExtractor(elm) {
  4959. if (!(elm instanceof HTMLElement)) {
  4960. return null;
  4961. }
  4962. let m = elm.textContent;
  4963. let isEmpty = m.trim().length === 0;
  4964. if (isEmpty) return null;
  4965. let s = elm.nodeName;
  4966. let id = elm.id;
  4967. if (id) s += '#' + id;
  4968. return s + '\n' + m;
  4969. }
  4970.  
  4971. if (REMOVE_DUPLICATE_META_RECOMMENDATION) {
  4972.  
  4973. async function checkDuplicatedMetaRecommendation() {
  4974. let mainContent0 = document.querySelector('#primary.ytd-watch-flexy #above-the-fold.ytd-watch-metadata');
  4975. let mainContent1 = document.querySelector('#tab-info ytd-expander > #content');
  4976. if (mainContent0 && mainContent1) {
  4977. const hashedContents = new Set();
  4978. for (let s1 = mainContent1.nextElementSibling; s1 instanceof HTMLElement; s1 = s1.nextElementSibling) {
  4979. let m = contentExtractor(s1);
  4980. if(m === null) continue;
  4981. hashedContents.add(m);
  4982. }
  4983.  
  4984. for (let s0 = mainContent0.nextElementSibling; s0 instanceof HTMLElement; s0 = s0.nextElementSibling) {
  4985. let m = contentExtractor(s0);
  4986. if (m !== null && hashedContents.has(m)) {
  4987. s0.classList.add('tyt-hidden-duplicated-meta');
  4988. } else {
  4989. s0.classList.remove('tyt-hidden-duplicated-meta');
  4990. }
  4991. }
  4992. hashedContents.clear();
  4993. }
  4994. }
  4995.  
  4996. let ks = renderIdentifier;
  4997. renderDeferred.debounce(() => {
  4998. if (ks !== renderIdentifier) return
  4999. checkDuplicatedMetaRecommendation();
  5000. })
  5001.  
  5002. }
  5003.  
  5004. /*
  5005. if (REPLACE_PIN_ICON) {
  5006.  
  5007.  
  5008.  
  5009. }
  5010. */
  5011.  
  5012. let renderId = renderIdentifier
  5013. renderDeferred.debounce(() => {
  5014. if (renderId !== renderIdentifier) return
  5015. // domInit_teaserInfo() // YouTube obsoleted feature?
  5016.  
  5017. triggerMenuItemResizing();
  5018.  
  5019. let h1 = document.querySelector('#below h1.ytd-watch-metadata yt-formatted-string')
  5020. if (h1) {
  5021.  
  5022.  
  5023. let s = '';
  5024.  
  5025. try {
  5026. if (formatDates && Object.keys(formatDates).length > 0) {
  5027.  
  5028. function getDurationInfo(bd1, bd2) {
  5029.  
  5030. let bdd = bd2 - bd1
  5031. let hrs = Math.floor(bdd / 3600000)
  5032. bdd = bdd - hrs * 3600000
  5033. let mins = Math.round(bdd / 60000)
  5034. let seconds = null
  5035. if (mins < 10 && hrs === 0) {
  5036. mins = Math.floor(bdd / 60000)
  5037. bdd = bdd - mins * 60000
  5038. seconds = Math.round(bdd / 1000)
  5039. if (seconds === 0) seconds = null
  5040. }
  5041.  
  5042. return { hrs, mins, seconds }
  5043.  
  5044. }
  5045.  
  5046. const formatDateResult = getFormatDateResultFunc();
  5047.  
  5048. if (formatDates.broadcastBeginAt && formatDates.isLiveNow === false) {
  5049.  
  5050. let bd1 = new KDate(formatDates.broadcastBeginAt)
  5051. let bd2 = formatDates.broadcastEndAt ? new KDate(formatDates.broadcastEndAt) : null
  5052.  
  5053. let isSameDay = 0
  5054. if (bd2 && bd1.toLocaleDateString() === bd2.toLocaleDateString()) {
  5055. isSameDay = 1
  5056.  
  5057. } else if (bd2 && +bd2 > +bd1 && bd2 - bd1 < 86400000) {
  5058.  
  5059. if (bd1.getHours() >= 6 && bd2.getHours() < 6) {
  5060. isSameDay = 2
  5061. }
  5062.  
  5063. }
  5064.  
  5065. let durationInfo = getDurationInfo(bd1, bd2)
  5066. if (isSameDay > 0) {
  5067.  
  5068. bd2.dayBack = (isSameDay === 2)
  5069.  
  5070. s = formatDateResult(0x200, { bd1, bd2, isSameDay, durationInfo, formatDates })
  5071.  
  5072. } else if (bd2 && isSameDay === 0) {
  5073.  
  5074. s = formatDateResult(0x210, { bd1, bd2, isSameDay, durationInfo, formatDates })
  5075.  
  5076. }
  5077.  
  5078.  
  5079. } else if (formatDates.broadcastBeginAt && formatDates.isLiveNow === true) {
  5080.  
  5081. let bd1 = new KDate(formatDates.broadcastBeginAt)
  5082.  
  5083. s = formatDateResult(0x300, { bd1, formatDates })
  5084.  
  5085. } else {
  5086. if (formatDates.uploadDate) {
  5087.  
  5088. if (formatDates.publishDate && formatDates.publishDate !== formatDates.uploadDate) {
  5089.  
  5090. s = formatDateResult(0x600, { formatDates })
  5091. } else {
  5092. s = formatDateResult(0x610, { formatDates })
  5093.  
  5094. }
  5095. } else if (!formatDates.uploadDate && formatDates.publishDate) {
  5096.  
  5097. s = formatDateResult(0x700, { formatDates })
  5098.  
  5099.  
  5100. }
  5101. }
  5102.  
  5103.  
  5104. }
  5105. } catch (e) {
  5106. s = '';
  5107. }
  5108.  
  5109. if (s) {
  5110. h1.setAttribute('data-title-details', s)
  5111. } else {
  5112. h1.removeAttribute('data-title-details')
  5113. }
  5114.  
  5115. }
  5116.  
  5117. })
  5118.  
  5119.  
  5120. checkPlaylistForInitialization();
  5121.  
  5122. mtf_fix_details().then(() => {
  5123. // setKeywords();
  5124. setToggleInfo();
  5125. renderDeferred.debounce(() => {
  5126. if (renderId !== renderIdentifier) return
  5127. setTimeout(() => {
  5128. //dispatchWindowResize(); //try to omit
  5129. dispatchWindowResize(); //add once for safe
  5130. manualResizeT();
  5131. }, 420)
  5132. })
  5133.  
  5134.  
  5135. let secondary = document.querySelector('#columns.ytd-watch-flexy #secondary.ytd-watch-flexy');
  5136.  
  5137. let columns = secondary ? closestDOM.call(secondary, '#columns.ytd-watch-flexy') : null;
  5138.  
  5139. setupHoverSlider(secondary, columns)
  5140.  
  5141. let tabInfo = document.querySelector('#tab-info');
  5142. addTabExpander(tabInfo);
  5143.  
  5144. let tabComments = document.querySelector('#tab-comments');
  5145. addTabExpander(tabComments);
  5146.  
  5147.  
  5148. });
  5149.  
  5150.  
  5151. });
  5152.  
  5153. });
  5154.  
  5155.  
  5156. globalHook('yt-watch-comments-ready', (evt) => {
  5157.  
  5158. if (!scriptEnable && tabsDeferred.resolved) { return }
  5159. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5160.  
  5161. let nodeName = evt.target.nodeName.toUpperCase()
  5162. advanceFetch();
  5163.  
  5164. comments_loader = comments_loader | 2;
  5165.  
  5166. let tabsDeferredSess = pageSession.session();
  5167. if (!scriptEnable && tabsDeferred.resolved) { }
  5168. else tabsDeferred.debounce(() => {
  5169.  
  5170. if (!tabsDeferredSess.isValid) return;
  5171. tabsDeferredSess = null;
  5172.  
  5173. checkAndMakeNewCommentFetch();
  5174.  
  5175. if (nodeName === 'YTD-WATCH-FLEXY') {
  5176. domInit_comments();
  5177. onCommentsReady();
  5178. }
  5179. });
  5180.  
  5181. })
  5182.  
  5183.  
  5184. window.addEventListener("message", (evt) => {
  5185. if (!scriptEnable && tabsDeferred.resolved) { return }
  5186. if (evt.origin === location.origin && evt.data.tabview) {
  5187. let data = evt.data.tabview;
  5188. if (data.eventType === "yt-page-type-changed") {
  5189. let detail = data.eventDetail
  5190. let { newPageType, oldPageType } = detail;
  5191. if (newPageType && oldPageType) {
  5192. let bool = false;
  5193. if (newPageType == 'ytd-watch-flexy') {
  5194. bool = true;
  5195. pageType = 'watch';
  5196. } else if (newPageType == 'ytd-browse') {
  5197. pageType = 'browse';
  5198. }
  5199. document.documentElement.classList.toggle('tabview-normal-player', bool)
  5200. }
  5201. }
  5202. }
  5203. }, bubblePassive);
  5204.  
  5205.  
  5206. globalHook('data-changed', (evt) => {
  5207.  
  5208. if (!scriptEnable && tabsDeferred.resolved) { return }
  5209.  
  5210. let nodeName = (((evt || 0).target || 0).nodeName || '').toUpperCase()
  5211.  
  5212. if (nodeName !== 'YTD-THUMBNAIL-OVERLAY-TOGGLE-BUTTON-RENDERER') return;
  5213.  
  5214. document.dispatchEvent(new CustomEvent("tabview-fix-popup-refit"));
  5215.  
  5216. })
  5217.  
  5218.  
  5219. DEBUG_LOG && globalHook('yt-rendererstamper-finished', (evt) => {
  5220.  
  5221. if (!scriptEnable && tabsDeferred.resolved) { return }
  5222. // might occur before initialization
  5223.  
  5224. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5225.  
  5226. const nodeName = evt.target.nodeName.toUpperCase();
  5227.  
  5228. // const S_GENERAL_RENDERERS = ['YTD-TOGGLE-BUTTON-RENDERER','YTD-MENU-RENDERER']
  5229. if (S_GENERAL_RENDERERS.includes(nodeName)) {
  5230. return;
  5231. }
  5232.  
  5233. _console.log(evt.target.nodeName, 904, evt.type, evt.detail);
  5234.  
  5235. });
  5236.  
  5237. DEBUG_LOG && globalHook('data-changed', (evt) => {
  5238.  
  5239. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5240.  
  5241. let nodeName = evt.target.nodeName.toUpperCase()
  5242. _console.log(nodeName, evt.type)
  5243.  
  5244. if (nodeName === 'YTD-ITEM-SECTION-RENDERER' || nodeName === 'YTD-COMMENTS') {
  5245.  
  5246. _console.log(344)
  5247.  
  5248. }
  5249.  
  5250. })
  5251.  
  5252. DEBUG_LOG && globalHook('yt-navigate', (evt) => {
  5253.  
  5254. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5255. _console.log(evt.target.nodeName, evt.type)
  5256.  
  5257. })
  5258.  
  5259. DEBUG_LOG && globalHook('ytd-playlist-lockup-now-playing-active', (evt) => {
  5260.  
  5261. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5262. _console.log(evt.target.nodeName, evt.type)
  5263.  
  5264.  
  5265. })
  5266.  
  5267. DEBUG_LOG && globalHook('yt-service-request-completed', (evt) => {
  5268.  
  5269. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5270. _console.log(evt.target.nodeName, evt.type)
  5271.  
  5272.  
  5273. })
  5274.  
  5275. DEBUG_LOG && globalHook('yt-commerce-action-done', (evt) => {
  5276.  
  5277. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5278. _console.log(evt.target.nodeName, evt.type)
  5279.  
  5280.  
  5281. })
  5282.  
  5283. DEBUG_LOG && globalHook('yt-execute-service-endpoint', (evt) => {
  5284.  
  5285. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5286. _console.log(evt.target.nodeName, evt.type)
  5287.  
  5288.  
  5289. })
  5290.  
  5291.  
  5292. DEBUG_LOG && globalHook('yt-request-panel-mode-change', (evt) => {
  5293.  
  5294. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5295. _console.log(evt.target.nodeName, evt.type)
  5296.  
  5297.  
  5298. })
  5299.  
  5300.  
  5301. DEBUG_LOG && globalHook('yt-visibility-refresh', (evt) => {
  5302.  
  5303. if (!evt || !evt.target /*|| evt.target.nodeType !== 1*/) return;
  5304. _console.log(evt.target.nodeName || '', evt.type)
  5305.  
  5306. const ytdFlexyElm = es.ytdFlexy;
  5307. _console.log(2784, evt.type, (ytdFlexyElm ? ytdFlexyElm.hasAttribute('hidden') : null), evt.detail)
  5308.  
  5309. _console.log(evt.detail)
  5310.  
  5311.  
  5312. })
  5313.  
  5314. DEBUG_LOG && globalHook('yt-request-panel-mode-change', (evt) => {
  5315.  
  5316. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5317. _console.log(evt.target.nodeName, evt.type)
  5318.  
  5319.  
  5320. })
  5321.  
  5322. DEBUG_LOG && globalHook('app-reset-layout', (evt) => {
  5323.  
  5324. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5325. _console.log(evt.target.nodeName, evt.type)
  5326.  
  5327.  
  5328. })
  5329. DEBUG_LOG && globalHook('yt-guide-close', (evt) => {
  5330.  
  5331. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5332. _console.log(evt.target.nodeName, evt.type)
  5333.  
  5334.  
  5335. })
  5336. DEBUG_LOG && globalHook('yt-page-data-will-change', (evt) => {
  5337.  
  5338. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5339. _console.log(evt.target.nodeName, evt.type)
  5340.  
  5341.  
  5342. })
  5343.  
  5344. DEBUG_LOG && globalHook('yt-retrieve-location', (evt) => {
  5345.  
  5346. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5347. _console.log(evt.target.nodeName, evt.type)
  5348.  
  5349.  
  5350. })
  5351.  
  5352. DEBUG_LOG && globalHook('yt-refit', (evt) => {
  5353.  
  5354. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5355. _console.log(evt.target.nodeName, evt.type)
  5356.  
  5357. })
  5358.  
  5359. DEBUG_LOG && globalHook('addon-attached', (evt) => {
  5360.  
  5361. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5362. _console.log(evt.target.nodeName, evt.type)
  5363.  
  5364. })
  5365.  
  5366. DEBUG_LOG && globalHook('yt-live-chat-context-menu-opened', (evt) => {
  5367.  
  5368. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5369. _console.log(evt.target.nodeName, evt.type)
  5370.  
  5371. })
  5372.  
  5373. DEBUG_LOG && globalHook('yt-live-chat-context-menu-closed', (evt) => {
  5374.  
  5375. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5376. _console.log(evt.target.nodeName, evt.type)
  5377.  
  5378. })
  5379.  
  5380. DEBUG_LOG && globalHook('yt-commentbox-resize', (evt) => {
  5381.  
  5382. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5383. _console.log(evt.target.nodeName, evt.type)
  5384. })
  5385.  
  5386. DEBUG_LOG && globalHook('yt-rich-grid-layout-refreshed', (evt) => {
  5387.  
  5388. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5389. _console.log(2327, evt.target.nodeName, evt.type)
  5390. })
  5391.  
  5392. DEBUG_LOG && globalHook('animationend', (evt) => {
  5393.  
  5394. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5395. _console.log(evt.target.nodeName, evt.type)
  5396.  
  5397.  
  5398. })
  5399.  
  5400. DEBUG_LOG && globalHook('yt-dismissible-item-dismissed', (evt) => {
  5401.  
  5402. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5403. _console.log(evt.target.nodeName, evt.type)
  5404.  
  5405.  
  5406. })
  5407.  
  5408. DEBUG_LOG && globalHook('yt-dismissible-item-undismissed', function (evt) {
  5409.  
  5410. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5411. _console.log(evt.target.nodeName, evt.type)
  5412.  
  5413.  
  5414. })
  5415.  
  5416.  
  5417. DEBUG_LOG && globalHook('yt-load-next-continuation', function (evt) {
  5418.  
  5419. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5420. _console.log(evt.target.nodeName, evt.type)
  5421.  
  5422.  
  5423. })
  5424.  
  5425.  
  5426. DEBUG_LOG && globalHook('yt-load-reload-continuation', function (evt) {
  5427.  
  5428. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5429. _console.log(evt.target.nodeName, evt.type)
  5430.  
  5431.  
  5432. })
  5433.  
  5434. DEBUG_LOG && globalHook('yt-toggle-button', function (evt) {
  5435.  
  5436. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5437. _console.log(evt.target.nodeName, evt.type)
  5438.  
  5439.  
  5440. })
  5441.  
  5442.  
  5443. }
  5444.  
  5445.  
  5446.  
  5447.  
  5448. function addIframeStyle(cDoc) {
  5449. if (cDoc.querySelector('#tyt-chatroom-css')) return false;
  5450. addStyle((iframeCSS() || ''), cDoc.documentElement).id = 'tyt-chatroom-css'
  5451. return true;
  5452. }
  5453.  
  5454. function chatFrameContentDocument() {
  5455. // non-null if iframe exist && contentDocument && readyState = complete
  5456. /** @type {HTMLIFrameElement | null} */
  5457. let iframe = document.querySelector('ytd-live-chat-frame iframe#chatframe');
  5458. if (!iframe) return null; //iframe must be there
  5459. /** @type {Document | null} */
  5460. let cDoc = null;
  5461. try {
  5462. cDoc = iframe.contentDocument;
  5463. } catch (e) { }
  5464. if (!cDoc) return null;
  5465. if (cDoc.readyState != 'complete') return null; //we must wait for its completion
  5466.  
  5467. return cDoc;
  5468.  
  5469. }
  5470.  
  5471. function chatFrameElement(/** @type {string} */ cssSelector) {
  5472. let cDoc = chatFrameContentDocument();
  5473. if (!cDoc) return null;
  5474. /** @type {HTMLElement | null} */
  5475. let elm = null;
  5476. try {
  5477. elm = cDoc.querySelector(cssSelector)
  5478. } catch (e) {
  5479. console.log('iframe error', e)
  5480. }
  5481. return elm;
  5482. }
  5483.  
  5484.  
  5485. function forceDisplayChatReplay() {
  5486. let items = chatFrameElement('yt-live-chat-item-list-renderer #items');
  5487. if (items && items.childElementCount !== 0) return;
  5488.  
  5489. let videoElm = document.querySelector('ytd-player#ytd-player video');
  5490.  
  5491. let ct = videoElm.currentTime;
  5492. if (ct >= 0 && !videoElm.ended && videoElm.readyState > videoElm.HAVE_CURRENT_DATA) {
  5493. let chat = document.querySelector('ytd-live-chat-frame#chat');
  5494. if (chat) {
  5495. nativeFunc(chat, "postToContentWindow", [{ "yt-player-video-progress": ct }])
  5496. }
  5497. }
  5498.  
  5499. }
  5500.  
  5501. function checkIframeDblClick() {
  5502. setTimeout(() => {
  5503.  
  5504. let Itemslist = chatFrameElement('#contents.yt-live-chat-renderer');
  5505. if (Itemslist && typeof Itemslist.ondblclick === 'function') iframePointEventsAllow = true;
  5506.  
  5507. if (iframePointEventsAllow) {
  5508. chatFrameElement('body').classList.add('tabview-allow-pointer-events');
  5509. }
  5510.  
  5511. }, 300)
  5512. }
  5513.  
  5514. function addPopupButton(chat) {
  5515. let showHideBtn = chat.querySelector('div#show-hide-button')
  5516. if (showHideBtn) {
  5517.  
  5518. let btn;
  5519. btn = document.querySelector('tyt-iframe-popup-btn')
  5520. if (btn) btn.remove();
  5521.  
  5522. btn = document.createElement('tyt-iframe-popup-btn')
  5523. elementAppend.call(showHideBtn, btn)
  5524. // console.log(334,2)
  5525. btn.dispatchEvent(new CustomEvent('tyt-iframe-popup-btn-setup'))
  5526. }
  5527.  
  5528. }
  5529.  
  5530. function iFrameContentReady(cDoc) {
  5531.  
  5532. // console.log(702, 1)
  5533. if (!cDoc) return;
  5534.  
  5535. // console.log(702, 2)
  5536. if (addIframeStyle(cDoc) === false) return;
  5537.  
  5538. // console.log(702, 3)
  5539. let frc = 0;
  5540. let cid = 0;
  5541.  
  5542. let fullReady = () => {
  5543.  
  5544. // console.log(702, 4)
  5545. if (!cDoc.documentElement.hasAttribute('style') && ++frc < 900) return;
  5546. clearInterval(cid);
  5547.  
  5548. // console.log(702, 5)
  5549. if (!scriptEnable || !isChatExpand()) return;
  5550.  
  5551. // console.log(702, 6)
  5552. let iframe = document.querySelector('body ytd-watch-flexy ytd-live-chat-frame iframe#chatframe');
  5553.  
  5554. // console.log(702, 7)
  5555. if (!iframe) return; //prevent iframe is detached from the page
  5556.  
  5557. // console.log(702, 8)
  5558. if (cDoc.querySelector('yt-live-chat-renderer #continuations')) {
  5559.  
  5560. // console.log(702, 9)
  5561. let chatFrame = document.querySelector('ytd-live-chat-frame#chat');
  5562. if (chatFrame) {
  5563. chatFrame.setAttribute('tyt-iframe-loaded', '')
  5564. // console.log(711, chatFrame)
  5565.  
  5566.  
  5567. // console.log(702, 10)
  5568. forceDisplayChatReplay();
  5569. checkIframeDblClick(); // user request for compatible with https://greasyfork.org/en/scripts/452335
  5570. iframe.dispatchEvent(new CustomEvent("tabview-chatroom-ready"))
  5571. // console.log(334,1)
  5572. addPopupButton(chatFrame)
  5573.  
  5574. }
  5575. }
  5576.  
  5577.  
  5578. }
  5579. cid = setInterval(fullReady, 10)
  5580. fullReady();
  5581.  
  5582.  
  5583. }
  5584.  
  5585. let iframeLoadHookA_id = 0
  5586.  
  5587. const iframeLoadHookA = function (evt) {
  5588.  
  5589.  
  5590. let isIframe = (((evt || 0).target || 0).nodeName === 'IFRAME');
  5591.  
  5592. if (isIframe && evt.target.matches('body iframe.style-scope.ytd-live-chat-frame#chatframe')) {
  5593. } else {
  5594. return;
  5595. }
  5596.  
  5597. let iframe = evt.target;
  5598. let tid = ++iframeLoadHookA_id;
  5599.  
  5600. // console.log(701, 2)
  5601. new Promise(resolve => {
  5602. if (tid !== iframeLoadHookA_id) return
  5603.  
  5604. // console.log(701, 3)
  5605. let k = 270
  5606. let cid = setInterval(() => {
  5607.  
  5608. if (tid !== iframeLoadHookA_id) return
  5609.  
  5610. if (!cid) return;
  5611.  
  5612. if (k-- < 1) {
  5613. clearInterval(cid);
  5614. cid = 0;
  5615. return resolve(false);
  5616. }
  5617.  
  5618. let cDoc = iframe.contentDocument;
  5619. if (!cDoc) return null;
  5620. if (cDoc.readyState != 'complete') return;
  5621. if (!cDoc.querySelector('body')) {
  5622. clearInterval(cid);
  5623. cid = 0;
  5624. return resolve(false);
  5625. }
  5626.  
  5627. if (!cDoc.querySelector('yt-live-chat-app')) return;
  5628.  
  5629. clearInterval(cid);
  5630. cid = 0;
  5631.  
  5632. if (!document.contains(iframe)) return resolve(false);
  5633.  
  5634. resolve([cDoc, iframe]);
  5635.  
  5636. cDoc = null
  5637.  
  5638. iframe = null
  5639.  
  5640.  
  5641. }, 17)
  5642.  
  5643.  
  5644. }).then((res) => {
  5645.  
  5646.  
  5647. // console.log(701, 4, res)
  5648. if (tid !== iframeLoadHookA_id) return
  5649.  
  5650. // console.log(701, 5)
  5651. if (!res) return;
  5652.  
  5653. // console.log(701, 6)
  5654.  
  5655. const [cDoc, iframe] = res
  5656.  
  5657. iFrameContentReady(cDoc)
  5658. iframe.dispatchEvent(new CustomEvent('tabview-chatframe-loaded'))
  5659.  
  5660.  
  5661. })
  5662.  
  5663.  
  5664.  
  5665. }
  5666.  
  5667. async function restorePIPforStickyHead(){
  5668. // after a trusted user action, PIP can be cancelled.
  5669. // this is to ensure enterPIP can be re-excecuted
  5670.  
  5671. if(isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation){
  5672. userActivation = false;
  5673. exitPIP();
  5674. }
  5675. }
  5676.  
  5677. let videosDeferred = new Deferred();
  5678.  
  5679. let _navigateLoadDT = 0;
  5680.  
  5681. function delayedClickHandler(){
  5682.  
  5683. if(isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled){
  5684. restorePIPforStickyHead();
  5685. } else if (!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && typeof IntersectionObserver == 'function') {
  5686. enablePIPforStickyHead();
  5687. }
  5688.  
  5689. }
  5690.  
  5691. function setupTabBtns(){
  5692.  
  5693. const materialTab = document.querySelector("#material-tabs")
  5694. if (!materialTab) return;
  5695.  
  5696. if (tabsUiScript_setclick) return;
  5697. tabsUiScript_setclick = true;
  5698.  
  5699. let fontSizeBtnClick = null;
  5700.  
  5701. materialTab.addEventListener('click', function (evt) {
  5702.  
  5703. if (!evt.isTrusted) return; // prevent call from background
  5704. if(isMiniviewForStickyHeadEnabled){
  5705. setTimeout(delayedClickHandler, 80);
  5706. } else if (!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && typeof IntersectionObserver == 'function') {
  5707. setTimeout(delayedClickHandler, 80);
  5708. }
  5709. let dom = evt.target;
  5710. if ((dom || 0).nodeType !== 1) return;
  5711.  
  5712. const domInteraction = dom.getAttribute('tyt-di');
  5713. if (domInteraction === 'q9Kjc') {
  5714. handlerMaterialTabClick.call(dom, evt)
  5715. } else if (domInteraction === '8rdLQ') {
  5716. fontSizeBtnClick.call(dom, evt)
  5717. }
  5718.  
  5719.  
  5720. }, true)
  5721.  
  5722. function updateCSS_fontsize(store) {
  5723.  
  5724. if (!store) return;
  5725.  
  5726. const ytdFlexyElm = es.ytdFlexy;
  5727. if (ytdFlexyElm) {
  5728. if (store['font-size-#tab-info']) ytdFlexyElm.style.setProperty('--ut2257-info', store['font-size-#tab-info'])
  5729. if (store['font-size-#tab-comments']) ytdFlexyElm.style.setProperty('--ut2257-comments', store['font-size-#tab-comments'])
  5730. if (store['font-size-#tab-videos']) ytdFlexyElm.style.setProperty('--ut2257-videos', store['font-size-#tab-videos'])
  5731. if (store['font-size-#tab-list']) ytdFlexyElm.style.setProperty('--ut2257-list', store['font-size-#tab-list'])
  5732. document.dispatchEvent(new CustomEvent("tabview-zoom-updated"));
  5733. }
  5734.  
  5735. }
  5736.  
  5737. fontSizeBtnClick = function (evt) {
  5738.  
  5739. evt.preventDefault();
  5740. evt.stopPropagation();
  5741. evt.stopImmediatePropagation();
  5742.  
  5743. /** @type {HTMLElement | null} */
  5744. let dom = evt.target;
  5745. if (!dom) return;
  5746.  
  5747.  
  5748. let value = dom.classList.contains('font-size-plus') ? 1 : dom.classList.contains('font-size-minus') ? -1 : 0;
  5749.  
  5750. let active_tab_content = closestDOM.call(dom, '[tyt-tab-content]').getAttribute('tyt-tab-content');
  5751.  
  5752. let store = getStore();
  5753. let settingKey = `font-size-${active_tab_content}`
  5754. if (!store[settingKey]) store[settingKey] = 1.0;
  5755. if (value < 0) store[settingKey] -= 0.05;
  5756. else if (value > 0) store[settingKey] += 0.05;
  5757. if (store[settingKey] < 0.1) store[settingKey] = 0.1;
  5758. else if (store[settingKey] > 10) store[settingKey] = 10.0;
  5759. setStore(store);
  5760.  
  5761.  
  5762. store = getStore();
  5763. updateCSS_fontsize(store);
  5764.  
  5765. }
  5766.  
  5767.  
  5768. function getDefaultTabBtnSetting(store){
  5769. if (!store) return;
  5770. let myDefaultTab= store[key_default_tab];
  5771. if (!myDefaultTab || typeof myDefaultTab !== 'string' || !/^\#[a-zA-Z\_\-\+]+$/.test(myDefaultTab)) return;
  5772. if (document.querySelector(`.tab-btn[tyt-tab-content="${myDefaultTab}"]:not(.tab-btn-hidden)`)) settings.defaultTab = myDefaultTab;
  5773.  
  5774. }
  5775.  
  5776. let store = getStore();
  5777. updateCSS_fontsize(store);
  5778. getDefaultTabBtnSetting(store);
  5779.  
  5780. }
  5781.  
  5782. function setMyDefaultTab(myDefaultTab_tmp){
  5783.  
  5784. let myDefaultTab_final = null
  5785. if (myDefaultTab_tmp && typeof myDefaultTab_tmp === 'string' && /^\#[a-zA-Z\_\-\+]+$/.test(myDefaultTab_tmp)){
  5786. if (document.querySelector(`.tab-btn[tyt-tab-content="${myDefaultTab_tmp}"]`)) myDefaultTab_final = myDefaultTab_tmp;
  5787. }
  5788.  
  5789. let store = getStore();
  5790. if(myDefaultTab_final) {
  5791. store[key_default_tab] = myDefaultTab_final;
  5792. settings.defaultTab = myDefaultTab_final;
  5793. } else {
  5794. delete store[key_default_tab];
  5795. settings.defaultTab = SETTING_DEFAULT_TAB_0;
  5796. }
  5797. setStore(store);
  5798.  
  5799. }
  5800. document.addEventListener('tabview-setMyDefaultTab', function (evt) {
  5801.  
  5802. let myDefaultTab_tmp = ((evt || 0).detail || 0).myDefaultTab
  5803.  
  5804. setMyDefaultTab(myDefaultTab_tmp)
  5805.  
  5806. }, false)
  5807.  
  5808. async function onNavigationEndAsync(isPageFirstLoaded) {
  5809.  
  5810. if (pageType !== 'watch') return
  5811.  
  5812.  
  5813. let tdt = Date.now();
  5814. _navigateLoadDT = tdt;
  5815.  
  5816. // avoid blocking the page when youtube is initializing the page
  5817. const promiseDelay = new Promise(requestAnimationFrame)
  5818. const promiseVideoRendered = videosDeferred.d()
  5819. await Promise.all([promiseVideoRendered, promiseDelay])
  5820.  
  5821. if (_navigateLoadDT !== tdt) return;
  5822. if (ytEventSequence !== 3) return;
  5823.  
  5824. const ytdFlexyElm = document.querySelector('ytd-watch-flexy')
  5825.  
  5826. if (!ytdFlexyElm) {
  5827. ytdFlexy = null
  5828. return;
  5829. }
  5830.  
  5831. scriptEnable = true;
  5832.  
  5833. ytdFlexy = mWeakRef(ytdFlexyElm)
  5834.  
  5835. const related = querySelectorFromAnchor.call(ytdFlexyElm, "#related.ytd-watch-flexy");
  5836. if (!related) return;
  5837.  
  5838. // isPageFirstLoaded && console.time("Tabview Youtube Render")
  5839.  
  5840. if (!document.querySelector("#right-tabs")) {
  5841. getLangForPage();
  5842. let docTmp = document.createElement('template');
  5843. docTmp.innerHTML = getTabsHTML();
  5844. let newElm = docTmp.content.firstElementChild;
  5845. if (newElm !== null) {
  5846. insertBeforeTo(newElm, related);
  5847. querySelectorFromAnchor.call(newElm, '#material-tabs').addEventListener('mousemove', (evt)=>{
  5848. evt.preventDefault();
  5849. evt.stopPropagation();
  5850. evt.stopImmediatePropagation();
  5851. }, true);
  5852. setupTabBtns();
  5853. console.debug('[tyt] #right-tabs inserted')
  5854. }
  5855. docTmp.textContent = '';
  5856. docTmp = null;
  5857. }
  5858.  
  5859. if (!ytdFlexyElm.hasAttribute('tyt-tab')) ytdFlexyElm.setAttribute('tyt-tab', '')
  5860.  
  5861. // append the next videos
  5862. // it exists as "related" is already here
  5863. fixTabs();
  5864. let switchToDefaultTabNotAllowed = false;
  5865.  
  5866. if (document.querySelector('ytd-watch-flexy[tyt-chat^="+"]')){
  5867. switchToDefaultTabNotAllowed = true;
  5868. } else if (document.querySelector('ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"]:not([hidden])')) {
  5869. switchToDefaultTabNotAllowed = true;
  5870. } else if (document.querySelector('ytd-watch-flexy ytd-donation-shelf-renderer.ytd-watch-flexy:not([hidden]):not(:empty)')) {
  5871. switchToDefaultTabNotAllowed = true;
  5872. }
  5873.  
  5874. if (switchToDefaultTabNotAllowed) {
  5875. switchTabActivity(null);
  5876. } else {
  5877. setToActiveTab(); // just switch to the default tab
  5878. }
  5879.  
  5880.  
  5881. mtoFlexyAttr.clear(true)
  5882. mtf_checkFlexy()
  5883.  
  5884. tabsDeferred.resolve();
  5885. FP.mtf_attrEngagementPanel(); // check whether no visible panels
  5886.  
  5887. // isPageFirstLoaded && console.timeEnd("Tabview Youtube Render")
  5888.  
  5889. // let ks = renderIdentifier;
  5890. // renderDeferred.debounce(() => {
  5891. // if (ks !== renderIdentifier) return
  5892. // if (_navigateLoadDT !== tdt) return;
  5893. // let donationShelf = document.querySelector('ytd-watch-flexy:not([tyt-donation-shelf]) ytd-donation-shelf-renderer.ytd-watch-flexy:not([hidden]):not(:empty)');
  5894. // if (donationShelf) {
  5895. // // console.log(334)
  5896. // // ignored if event handler for tabview-donation-shelf-set-visibility is not yet hooked.
  5897. // setTimeout(()=>{
  5898. // if (ks !== renderIdentifier) return
  5899. // if (_navigateLoadDT !== tdt) return;
  5900. // // console.log(554)
  5901. // let donationShelf = document.querySelector('ytd-watch-flexy:not([tyt-donation-shelf]) ytd-donation-shelf-renderer.ytd-watch-flexy:not([hidden]):not(:empty)');
  5902. // if(!donationShelf) return;
  5903. // document.dispatchEvent(new CustomEvent('tabview-donation-shelf-set-visibility', {
  5904. // detail: {
  5905. // visibility: true,
  5906. // flushDOM: true
  5907. // }
  5908. // }));
  5909. // },450)
  5910. // }
  5911. // donationShelf = null;
  5912.  
  5913. // })
  5914.  
  5915. isPageFirstLoaded && document.documentElement.removeAttribute('tyt-lock')
  5916.  
  5917. }
  5918.  
  5919.  
  5920. function fetchCommentsFinished() {
  5921. const ytdFlexyElm = es.ytdFlexy;
  5922. if (!scriptEnable || !ytdFlexyElm) return;
  5923. if (mtf_forceCheckLiveVideo_disable === 2) return;
  5924. ytdFlexyElm.setAttribute('tyt-comments', 'L');
  5925. _console.log(2909, 1)
  5926. }
  5927.  
  5928. function setCommentSection( /** @type {number} */ value) {
  5929.  
  5930. Q.comments_section_loaded = value;
  5931. if (value === 0 && fetchCounts) {
  5932. fetchCounts.fetched = false; // unknown bug
  5933. }
  5934.  
  5935. }
  5936.  
  5937.  
  5938. function emptyCommentSection() {
  5939. let tab_btn = document.querySelector('.tab-btn[tyt-tab-content="#tab-comments"]')
  5940. if (tab_btn) {
  5941. let span = querySelectorFromAnchor.call(tab_btn, 'span#tyt-cm-count');
  5942. tab_btn.removeAttribute('loaded-comment')
  5943. if (span) {
  5944. span.textContent = '';
  5945. }
  5946. }
  5947. setCommentSection(0);
  5948. _console.log(7233, 'comments_section_loaded = 0')
  5949. }
  5950.  
  5951.  
  5952. function _disableComments() {
  5953.  
  5954.  
  5955. _console.log(2909, 1)
  5956. if (!scriptEnable) return;
  5957. let cssElm = es.ytdFlexy;
  5958. if (!cssElm) return;
  5959.  
  5960. _console.log(2909, 2)
  5961.  
  5962.  
  5963. let comments = document.querySelector('ytd-comments#comments')
  5964. if (mtf_forceCheckLiveVideo_disable === 2) {
  5965. // earlier than DOM change
  5966. } else {
  5967. if (comments && !comments.hasAttribute('hidden')) return; // visible comments content)
  5968. }
  5969.  
  5970. _console.log(2909, 4)
  5971. if (Q.comments_section_loaded === 2) return; //already disabled
  5972.  
  5973. setCommentSection(2);
  5974.  
  5975. _console.log(2909, 5)
  5976.  
  5977. let tabBtn = document.querySelector('.tab-btn[tyt-tab-content="#tab-comments"]');
  5978. if (tabBtn) {
  5979. let span = querySelectorFromAnchor.call(tabBtn, 'span#tyt-cm-count');
  5980. tabBtn.removeAttribute('loaded-comment')
  5981. if (!tabBtn.classList.contains('tab-btn-hidden')) {
  5982. //console.log('hide', comments, comments && comments.hasAttribute('hidden'))
  5983. hideTabBtn(tabBtn)
  5984. }
  5985. if (span) {
  5986. span.textContent = '';
  5987. }
  5988. }
  5989.  
  5990. cssElm.setAttribute('tyt-comments', 'D');
  5991.  
  5992. _console.log(2909, 10)
  5993.  
  5994.  
  5995. }
  5996.  
  5997.  
  5998. function setKeywords() {
  5999.  
  6000. return;
  6001.  
  6002. if (typeof String.prototype.replacei !== 'function') {
  6003. // reference: https://stackoverflow.com/questions/7313395/case-insensitive-replace-all
  6004. String.replacei = String.prototype.replacei = function (rep, rby) {
  6005. var pos = this.toLowerCase().indexOf(rep.toLowerCase());
  6006. return pos == -1 ? this : this.substring(0, pos) + rby(this.substring(pos, pos + rep.length)) + this.substring(pos + rep.length);
  6007. };
  6008. }
  6009.  
  6010. let data = pageFetchedData;
  6011. console.log(data)
  6012.  
  6013.  
  6014. let keywords = ((((data || 0).pageData || 0).playerResponse || 0).videoDetails || 0).keywords;
  6015. console.log(keywords)
  6016.  
  6017. if (keywords && keywords.length > 0) {
  6018.  
  6019.  
  6020. let title = '';
  6021.  
  6022. try {
  6023. title = ((((data || 0).pageData || 0).response || 0).contents || 0).twoColumnWatchNextResults.results.results.contents[0].videoPrimaryInfoRenderer.title.runs[0].text;
  6024. if (typeof title !== 'string') title = '';
  6025. } catch (e) { }
  6026.  
  6027. let strText = title;
  6028.  
  6029. let tabsDeferredSess = pageSession.session();
  6030. if (!scriptEnable && tabsDeferred.resolved) { }
  6031. else tabsDeferred.debounce(() => {
  6032.  
  6033. if (!tabsDeferredSess.isValid) return;
  6034. tabsDeferredSess = null;
  6035.  
  6036.  
  6037. let res = [];
  6038. for (const keyword of keywords) {
  6039. if (strText.toUpperCase().includes(keyword.toUpperCase())) {
  6040. res.push(keyword);
  6041. }
  6042. }
  6043. if (res.length > 0) {
  6044. console.log('tabview video keywords', res)
  6045. window.postMessage({
  6046. tabview: {
  6047. eventType: 0x3700,
  6048. eventDetail: {
  6049. keywords: res
  6050. }
  6051. }
  6052. }, location.origin);
  6053. }
  6054.  
  6055.  
  6056.  
  6057. let strElms = document.querySelectorAll('#title.ytd-watch-metadata yt-formatted-string.style-scope.ytd-watch-metadata');
  6058. //console.log(keywords,strElms)
  6059. for (const strElm of strElms) {
  6060. if (strElm.id == 'super-title' || strElm.id == 'original-info') {
  6061.  
  6062. } else {
  6063. if (strElm.querySelector('*')) {
  6064.  
  6065. } else {
  6066. /** @type{string} */
  6067. let strText = strElm.textContent;
  6068. if (strText) {
  6069.  
  6070. let res = [];
  6071. for (const keyword of keywords) {
  6072. if (strText.toUpperCase().includes(keyword.toUpperCase())) {
  6073. res.push(keyword);
  6074. }
  6075. }
  6076. if (res.length > 0) {
  6077. console.log('tabview video keywords', res)
  6078.  
  6079. if (res.length > 1) res.sort((a, b) => { return b.length - a.length });
  6080. let usedKeywords = {};
  6081. for (const s of res) {
  6082. strText = strText.replacei(s, ((s) => {
  6083. usedKeywords[s] = true;
  6084. return `\n${s}\n`
  6085. }))
  6086. }
  6087. strText = strText.replace(`\n\n+`, '\n')
  6088. let retElms = strText.split('\n').map(w => {
  6089. let elm = document.createElement('tabview-txt')
  6090. if (usedKeywords[w]) elm.classList.add('tabview-title-keyword')
  6091. elm.textContent = w;
  6092. return elm
  6093. })
  6094.  
  6095. let p = querySelectorFromAnchor.call(strElm.parentNode, '.tabview-txt');
  6096.  
  6097. if (!p) {
  6098. p = strElm.cloneNode(false)
  6099. p.classList.add('tabview-txt')
  6100. strElm.after(p);
  6101. } else {
  6102. strElm.after(p);
  6103. }
  6104.  
  6105. requestAnimationFrame(() => {
  6106.  
  6107. p.textContent = 'x';
  6108. p.firstChild.replaceWith(...retElms);
  6109. p.removeAttribute('is-empty')
  6110. strElm.setAttribute('is-empty', '')
  6111.  
  6112. })
  6113.  
  6114.  
  6115. }
  6116. break;
  6117. }
  6118. }
  6119. }
  6120. }
  6121.  
  6122. })
  6123.  
  6124. }
  6125.  
  6126.  
  6127. }
  6128.  
  6129. function setToggleInfo() {
  6130.  
  6131. scriptletDeferred.d().then(() => {
  6132.  
  6133. let elem = document.querySelector('#primary.ytd-watch-flexy #below ytd-watch-metadata #info-container.ytd-watch-metadata:first-child:not([tyt-info-toggler])')
  6134. if (elem) {
  6135.  
  6136. elem.setAttribute('tyt-info-toggler', '')
  6137. elem.dispatchEvent(new CustomEvent('tyt-info-toggler'))
  6138.  
  6139. }
  6140.  
  6141. });
  6142. }
  6143.  
  6144.  
  6145. function flexyAttr_toggleFlag(mFlag, b, flag) {
  6146. return b ? (mFlag | flag) : (mFlag & ~flag);
  6147. }
  6148.  
  6149. function flexAttr_toLayoutStatus(nls, attributeName) {
  6150.  
  6151. let attrElm, b, v;
  6152. switch (attributeName) {
  6153. case 'theater':
  6154. b = isTheater();
  6155. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_THEATER);
  6156. break;
  6157. case 'tyt-chat':
  6158. attrElm = es.ytdFlexy;
  6159. v = attrElm.getAttribute('tyt-chat');
  6160.  
  6161. if (v !== null && v.charAt(0) === '-') {
  6162. nls = flexyAttr_toggleFlag(nls, true, LAYOUT_CHATROOM | LAYOUT_CHATROOM_COLLAPSED);
  6163. } else {
  6164. nls = flexyAttr_toggleFlag(nls, v !== null, LAYOUT_CHATROOM);
  6165. nls = flexyAttr_toggleFlag(nls, false, LAYOUT_CHATROOM_COLLAPSED);
  6166. }
  6167.  
  6168. break;
  6169. case 'is-two-columns_':
  6170. b = isWideScreenWithTwoColumns();
  6171. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_TWO_COLUMNS);
  6172. break;
  6173.  
  6174. case 'tyt-tab':
  6175. attrElm = es.ytdFlexy;
  6176. b = isNonEmptyString(attrElm.getAttribute('tyt-tab'));
  6177. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_TAB_EXPANDED);
  6178. break;
  6179.  
  6180. case 'fullscreen':
  6181. attrElm = es.ytdFlexy;
  6182. b = attrElm.hasAttribute('fullscreen');
  6183. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_FULLSCREEN);
  6184. break;
  6185.  
  6186. case 'tyt-ep-visible':
  6187. attrElm = es.ytdFlexy;
  6188. v = attrElm.getAttribute('tyt-ep-visible');
  6189. b = (+v > 0)
  6190. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_ENGAGEMENT_PANEL_EXPANDED);
  6191. break;
  6192.  
  6193. case 'tyt-donation-shelf':
  6194. attrElm = es.ytdFlexy;
  6195. b = attrElm.hasAttribute('tyt-donation-shelf');
  6196. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_DONATION_SHELF_EXPANDED);
  6197. break;
  6198.  
  6199. }
  6200.  
  6201. return nls;
  6202.  
  6203.  
  6204. }
  6205.  
  6206.  
  6207.  
  6208. function ito_details(entries, observer) {
  6209. if (!detailsTriggerReset) return;
  6210. if (!entries || entries.length !== 1) return; // unlikely
  6211. let entry = entries[0];
  6212. //console.log(entries)
  6213. if (entry.isIntersecting === true) {
  6214.  
  6215. if (fT(wls.layoutStatus, LAYOUT_TWO_COLUMNS | LAYOUT_FULLSCREEN, 0) === false) return;
  6216.  
  6217. let dom = entry.target;
  6218. if (!dom) return; //unlikely
  6219.  
  6220. let bool = false;
  6221. let descClickable = null;
  6222. if (fT(wls.layoutStatus, 0, LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED | LAYOUT_CHATROOM_EXPANDED | LAYOUT_TAB_EXPANDED) === false) {
  6223. descClickable = closestDOM.call(dom, '#description.item.style-scope.ytd-watch-metadata')
  6224. if (descClickable) {
  6225. detailsTriggerReset = false;
  6226. bool = true;
  6227. }
  6228. }
  6229.  
  6230. async function runAsync(dom, bool) {
  6231.  
  6232. if (bool) {
  6233. let descClickable = closestDOM.call(dom, '#description.item.style-scope.ytd-watch-metadata')
  6234. if (descClickable) {
  6235. descClickable.click();
  6236. }
  6237. }
  6238.  
  6239. await new Promise(r => setTimeout(r, 20));
  6240.  
  6241. let pInner, nw = null;
  6242. try {
  6243. let x = closestDOM.call(dom, '#description.item.style-scope.ytd-watch-metadata');
  6244. let h2 = x.offsetHeight;
  6245. pInner = closestDOM.call(x, '#primary-inner')
  6246. let h1 = pInner.offsetHeight;
  6247. x.setAttribute('userscript-scrollbar-render', '')
  6248. if (h1 > h2 && h2 > 0 && h1 > 0) nw = h1 - h2
  6249. } catch (e) { }
  6250. if(pInner){
  6251. pInner.style.setProperty('--tyt-desc-top-h', `${nw ? nw : 0}px`)
  6252. }
  6253. }
  6254.  
  6255. runAsync(dom, bool);
  6256.  
  6257.  
  6258. }
  6259.  
  6260. }
  6261.  
  6262. function immediateCheck() {
  6263.  
  6264.  
  6265. if (!scriptEnable) return;
  6266.  
  6267. if(fT(wls.layoutStatus, LAYOUT_TWO_COLUMNS, LAYOUT_TAB_EXPANDED | LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED | LAYOUT_THEATER | LAYOUT_FULLSCREEN | LAYOUT_CHATROOM_EXPANDED)){
  6268. setToActiveTab();
  6269. }
  6270.  
  6271. }
  6272.  
  6273.  
  6274. const mtf_attrFlexy = (mutations, observer) => {
  6275.  
  6276. //attr mutation checker - $$ytdFlexyElm$$ {ytd-watch-flexy} \single
  6277. //::attr
  6278. // ~ 'tyt-chat', 'theater', 'is-two-columns_',
  6279. // ~ 'tyt-tab', 'fullscreen', 'tyt-ep-visible',
  6280. // ~ 'hidden', 'is-extra-wide-video_'
  6281.  
  6282. //console.log(15330, scriptEnable, es.ytdFlexy, mutations)
  6283.  
  6284. if (!scriptEnable) return;
  6285.  
  6286. const cssElm = es.ytdFlexy;
  6287. if (!cssElm) return;
  6288.  
  6289. if (!mutations) return;
  6290.  
  6291. const old_layoutStatus = wls.layoutStatus
  6292. if (old_layoutStatus === 0) return;
  6293. let new_layoutStatus = old_layoutStatus;
  6294.  
  6295. let checkedChat = false;
  6296. let mss = 0;
  6297. let dcall = 0;
  6298.  
  6299. for (const mutation of mutations) {
  6300. new_layoutStatus = flexAttr_toLayoutStatus(new_layoutStatus, mutation.attributeName);
  6301. _console.log(8221, 18, mutation.attributeName)
  6302. if (mutation.attributeName === 'tyt-chat') {
  6303.  
  6304. if (!checkedChat) {
  6305. checkedChat = true; // avoid double call
  6306.  
  6307. if ((cssElm.getAttribute('tyt-chat') || '').indexOf('chat$live') >= 0) {
  6308. // assigned new attribute - "chat$live" => disable comments section
  6309.  
  6310. //console.log(3712,2)
  6311. _disableComments();
  6312. }
  6313.  
  6314. if (!cssElm.hasAttribute('tyt-chat')) {
  6315. // might or might not collapsed before
  6316. dcall |= 1;
  6317. }
  6318. }
  6319.  
  6320. } else if (mutation.attributeName === 'tyt-ep-visible') {
  6321. // assume any other active component such as tab content and chatroom
  6322.  
  6323. if (+(cssElm.getAttribute('tyt-ep-visible') || 0) === 0 && +mutation.oldValue > 0) {
  6324. dcall |= 2;
  6325. }
  6326.  
  6327. if (mss === 0) mss = 1;
  6328. else mss = -1;
  6329.  
  6330. } else if (mutation.attributeName === 'tyt-donation-shelf') {
  6331. // assume any other active component such as tab content and chatroom
  6332.  
  6333. // console.log(4545, cssElm.hasAttribute('tyt-donation-shelf'))
  6334. if (!(cssElm.hasAttribute('tyt-donation-shelf'))) {
  6335. dcall |= 4;
  6336. } else {
  6337. lstTab.lastPanel = '#donation-shelf'
  6338. switchTabActivity(null);
  6339. // console.log(55)
  6340. }
  6341. if (mss === 0) mss = 2;
  6342. else mss = -1;
  6343.  
  6344. } else if (mutation.attributeName === 'is-extra-wide-video_') {
  6345. setTimeout(() => {
  6346. updateFloatingSlider(); //required for hover slider // eg video after ads
  6347. }, 1);
  6348. }
  6349. }
  6350.  
  6351. new_layoutStatus = fixLayoutStatus(new_layoutStatus);
  6352.  
  6353. if (new_layoutStatus !== old_layoutStatus) {
  6354.  
  6355. if (fT(new_layoutStatus, LAYOUT_TWO_COLUMNS, LAYOUT_TAB_EXPANDED | LAYOUT_THEATER | LAYOUT_CHATROOM_EXPANDED)) {
  6356. if (mss === 1) {
  6357. if (fT(new_layoutStatus, LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED, 0)) {
  6358. closeDonationShelf();
  6359. }
  6360. } else if (mss === 2) {
  6361. if (fT(new_layoutStatus, LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED, 0)) {
  6362. ytBtnCloseEngagementPanels();
  6363. }
  6364. }
  6365. }
  6366. wls.layoutStatus = new_layoutStatus
  6367.  
  6368. }
  6369.  
  6370. let timeout240 = new Promise(r => timeline.setTimeout(r, 240));
  6371. timeout240.then(immediateCheck);
  6372.  
  6373. }
  6374.  
  6375.  
  6376. function setupChatFrameDisplayState1(chatBlockR, initialDisplayState) {
  6377.  
  6378.  
  6379. const ytdFlexyElm = es.ytdFlexy;
  6380. if (!scriptEnable || !ytdFlexyElm) return;
  6381.  
  6382. let chatTypeChanged = mtf_chatBlockQ !== chatBlockR;
  6383.  
  6384. let attr_chatblock = chatBlockR === 1 ? 'chat$live' : chatBlockR === 3 ? 'chat$playback' : false;
  6385. let attr_chatcollapsed = false;
  6386.  
  6387.  
  6388. if (attr_chatblock) {
  6389. let chatFrame = document.querySelector('ytd-live-chat-frame#chat')
  6390. if (chatFrame) {
  6391. attr_chatcollapsed = chatFrame.hasAttribute('collapsed');
  6392. if (!attr_chatcollapsed) {
  6393.  
  6394. //nativeFunc(p,'setupPlayerProgressRelay')
  6395. //if(!p.isFrameReady)
  6396. //nativeFunc(p, "urlChanged")
  6397. //console.log(12399,1)
  6398. chatFrame.dispatchEvent(new CustomEvent("tabview-chatroom-newpage")); //possible empty iframe is shown
  6399.  
  6400. }
  6401. } else {
  6402. attr_chatcollapsed = initialDisplayState === 'LIVE_CHAT_DISPLAY_STATE_COLLAPSED' ? true : false;
  6403. }
  6404. }
  6405.  
  6406. if (chatTypeChanged) {
  6407. mtf_chatBlockQ = chatBlockR
  6408.  
  6409. _console.log(932, 2, attr_chatblock, attr_chatcollapsed)
  6410.  
  6411. //LIVE_CHAT_DISPLAY_STATE_COLLAPSED
  6412. //LIVE_CHAT_DISPLAY_STATE_EXPANDED
  6413. let v = attr_chatblock
  6414. if (typeof attr_chatblock == 'string') {
  6415.  
  6416. if (attr_chatcollapsed === true) v = '-' + attr_chatblock
  6417. if (attr_chatcollapsed === false) v = '+' + attr_chatblock;
  6418. }
  6419. wAttr(ytdFlexyElm, 'tyt-chat', v)
  6420.  
  6421. _console.log(932, 3, ytdFlexyElm.hasAttribute('tyt-chat'))
  6422.  
  6423.  
  6424. }
  6425.  
  6426. return { attr_chatblock, attr_chatcollapsed, chatTypeChanged }
  6427. }
  6428.  
  6429. function setupChatFrameDisplayState2() {
  6430.  
  6431. const ytdFlexyElm = es.ytdFlexy;
  6432. if (!scriptEnable || !ytdFlexyElm) return null;
  6433.  
  6434. // this is a backup solution only; should be abandoned
  6435.  
  6436. let attr_chatblock = null
  6437. let attr_chatcollapsed = null;
  6438.  
  6439. const elmChat = document.querySelector('ytd-live-chat-frame#chat')
  6440. let elmCont = null;
  6441. if (elmChat) {
  6442. elmCont = chatFrameElement('yt-live-chat-renderer #continuations')
  6443.  
  6444.  
  6445. let s = 0;
  6446. if (elmCont) {
  6447. //not found if it is collapsed.
  6448. s |= querySelectorFromAnchor.call(elmCont, 'yt-timed-continuation') ? 1 : 0;
  6449. s |= querySelectorFromAnchor.call(elmCont, 'yt-live-chat-replay-continuation, yt-player-seek-continuation') ? 2 : 0;
  6450. //s |= elmCont.querySelector('yt-live-chat-restricted-participation-renderer')?4:0;
  6451. if (s == 1) {
  6452. attr_chatblock = 'chat$live';
  6453. } else if (s == 2) attr_chatblock = 'chat$playback';
  6454.  
  6455. if (s == 1) {
  6456. let cmCountElm = document.querySelector("span#tyt-cm-count")
  6457. if (cmCountElm) cmCountElm.textContent = '';
  6458. }
  6459.  
  6460. } else if (!ytdFlexyElm.hasAttribute('tyt-chat')) {
  6461. // live chat frame but type not known
  6462.  
  6463. attr_chatblock = '';
  6464.  
  6465. }
  6466. //keep unknown as original
  6467.  
  6468.  
  6469. let isCollapsed = !!elmChat.hasAttribute('collapsed');
  6470. attr_chatcollapsed = isCollapsed;
  6471.  
  6472. } else {
  6473. attr_chatblock = false;
  6474. attr_chatcollapsed = false;
  6475.  
  6476. }
  6477.  
  6478. return { attr_chatblock, attr_chatcollapsed }
  6479.  
  6480. }
  6481.  
  6482.  
  6483. const mtf_checkFlexy = () => {
  6484. // once per $$native-ytd-watch-flexy$$ {ytd-watch-flexy} detection
  6485.  
  6486. const ytdFlexyElm = es.ytdFlexy;
  6487. if (!scriptEnable || !ytdFlexyElm) return true;
  6488.  
  6489.  
  6490. wls.layoutStatus = 0;
  6491.  
  6492. let isFlexyHidden = (ytdFlexyElm.hasAttribute('hidden'));
  6493.  
  6494. if (!isFlexyHidden) {
  6495. let rChatExist = setupChatFrameDisplayState2();
  6496. if (rChatExist) {
  6497. let { attr_chatblock, attr_chatcollapsed } = rChatExist;
  6498. if (attr_chatblock === null) {
  6499. //remove attribute if it is unknown
  6500. attr_chatblock = false;
  6501. attr_chatcollapsed = false;
  6502. }
  6503. let v = attr_chatblock;
  6504. if (typeof v === 'string') {
  6505. if (attr_chatcollapsed === true) v = '-' + v;
  6506. if (attr_chatcollapsed === false) v = '+' + v;
  6507. }
  6508. wAttr(ytdFlexyElm, 'tyt-chat', v)
  6509.  
  6510. }
  6511. }
  6512.  
  6513. let rTabSelection = [...querySelectorAllFromAnchor.call(ytdFlexyElm, '.tab-btn[tyt-tab-content]')]
  6514. .map(elm => ({ elm, hidden: elm.classList.contains('tab-btn-hidden') }));
  6515.  
  6516. if (rTabSelection.length === 0) {
  6517. wAttr(ytdFlexyElm, 'tyt-tab', false);
  6518. } else {
  6519. rTabSelection = rTabSelection.filter(entry => entry.hidden !== true); // all available tabs
  6520. if (rTabSelection.length === 0) wAttr(ytdFlexyElm, 'tyt-tab', '');
  6521. }
  6522. rTabSelection = null;
  6523.  
  6524. let rEP = engagement_panels_();
  6525. if (rEP && rEP.list.length > 0) {
  6526. wAttr(ytdFlexyElm, 'tyt-ep-visible', `${rEP.value}`);
  6527. } else {
  6528. wAttr(ytdFlexyElm, 'tyt-ep-visible', false);
  6529. }
  6530.  
  6531. let ls = LAYOUT_VAILD;
  6532. ls = flexAttr_toLayoutStatus(ls, 'theater')
  6533. ls = flexAttr_toLayoutStatus(ls, 'tyt-chat')
  6534. ls = flexAttr_toLayoutStatus(ls, 'is-two-columns_')
  6535. ls = flexAttr_toLayoutStatus(ls, 'tyt-tab')
  6536. ls = flexAttr_toLayoutStatus(ls, 'fullscreen')
  6537. ls = flexAttr_toLayoutStatus(ls, 'tyt-ep-visible')
  6538. ls = flexAttr_toLayoutStatus(ls, 'tyt-donation-shelf')
  6539.  
  6540. fixLayoutStatus(ls)
  6541.  
  6542. wls.layoutStatus = ls
  6543.  
  6544. mtoFlexyAttr.bindElement(ytdFlexyElm, {
  6545. attributes: true,
  6546. attributeFilter: ['tyt-chat', 'theater', 'is-two-columns_', 'tyt-tab', 'fullscreen', 'tyt-ep-visible', 'tyt-donation-shelf', 'hidden', 'is-extra-wide-video_'],
  6547. attributeOldValue: true
  6548. })
  6549.  
  6550. let columns = document.querySelector('ytd-page-manager#page-manager #columns.ytd-watch-flexy')
  6551. if (columns) {
  6552. wAttr(columns, 'userscript-scrollbar-render', true);
  6553. }
  6554.  
  6555. immediateCheck()
  6556.  
  6557. return false;
  6558. }
  6559.  
  6560. document.addEventListener('tabview-fix-layout',()=>{
  6561. immediateCheck()
  6562.  
  6563. },false)
  6564.  
  6565.  
  6566. function switchTabActivity(activeLink) {
  6567.  
  6568. //console.log(4545, activeLink)
  6569. if (!scriptEnable) return;
  6570.  
  6571. const ytdFlexyElm = es.ytdFlexy;
  6572.  
  6573. if (!ytdFlexyElm) return;
  6574.  
  6575. if (activeLink && activeLink.classList.contains('tab-btn-hidden')) return; // not allow to switch to hide tab
  6576.  
  6577. //if (isTheater() && isWideScreenWithTwoColumns()) activeLink = null;
  6578.  
  6579.  
  6580. function runAtEnd() {
  6581.  
  6582. if (activeLink) {
  6583. lstTab.lastTab = activeLink.getAttribute('tyt-tab-content')
  6584. lstTab.lastPanel = null;
  6585.  
  6586. if (!document.querySelector(`${lstTab.lastTab}.tab-content-cld tabview-view-tab-expander`)) {
  6587.  
  6588. let secondary = document.querySelector('#secondary.ytd-watch-flexy');
  6589. if (secondary) {
  6590. secondary.dispatchEvent(new CustomEvent('tabview-hover-slider-restore'))
  6591. //console.log(1995)
  6592. }
  6593.  
  6594.  
  6595. }
  6596. }
  6597.  
  6598. ytdFlexyElm.setAttribute('tyt-tab', activeLink ? lstTab.lastTab : '')
  6599.  
  6600. }
  6601.  
  6602. const links = document.querySelectorAll('#material-tabs a[tyt-tab-content]');
  6603.  
  6604. //console.log(701, activeLink)
  6605.  
  6606. for (const link of links) {
  6607. let content = document.querySelector(link.getAttribute('tyt-tab-content'));
  6608. if (link && content) {
  6609. if (link !== activeLink) {
  6610. link.classList.remove("active");
  6611. content.classList.add("tab-content-hidden");
  6612. if (!content.hasAttribute("tyt-hidden")) {
  6613. content.setAttribute("tyt-hidden", ""); // for https://greasyfork.org/en/scripts/456108
  6614. }
  6615. } else {
  6616. link.classList.add("active");
  6617. if (content.hasAttribute("tyt-hidden")) {
  6618. content.removeAttribute("tyt-hidden"); // for https://greasyfork.org/en/scripts/456108
  6619. }
  6620. content.classList.remove("tab-content-hidden");
  6621. }
  6622. }
  6623. }
  6624.  
  6625. runAtEnd();
  6626.  
  6627.  
  6628. }
  6629.  
  6630.  
  6631. function getStore() {
  6632. let s = localStorage[STORE_key];
  6633. function resetStore() {
  6634. let ret = {
  6635. version: 1,
  6636. };
  6637. localStorage[STORE_key] = JSON.stringify(ret);
  6638. return ret;
  6639. }
  6640. if (!s) return resetStore();
  6641. let obj = null;
  6642. try {
  6643. obj = JSON.parse(s);
  6644. } catch (e) { }
  6645. return obj && obj.version === STORE_VERSION ? obj : resetStore();
  6646. }
  6647.  
  6648. function setStore(obj) {
  6649. if (!obj || typeof obj !== 'object') return false;
  6650. if (obj.version !== STORE_VERSION) return false;
  6651. localStorage[STORE_key] = JSON.stringify(obj);
  6652. return true;
  6653. }
  6654.  
  6655.  
  6656.  
  6657. async function handlerMaterialTabClickInner(tabBtn) {
  6658.  
  6659. await Promise.resolve(0);
  6660.  
  6661. const layoutStatusMutexUnlock = await new Promise(resolve => {
  6662. layoutStatusMutex.lockWith(unlock => {
  6663. resolve(unlock)
  6664. })
  6665. });
  6666.  
  6667. // locked
  6668. let unlock = layoutStatusMutexUnlock; // function of unlock inside layoutStatusMutex
  6669.  
  6670. //console.log(8515)
  6671. switchTabActivity_lastTab = tabBtn.getAttribute('tyt-tab-content');
  6672.  
  6673. let isActiveAndVisible = tabBtn.classList.contains('tab-btn') && tabBtn.classList.contains('active') && !tabBtn.classList.contains('tab-btn-hidden')
  6674.  
  6675. _console.log(8221, 15, isActiveAndVisible)
  6676.  
  6677. if (isFullScreen()) {
  6678.  
  6679.  
  6680. const fullScreenTabScrollIntoView = () => {
  6681. let scrollElement = document.querySelector('ytd-app[scrolling]')
  6682. if (!scrollElement) return;
  6683. // single column view; click button; scroll to tab content area 100%
  6684. let rightTabs = document.querySelector('#right-tabs');
  6685. let pTop = rightTabs.getBoundingClientRect().top - scrollElement.getBoundingClientRect().top
  6686. if (rightTabs && pTop > 0 && tabBtn.classList.contains('active')) {
  6687. rightTabs.scrollIntoView(false);
  6688. }
  6689. }
  6690.  
  6691. _console.log(8221, 16, 1)
  6692.  
  6693. if (isActiveAndVisible) {
  6694. timeline.setTimeout(unlock, 80);
  6695. switchTabActivity(null);
  6696. } else {
  6697.  
  6698. if (isChatExpand() && isWideScreenWithTwoColumns()) {
  6699. ytBtnCollapseChat();
  6700. } else if (isEngagementPanelExpanded() && isWideScreenWithTwoColumns()) {
  6701. ytBtnCloseEngagementPanels();
  6702. } else if (isDonationShelfExpanded() && isWideScreenWithTwoColumns()) {
  6703. closeDonationShelf();
  6704. }
  6705.  
  6706.  
  6707. timeline.setTimeout(fullScreenTabScrollIntoView, 60)
  6708.  
  6709. timeline.setTimeout(unlock, 80);
  6710. switchTabActivity(tabBtn)
  6711. }
  6712.  
  6713. } else if (isWideScreenWithTwoColumns() && !isTheater() && isActiveAndVisible) {
  6714.  
  6715. _console.log(8221, 16, 2)
  6716. //optional
  6717. timeline.setTimeout(unlock, 80);
  6718. switchTabActivity(null);
  6719. ytBtnSetTheater();
  6720. } else if (isActiveAndVisible) {
  6721.  
  6722. _console.log(8221, 16, 3)
  6723. timeline.setTimeout(unlock, 80);
  6724. switchTabActivity(null);
  6725. } else {
  6726.  
  6727. _console.log(8221, 16, 4)
  6728.  
  6729. if (isChatExpand() && isWideScreenWithTwoColumns()) {
  6730. ytBtnCollapseChat();
  6731. } else if (isEngagementPanelExpanded() && isWideScreenWithTwoColumns()) {
  6732. ytBtnCloseEngagementPanels();
  6733. } else if (isDonationShelfExpanded() && isWideScreenWithTwoColumns()) {
  6734. closeDonationShelf();
  6735. } else if (isWideScreenWithTwoColumns() && isTheater() && !isFullScreen()) {
  6736. ytBtnCancelTheater(); //ytd-watch-flexy attr [theater]
  6737. }
  6738.  
  6739. timeline.setTimeout(() => {
  6740. // single column view; click button; scroll to tab content area 100%
  6741. let rightTabs = document.querySelector('#right-tabs');
  6742. if (!isWideScreenWithTwoColumns() && rightTabs && rightTabs.offsetTop > 0 && tabBtn.classList.contains('active')) {
  6743. let tabButtonBar = document.querySelector('#material-tabs');
  6744. let tabButtonBarHeight = tabButtonBar ? tabButtonBar.offsetHeight : 0;
  6745. window.scrollTo(0, rightTabs.offsetTop - tabButtonBarHeight);
  6746. }
  6747. }, 60)
  6748. // _console.log(8519)
  6749.  
  6750. timeline.setTimeout(unlock, 80)
  6751. switchTabActivity(tabBtn)
  6752.  
  6753. }
  6754.  
  6755.  
  6756. }
  6757.  
  6758. function handlerMaterialTabClick(/** @type {MouseEvent} */ evt) {
  6759.  
  6760. //console.log(8510)
  6761. const ytdFlexyElm = es.ytdFlexy;
  6762. if (!scriptEnable || !ytdFlexyElm) return null;
  6763.  
  6764. let tabBtn = this;
  6765.  
  6766. if (!tabBtn.hasAttribute('tyt-tab-content')) return;
  6767.  
  6768. /** @type {HTMLElement | null} */
  6769. let dom = evt.target;
  6770. if (!dom) return;
  6771.  
  6772. if (dom.classList.contains('font-size-btn')) return;
  6773.  
  6774.  
  6775. evt.preventDefault();
  6776.  
  6777. handlerMaterialTabClickInner(tabBtn);
  6778.  
  6779.  
  6780. }
  6781.  
  6782. function onVideoLeavePictureInPicuture() {
  6783. isMiniviewForStickyHeadEnabled = false;
  6784. }
  6785.  
  6786.  
  6787. let videoPlayerInsectObserver = null;
  6788. let videoInsected = false;
  6789.  
  6790. async function enablePIPforStickyHead() {
  6791. // use async & await to avoid handler took 60ms
  6792. if (!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && userActivation && typeof IntersectionObserver == 'function') {
  6793. let video = document.querySelector('#player video');
  6794. if (!video) return;
  6795.  
  6796. await Promise.resolve(0)
  6797. const pageClientWidth = document.documentElement.clientWidth;
  6798. if (pageClientWidth + 320 < screen.width && pageClientWidth > 320 && !document.querySelector('#rCbM3')) {
  6799.  
  6800. await Promise.resolve(0)
  6801. // desktop or notebook can use this feature
  6802.  
  6803. // --------------------------------------------------------
  6804. // ignore user activation error
  6805. enterPIP(video, null).then(r => {
  6806. if (r === true) {
  6807. userActivation = false;
  6808. isMiniviewForStickyHeadEnabled = true;
  6809. }
  6810. });
  6811. // --------------------------------------------------------
  6812. video.removeEventListener('leavepictureinpicture', onVideoLeavePictureInPicuture, false);
  6813. video.addEventListener('leavepictureinpicture', onVideoLeavePictureInPicuture, false);
  6814.  
  6815. if(!video.hasAttribute('NOL4j')){
  6816. video.setAttribute('NOL4j',"");
  6817.  
  6818. await Promise.resolve(0)
  6819.  
  6820. let callback = (entries)=>{
  6821.  
  6822.  
  6823. let lastEntry = entries[entries.length-1];
  6824. if(lastEntry && lastEntry.isIntersecting === true){
  6825.  
  6826. videoInsected = true;
  6827. if(isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation && videoInsected){
  6828. restorePIPforStickyHead();
  6829. }
  6830.  
  6831. }else {
  6832. videoInsected =false;
  6833. }
  6834. };
  6835.  
  6836. if(!videoPlayerInsectObserver){
  6837. videoPlayerInsectObserver = new IntersectionObserver(callback, {
  6838. root: null,
  6839. rootMargin: "0px",
  6840. threshold: 0.25
  6841. });
  6842. }
  6843.  
  6844. videoPlayerInsectObserver.takeRecords();
  6845. videoPlayerInsectObserver.disconnect();
  6846.  
  6847. videoPlayerInsectObserver.observe(video);
  6848.  
  6849. }
  6850.  
  6851. }
  6852. }
  6853. }
  6854.  
  6855. function setStickyHeader(targetElm, bool, getWidthHeight, getLeftRight) {
  6856.  
  6857. //if(isStickyHeaderEnabled===bool) return; // no update
  6858.  
  6859. if (bool === true) {
  6860. const { width, height } = getWidthHeight();
  6861. targetElm.style.setProperty("--tyt-stickybar-w", width + 'px')
  6862. targetElm.style.setProperty("--tyt-stickybar-h", height + 'px')
  6863. const res = getLeftRight();
  6864. if (res) {
  6865.  
  6866. targetElm.style.setProperty("--tyt-stickybar-l", (res.left) + 'px')
  6867. targetElm.style.setProperty("--tyt-stickybar-r", (res.right) + 'px')
  6868.  
  6869. }
  6870. wAttr(targetElm, 'tyt-stickybar', true);
  6871. isStickyHeaderEnabled = true;
  6872.  
  6873. if (!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && userActivation && typeof IntersectionObserver == 'function') {
  6874. setTimeout(enablePIPforStickyHead, 0);
  6875. }
  6876.  
  6877. } else if (bool === false) {
  6878.  
  6879. wAttr(targetElm, 'tyt-stickybar', false);
  6880. isStickyHeaderEnabled = false;
  6881.  
  6882.  
  6883. }
  6884.  
  6885.  
  6886. }
  6887.  
  6888. const singleColumnScrolling = async function () {
  6889. //makeHeaderFloat
  6890. // required for 1) init 2) layout change 3) resizing
  6891.  
  6892. if (!scriptEnable || pageType !== 'watch') return;
  6893.  
  6894.  
  6895. let isTwoCol = (wls.layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS;
  6896. if (isTwoCol) {
  6897.  
  6898. if (isStickyHeaderEnabled) {
  6899.  
  6900. let targetElm = document.querySelector("#right-tabs");
  6901. setStickyHeader(targetElm, false, null, null);
  6902. }
  6903. return;
  6904. }
  6905.  
  6906. let pageY = scrollY;
  6907.  
  6908.  
  6909. let tdt = Date.now();
  6910. singleColumnScrolling_dt = tdt;
  6911.  
  6912.  
  6913. _console.log(7891, 'scrolling')
  6914.  
  6915. function getXYStatus(res) {
  6916.  
  6917. const [navHeight, elmY] = res;
  6918.  
  6919. let xyz = [elmY + navHeight, pageY, elmY - navHeight]
  6920.  
  6921. let xyStatus = 0
  6922. if (xyz[1] < xyz[2] && xyz[2] < xyz[0]) {
  6923. // 1
  6924. xyStatus = 1
  6925. }
  6926.  
  6927. if (xyz[0] > xyz[1] && xyz[1] > xyz[2]) {
  6928.  
  6929. //2
  6930. xyStatus = 2
  6931.  
  6932. }
  6933.  
  6934. if (xyz[2] < xyz[0] && xyz[0] < xyz[1]) {
  6935. // 3
  6936.  
  6937. xyStatus = 3
  6938.  
  6939.  
  6940. }
  6941.  
  6942. return xyStatus;
  6943. }
  6944.  
  6945. let [targetElm, header, navElm] = await Promise.all([
  6946. new Promise(f => f(document.querySelector("#right-tabs"))),
  6947.  
  6948. new Promise(f => f(document.querySelector("#right-tabs header"))),
  6949.  
  6950. new Promise(f => f(document.querySelector('#masthead-container, #masthead'))),
  6951.  
  6952. ]);
  6953.  
  6954. function emptyForGC() {
  6955. targetElm = null;
  6956. header = null;
  6957. navElm = null;
  6958. }
  6959.  
  6960. if (!targetElm || !header) {
  6961. return emptyForGC();
  6962. }
  6963. if (singleColumnScrolling_dt !== tdt) return emptyForGC();
  6964.  
  6965. let res2 = await Promise.all([
  6966. new Promise(f => f(navElm ? navElm.offsetHeight : 0)),
  6967. new Promise(f => f(targetElm.offsetTop))
  6968. ])
  6969.  
  6970. if (res2 === null) return emptyForGC();
  6971.  
  6972. if (singleColumnScrolling_dt !== tdt) return emptyForGC();
  6973.  
  6974.  
  6975. const xyStatus = getXYStatus(res2);
  6976.  
  6977.  
  6978. function getLeftRight() {
  6979.  
  6980. let thp = document.querySelector('tabview-view-pos-thead');
  6981. if (thp) {
  6982.  
  6983. let rect = thp.getBoundingClientRect()
  6984. if (rect) {
  6985. return {
  6986. left: rect.left,
  6987. right: document.documentElement.clientWidth - rect.right
  6988. };
  6989. }
  6990. }
  6991. return null;
  6992. }
  6993.  
  6994. let bool = (xyStatus == 2 || xyStatus == 3) ? true : ((xyStatus == 1) ? false : null);
  6995.  
  6996. function getWidthHeight() {
  6997. return { width: targetElm.offsetWidth, height: header.offsetHeight };
  6998. }
  6999.  
  7000. setStickyHeader(targetElm, bool, getWidthHeight, getLeftRight);
  7001.  
  7002.  
  7003. emptyForGC();
  7004.  
  7005. };
  7006.  
  7007.  
  7008. const singleColumnScrolling2 = async function (xyStatus, width, xRect) {
  7009. //makeHeaderFloat
  7010.  
  7011. if (!scriptEnable || pageType !== 'watch') return;
  7012.  
  7013.  
  7014. if ((wls.layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) {
  7015. return;
  7016. }
  7017.  
  7018. let [targetElm, header] = await Promise.all([
  7019. new Promise(f => f(document.querySelector("#right-tabs"))),
  7020. new Promise(f => f(document.querySelector("#right-tabs header")))
  7021. ]);
  7022.  
  7023. function emptyForGC() {
  7024. targetElm = null;
  7025. header = null;
  7026. }
  7027.  
  7028.  
  7029. if (!targetElm || !header) {
  7030. return emptyForGC();
  7031. }
  7032.  
  7033. function getLeftRight() {
  7034. return xRect;
  7035. }
  7036.  
  7037. let bool = (xyStatus == 2 || xyStatus == 3) ? true : ((xyStatus == 1) ? false : null);
  7038.  
  7039. function getWidthHeight() {
  7040. return { width: (width || targetElm.offsetWidth), height: header.offsetHeight };
  7041. }
  7042.  
  7043. setStickyHeader(targetElm, bool, getWidthHeight, getLeftRight);
  7044.  
  7045. emptyForGC();
  7046.  
  7047. };
  7048.  
  7049.  
  7050. function resetBuggyLayoutForNewVideoPage() {
  7051.  
  7052. const ytdFlexyElm = es.ytdFlexy;
  7053. if (!ytdFlexyElm) return;
  7054.  
  7055. //(flexy is visible and watch video page)
  7056.  
  7057. scriptEnable = true;
  7058.  
  7059. _console.log(27056)
  7060.  
  7061. let new_layoutStatus = wls.layoutStatus
  7062.  
  7063. new_layoutStatus & (LAYOUT_CHATROOM_COLLAPSED | LAYOUT_CHATROOM)
  7064.  
  7065. const new_isExpandedChat = !(new_layoutStatus & LAYOUT_CHATROOM_COLLAPSED) && !!(new_layoutStatus & LAYOUT_CHATROOM)
  7066. const new_isCollapsedChat = !!(new_layoutStatus & LAYOUT_CHATROOM_COLLAPSED) && !!(new_layoutStatus & LAYOUT_CHATROOM)
  7067.  
  7068. const new_isTwoColumns = new_layoutStatus & LAYOUT_TWO_COLUMNS;
  7069. const new_isTheater = new_layoutStatus & LAYOUT_THEATER;
  7070. const new_isTabExpanded = new_layoutStatus & LAYOUT_TAB_EXPANDED;
  7071. const new_isFullScreen = new_layoutStatus & LAYOUT_FULLSCREEN;
  7072. const new_isExpandedEPanel = new_layoutStatus & LAYOUT_ENGAGEMENT_PANEL_EXPANDED;
  7073. const new_isExpandedDonationShelf = new_layoutStatus & LAYOUT_DONATION_SHELF_EXPANDED;
  7074. const nothingShown = !new_isTabExpanded && !new_isExpandedChat && !new_isExpandedEPanel && !new_isExpandedDonationShelf
  7075.  
  7076. if (ytdFlexyElm.getAttribute('tyt-tab') === '' && new_isTwoColumns && !new_isTheater && nothingShown && !new_isFullScreen) {
  7077. // e.g. engage panel removed after miniview and change video
  7078. setToActiveTab();
  7079. } else if (new_isExpandedEPanel && querySelectorAllFromAnchor.call(ytdFlexyElm, 'ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"]:not([hidden])').length === 0) {
  7080. wls.layoutStatus = new_layoutStatus & (~LAYOUT_ENGAGEMENT_PANEL_EXPANDED)
  7081. } else if (new_isExpandedDonationShelf && querySelectorAllFromAnchor.call(ytdFlexyElm, 'ytd-donation-shelf-renderer.ytd-watch-flexy:not([hidden])').length === 0) {
  7082. wls.layoutStatus = new_layoutStatus & (~LAYOUT_DONATION_SHELF_EXPANDED)
  7083. }
  7084.  
  7085. }
  7086.  
  7087.  
  7088. function extractInfoFromLiveChatRenderer(liveChatRenderer) {
  7089.  
  7090. let lcr = liveChatRenderer
  7091.  
  7092. let data_shb = ((lcr || 0).showHideButton || 0).toggleButtonRenderer
  7093.  
  7094. let default_display_state = null, txt_collapse = null, txt_expand = null;
  7095.  
  7096.  
  7097. if (data_shb && data_shb.defaultText && data_shb.toggledText && data_shb.defaultText.runs && data_shb.toggledText.runs) {
  7098.  
  7099. if (data_shb.defaultText.runs.length === 1 && data_shb.toggledText.runs.length === 1) {
  7100.  
  7101. if (lcr.initialDisplayState == "LIVE_CHAT_DISPLAY_STATE_EXPANDED") {
  7102.  
  7103. default_display_state = lcr.initialDisplayState
  7104.  
  7105. txt_collapse = (data_shb.defaultText.runs[0] || 0).text // COLLAPSE the area
  7106.  
  7107. txt_expand = (data_shb.toggledText.runs[0] || 0).text // expand the area
  7108.  
  7109. } else if (lcr.initialDisplayState == "LIVE_CHAT_DISPLAY_STATE_COLLAPSED") {
  7110. default_display_state = lcr.initialDisplayState
  7111.  
  7112. txt_expand = (data_shb.defaultText.runs[0] || 0).text // expand the area
  7113.  
  7114. txt_collapse = (data_shb.toggledText.runs[0] || 0).text // COLLAPSE the area
  7115. }
  7116.  
  7117.  
  7118. if (typeof txt_expand == 'string' && typeof txt_collapse == 'string' && txt_expand.length > 0 && txt_collapse.length > 0) {
  7119.  
  7120. } else {
  7121. txt_expand = null;
  7122. txt_collapse = null;
  7123. }
  7124. }
  7125.  
  7126. }
  7127.  
  7128. return { default_display_state, txt_collapse, txt_expand }
  7129.  
  7130. }
  7131.  
  7132.  
  7133. function newVideoPage(evt_detail) {
  7134.  
  7135. //toggleBtnDC = 1;
  7136.  
  7137. console.debug('[tyt] newVideoPage')
  7138.  
  7139. const ytdFlexyElm = es.ytdFlexy;
  7140. if (!ytdFlexyElm) return;
  7141.  
  7142. timeline.reset();
  7143. layoutStatusMutex = new Mutex();
  7144.  
  7145. let liveChatRenderer = null;
  7146. let isReplay = null;
  7147.  
  7148. if (pageType !== 'watch') return; // scriptEnable -> pageType shall be always 'watch'
  7149. resetBuggyLayoutForNewVideoPage();
  7150.  
  7151. try {
  7152. liveChatRenderer = evt_detail.pageData.response.contents.twoColumnWatchNextResults.conversationBar.liveChatRenderer
  7153. } catch (e) { }
  7154. if (liveChatRenderer) {
  7155. if (liveChatRenderer.isReplay === true) isReplay = true;
  7156. }
  7157.  
  7158. pageFetchedDataVideoId = ((((evt_detail || 0).pageData || 0).playerResponse || 0).videoDetails || 0).videoId || 0;
  7159.  
  7160.  
  7161. const chatBlockR = liveChatRenderer ? (isReplay ? 3 : 1) : 0
  7162. const initialDisplayState = liveChatRenderer ? liveChatRenderer.initialDisplayState : null;
  7163.  
  7164.  
  7165. liveChatRenderer = null; // release memory for GC, just in case
  7166.  
  7167. let f = () => {
  7168.  
  7169. _console.log(932, 1, 1)
  7170. const ytdFlexyElm = es.ytdFlexy;
  7171. if (!scriptEnable || !ytdFlexyElm) return;
  7172.  
  7173. _console.log(932, 1, 2)
  7174. if (pageType !== 'watch') return;
  7175.  
  7176. _console.log(932, 1, 3)
  7177.  
  7178.  
  7179. let displayState = setupChatFrameDisplayState1(chatBlockR, initialDisplayState);
  7180.  
  7181. let { attr_chatblock, attr_chatcollapsed, chatTypeChanged } = displayState;
  7182.  
  7183.  
  7184. if (pageType === 'watch') { // reset info when hidden
  7185.  
  7186. let elm_storeLastPanel = es.storeLastPanel;
  7187.  
  7188. if (!elm_storeLastPanel) storeLastPanel = null;
  7189. else if (!isDOMVisible(elm_storeLastPanel)) {
  7190. storeLastPanel = null;
  7191. ytBtnCloseEngagementPanels();
  7192. }
  7193.  
  7194. }
  7195.  
  7196. if (chatTypeChanged) {
  7197.  
  7198. if (attr_chatblock == 'chat$live') {
  7199.  
  7200. _console.log(932, 4)
  7201.  
  7202. mtf_forceCheckLiveVideo_disable = 2;
  7203.  
  7204. //console.log(3712,1)
  7205.  
  7206. _disableComments();
  7207.  
  7208.  
  7209. } else {
  7210.  
  7211. const tabBtn = document.querySelector('[tyt-tab-content="#tab-comments"].tab-btn-hidden')
  7212. if (tabBtn) {
  7213. emptyCommentSection();
  7214. _console.log(9360, 74);
  7215. tabBtn.classList.remove("tab-btn-hidden")
  7216. } else {
  7217. setCommentSection(0);
  7218. }
  7219.  
  7220. mtf_forceCheckLiveVideo_disable = 0;
  7221.  
  7222. _console.log(7234, 'comments_section_loaded = 0')
  7223. restoreFetching();
  7224.  
  7225.  
  7226. }
  7227.  
  7228.  
  7229. } else {
  7230.  
  7231. // restore Fetching only
  7232.  
  7233. if (mtf_forceCheckLiveVideo_disable !== 2 && (attr_chatblock === false || attr_chatblock === 'chat$playback')) {
  7234.  
  7235. emptyCommentSection();
  7236. _console.log(9360, 77);
  7237. mtf_forceCheckLiveVideo_disable = 0;
  7238. _console.log(7235, 'comments_section_loaded = 0')
  7239. restoreFetching();
  7240.  
  7241. }
  7242.  
  7243. }
  7244.  
  7245.  
  7246. checkAndMakeNewCommentFetch();
  7247.  
  7248. }
  7249.  
  7250. f();
  7251.  
  7252. }
  7253.  
  7254. function setVideosTwoColumns(/** @type {number} */ flag, /** @type {boolean} */ bool) {
  7255.  
  7256. //two columns to one column
  7257.  
  7258. /*
  7259. [placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy
  7260.  
  7261. is-two-columns ="" => no is-two-columns
  7262. [placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer
  7263. no hidden => hidden =""
  7264. [placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer
  7265. hidden ="" => no hidden
  7266.  
  7267. */
  7268.  
  7269. let cssSelector1 = '[placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy'
  7270.  
  7271. let cssSelector2 = '[placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer'
  7272.  
  7273. let cssSelector3 = '[placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer'
  7274.  
  7275. let res = {}
  7276. if (flag & 1) {
  7277. res.m1 = document.querySelector(cssSelector1)
  7278. if (res.m1) wAttr(res.m1, 'is-two-columns', bool ? '' : false);
  7279. }
  7280.  
  7281. if (flag & 2) {
  7282. res.m2 = document.querySelector(cssSelector2)
  7283. if (res.m2) wAttr(res.m2, 'hidden', bool ? false : '');
  7284. }
  7285.  
  7286. if (flag & 4) {
  7287. res.m3 = document.querySelector(cssSelector3)
  7288. if (res.m3) wAttr(res.m3, 'hidden', bool ? '' : false);
  7289. }
  7290.  
  7291. return res
  7292.  
  7293.  
  7294. }
  7295.  
  7296. // ---------------------------------------------------------------------------------------------
  7297.  
  7298. // ---- EVENTS ----
  7299.  
  7300. let ytEventSequence = 0
  7301. let formatDates = null
  7302.  
  7303. function pageBeingFetched(evt, isPageFirstLoaded) {
  7304.  
  7305. let nodeName = (((evt||0).target||0).nodeName||'').toUpperCase()
  7306. if (nodeName !== 'YTD-APP') return;
  7307.  
  7308. let pageFetchedDataLocal = evt.detail;
  7309.  
  7310. let d_page = ((pageFetchedDataLocal||0).pageData||0).page;
  7311. if (!d_page) return;
  7312.  
  7313. pageType = d_page;
  7314.  
  7315. if (pageType !== 'watch') return
  7316.  
  7317. let promiseChatDetails = null
  7318.  
  7319. let isFirstLoad = firstLoadStatus & 8;
  7320.  
  7321. if (isFirstLoad) {
  7322. firstLoadStatus -= 8;
  7323. document.addEventListener('load', iframeLoadHookA, capturePassive)
  7324. ytMicroEventsInit();
  7325. }
  7326. // ytMicroEventsInit set
  7327. variableResets();
  7328.  
  7329. if (isFirstLoad) {
  7330.  
  7331. if (ytEventSequence >= 2) {
  7332. let docElement = document.documentElement
  7333. if (docElement.hasAttribute('tabview-loaded')) {
  7334. throw 'Tabview Youtube Duplicated';
  7335. }
  7336. docElement.setAttribute('tabview-loaded', '')
  7337.  
  7338. Promise.resolve(docElement).then(docElement => {
  7339. if (ytEventSequence >= 2) {
  7340. docElement.dispatchEvent(new CustomEvent('tabview-ce-hack'))
  7341. docElement = null
  7342. }
  7343. })
  7344.  
  7345. }
  7346. }
  7347. // tabview-loaded delay set
  7348.  
  7349. formatDates={}
  7350. try{
  7351. formatDates.publishDate = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.publishDate
  7352. }catch(e){}
  7353. // 2022-12-30
  7354.  
  7355. try{
  7356. formatDates.uploadDate = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.uploadDate
  7357. }catch(e){}
  7358. // 2022-12-30
  7359.  
  7360. try{
  7361. formatDates.publishDate2 = pageFetchedDataLocal.pageData.response.contents.twoColumnWatchNextResults.results.results.contents[0].videoPrimaryInfoRenderer.dateText.simpleText
  7362. }catch(e){}
  7363. // 2022/12/31
  7364.  
  7365. if(typeof formatDates.publishDate2==='string' && formatDates.publishDate2 !== formatDates.publishDate){
  7366. formatDates.publishDate = formatDates.publishDate2
  7367. formatDates.uploadDate = null
  7368. }
  7369.  
  7370. try{
  7371. formatDates.broadcastBeginAt = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.liveBroadcastDetails.startTimestamp
  7372. }catch(e){}
  7373. try{
  7374. formatDates.broadcastEndAt = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.liveBroadcastDetails.endTimestamp
  7375. }catch(e){}
  7376. try{
  7377. formatDates.isLiveNow = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.liveBroadcastDetails.isLiveNow
  7378. }catch(e){}
  7379.  
  7380. promiseChatDetails = new Promise(resolve => {
  7381. if (ytEventSequence >= 2) {
  7382. let liveChatRenderer = null;
  7383. try {
  7384. liveChatRenderer = pageFetchedDataLocal.pageData.response.contents.twoColumnWatchNextResults.conversationBar.liveChatRenderer
  7385. } catch (e) { }
  7386. chatroomDetails = liveChatRenderer ? extractInfoFromLiveChatRenderer(liveChatRenderer) : null;
  7387. liveChatRenderer = null; // release memory for GC, just in case
  7388. }
  7389. resolve(0)
  7390. })
  7391.  
  7392. let ytdFlexyElm = document.querySelector('ytd-watch-flexy')
  7393.  
  7394. if (!ytdFlexyElm) return;
  7395.  
  7396.  
  7397. ytdFlexy = mWeakRef(ytdFlexyElm);
  7398.  
  7399. ytdFlexyElm = null;
  7400.  
  7401. Promise.resolve(0).then(() => {
  7402.  
  7403. if (ytEventSequence >= 2 && pageRendered === 0) {
  7404.  
  7405. const ytdFlexyElm = es.ytdFlexy; // shall be always non-null
  7406. if (ytdFlexyElm) {
  7407.  
  7408. let elmPL = document.createElement('tabview-view-ploader');
  7409. pageRendered = 1;
  7410. // ytdFlexyElm.appendChild(elmPL);
  7411. elementAppend.call(ytdFlexyElm, elmPL);
  7412. // pageRendered keeps at 1 if the video is continuously playing at the background
  7413. // pageRendered would not be resolve but will reset for each change of video
  7414.  
  7415. }
  7416.  
  7417. }
  7418.  
  7419. })
  7420.  
  7421. let renderId = renderIdentifier
  7422. renderDeferred.debounce(() => {
  7423. if (renderId !== renderIdentifier) return
  7424. if (ytEventSequence >= 2) {
  7425. advanceFetch(); // at least one triggering at yt-page-data-fetched
  7426. }
  7427. });
  7428.  
  7429. Promise.race([promiseChatDetails]).then(() => {
  7430.  
  7431. const ytdFlexyElm = es.ytdFlexy;
  7432. if (ytEventSequence >= 2 && ytdFlexyElm) {
  7433. ytdFlexyElm.classList.toggle('tyt-chat-toggleable', !!chatroomDetails);
  7434. }
  7435.  
  7436. }).then(() => {
  7437.  
  7438. if (ytEventSequence >= 2) {
  7439.  
  7440. let tabsDeferredSess = pageSession.session();
  7441. if (!scriptEnable && tabsDeferred.resolved) { }
  7442. else tabsDeferred.debounce(() => {
  7443.  
  7444. if (!tabsDeferredSess.isValid) return;
  7445. tabsDeferredSess = null;
  7446.  
  7447. if (ytEventSequence >= 2 && pageFetchedDataLocal !== null) {
  7448. domInit_comments();
  7449. newVideoPage(pageFetchedDataLocal);
  7450. pageFetchedDataLocal = null;
  7451. }
  7452.  
  7453. });
  7454.  
  7455. }
  7456.  
  7457. })
  7458.  
  7459. }
  7460.  
  7461. let pageSeqMutex = new Mutex()
  7462.  
  7463. function pageSeq1(evt) {
  7464. _navigateLoadDT = 0
  7465. if (ytEventSequence !== 1) {
  7466. ytEventSequence = 1
  7467. pageSeqMutex.lockWith(unlock=>{
  7468. pageBeingInit();
  7469. unlock();
  7470. })
  7471. }
  7472. }
  7473.  
  7474. function pageSeq2(evt) {
  7475. _navigateLoadDT = 0
  7476.  
  7477. if (ytEventSequence !== 1) {
  7478. ytEventSequence = 1
  7479. pageSeqMutex.lockWith(unlock=>{
  7480. pageBeingInit();
  7481. unlock();
  7482. })
  7483. }
  7484. if (ytEventSequence === 1) {
  7485. ytEventSequence = 2
  7486.  
  7487. pageType = null
  7488. pageSeqMutex.lockWith(unlock=>{
  7489. let mIsPageFirstLoaded = _isPageFirstLoaded
  7490. pageType = null
  7491. // mIsPageFirstLoaded && console.time("Tabview Youtube Load")
  7492. pageBeingFetched(evt, mIsPageFirstLoaded)
  7493. // mIsPageFirstLoaded && console.timeEnd("Tabview Youtube Load")
  7494. // ytMicroEventsInit set + tabview-loaded delay set
  7495. new Promise(() => {
  7496. if (ytEventSequence >= 2) {
  7497. document.documentElement.classList.toggle('tabview-normal-player', pageType === 'watch');
  7498. }
  7499. })
  7500. if (pageType !== 'watch') {
  7501. ytdFlexy = null
  7502. chatroomDetails = null
  7503. Promise.resolve(0).then(() => {
  7504. if (ytEventSequence >= 2) {
  7505. variableResets();
  7506. emptyCommentSection();
  7507. _console.log(9360, 75);
  7508. tabsDeferred.reset();
  7509. _pageBeingInit();
  7510. tabsDeferred.resolve(); // for page initialization
  7511. }
  7512. })
  7513. }
  7514.  
  7515. if (_updateTimeAccum > 0) {
  7516. let currentVideo = document.querySelector('#movie_player video[src]')
  7517. let keep_viTime = false
  7518. if (currentVideo && currentVideo.readyState > currentVideo.HAVE_CURRENT_DATA && currentVideo.currentTime > 2.2) {
  7519. // allow miniview browsing
  7520. keep_viTime = true
  7521. }
  7522. if (!keep_viTime) {
  7523. _viTimeNum = 200;
  7524. _updateTimeAccum = 0;
  7525. delete document.head.dataset.viTime;
  7526. }
  7527. }
  7528.  
  7529. unlock();
  7530. })
  7531. }
  7532.  
  7533. }
  7534.  
  7535. function pageSeq3(evt) {
  7536. _navigateLoadDT = 0
  7537. if (ytEventSequence === 2) {
  7538. ytEventSequence = 3
  7539. pageSeqMutex.lockWith(unlock => {
  7540. if (pageType === 'watch') {
  7541. let mIsPageFirstLoaded = _isPageFirstLoaded
  7542. // ytMicroEventsInit set + tabview-loaded delay set
  7543. onNavigationEndAsync(mIsPageFirstLoaded)
  7544. _isPageFirstLoaded = false
  7545. }
  7546. unlock();
  7547. })
  7548. }
  7549. }
  7550.  
  7551.  
  7552. document.addEventListener('yt-navigate-start', pageSeq1, bubblePassive)
  7553. document.addEventListener('yt-navigate-cache', pageSeq1, bubblePassive)
  7554. document.addEventListener('yt-navigate-redirect', pageSeq1, bubblePassive)
  7555. document.addEventListener('yt-page-data-fetched', pageSeq2, bubblePassive)
  7556. document.addEventListener("yt-navigate-finish", pageSeq3, bubblePassive)
  7557. //yt-navigate-redirect
  7558. //yt-page-data-fetched
  7559. //yt-navigate-error
  7560. //yt-navigate-start
  7561. //yt-page-manager-navigate-start
  7562. //yt-navigate
  7563. //yt-navigate-cache
  7564.  
  7565. globalHook('yt-page-data-fetched', generalLog901)
  7566. //globalHook('yt-rendererstamper-finished',generalLog901)
  7567. globalHook('yt-page-data-updated', generalLog901)
  7568. globalHook('yt-player-updated', generalLog901)
  7569. globalHook('yt-watch-comments-ready', generalLog901)
  7570. globalHook('yt-page-type-changed', generalLog901)
  7571. globalHook('data-changed', generalLog901)
  7572. globalHook('yt-navigate-finish', generalLog901)
  7573. globalHook('yt-navigate-redirect', generalLog901)
  7574. globalHook('yt-navigate-error', generalLog901)
  7575. globalHook('yt-navigate-start', generalLog901)
  7576. globalHook('yt-page-manager-navigate-start', generalLog901)
  7577. globalHook('yt-navigate', generalLog901)
  7578. globalHook('yt-navigate-cache', generalLog901)
  7579.  
  7580.  
  7581. // ---------------------------------------------------------------------------------------------
  7582.  
  7583.  
  7584. function manualResizeT(){
  7585.  
  7586. if (!scriptEnable) return;
  7587. if (pageType !== 'watch') return;
  7588. //lastResizeAt = Date.now();
  7589.  
  7590. if((wls.layoutStatus & LAYOUT_FULLSCREEN) === LAYOUT_FULLSCREEN ){
  7591.  
  7592. }else if ((wls.layoutStatus & LAYOUT_TWO_COLUMNS) === 0) {
  7593. // single col
  7594.  
  7595. setTimeout3(() => {
  7596. singleColumnScrolling(true)
  7597. })
  7598.  
  7599. } else {
  7600. // two cols
  7601.  
  7602. updateFloatingSlider();
  7603.  
  7604. }
  7605.  
  7606.  
  7607. }
  7608. //let lastResizeAt = 0;
  7609. let resizeCount = 0;
  7610. window.addEventListener('resize', function (evt) {
  7611.  
  7612. if (evt.isTrusted === true) {
  7613. //console.log(evt)
  7614. let tcw = ++resizeCount;
  7615. Promise.resolve(0).then(()=>{
  7616. if (tcw !== resizeCount) return;
  7617. setTimeout(() => {
  7618. // avoid duplicate calling during resizing
  7619. if (tcw !== resizeCount) return;
  7620. resizeCount = 0;
  7621. manualResizeT();
  7622. dispatchCommentRowResize();
  7623. }, 160);
  7624. });
  7625. }
  7626.  
  7627. }, bubblePassive)
  7628.  
  7629.  
  7630. document.addEventListener("tyt-chat-popup",(evt)=>{
  7631.  
  7632. let detail = (evt || 0).detail
  7633. if (!detail) return
  7634. const { popuped } = detail
  7635. if (typeof popuped !== 'boolean') return;
  7636.  
  7637. let ytdFlexyElm = es.ytdFlexy
  7638. if (!ytdFlexyElm) return
  7639.  
  7640. ytdFlexyElm.classList.toggle('tyt-chat-popup', popuped)
  7641. if (popuped === true) {
  7642. enableLivePopupCheck = true;
  7643. ytBtnSetTheater()
  7644. } else {
  7645. enableLivePopupCheck = false;
  7646. ytBtnCancelTheater()
  7647. }
  7648.  
  7649. })
  7650.  
  7651.  
  7652. let doingSelectionChange = false;
  7653. document.addEventListener("keyup", (evt) => {
  7654. if (!evt || !evt.target || !evt.key) return;
  7655. if (doingSelectionChange) {
  7656. if (!evt.shiftKey || evt.key.indexOf("Shift") == 0) {
  7657. doingSelectionChange = false;
  7658. }
  7659. }
  7660. })
  7661.  
  7662. document.addEventListener("keydown", (evt) => {
  7663. if (!evt || !evt.target || !evt.key) return;
  7664. if (evt.shiftKey && evt.key.indexOf("Arrow") == 0) {
  7665. try {
  7666. if (doingSelectionChange || !window.getSelection().isCollapsed) {
  7667. evt.stopImmediatePropagation();
  7668. evt.stopPropagation();
  7669. doingSelectionChange = true;
  7670. }
  7671.  
  7672. } catch (e) {
  7673.  
  7674. }
  7675. }
  7676. }, true);
  7677.  
  7678. let userActivation = false;
  7679.  
  7680. document.addEventListener('click', function () {
  7681. userActivation = true;
  7682.  
  7683.  
  7684. if (isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation && videoInsected) {
  7685. setTimeout(delayedClickHandler, 80);
  7686. }
  7687.  
  7688. // if(isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation){
  7689. // setTimeout(restorePIPforStickyHead, 80);
  7690. // }else if(!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && userActivation && typeof IntersectionObserver == 'function'){
  7691. // setTimeout(enablePIPforStickyHead, 80);
  7692. // }
  7693. });
  7694.  
  7695. // new comment count fetch way
  7696. document.addEventListener('ytd-comments-data-changed', function (evt) {
  7697. const hasData = (evt.detail || 0).hasData;
  7698. if (hasData === false) {
  7699. // this is much effective to clear the counting text
  7700. emptyCommentSection();
  7701. }
  7702. innerDOMCommentsCountLoader(true);
  7703. checkAndMakeNewCommentFetch();
  7704. }, true);
  7705.  
  7706. document.addEventListener('ytd-comments-header-changed', function(){
  7707. innerDOMCommentsCountLoader(true);
  7708. checkAndMakeNewCommentFetch();
  7709. }, true);
  7710.  
  7711. document.addEventListener("tabview-plugin-loaded", () => {
  7712.  
  7713. scriptletDeferred.resolve();
  7714.  
  7715. if (MINIVIEW_BROWSER_ENABLE) {
  7716. document.dispatchEvent(new CustomEvent("tabview-miniview-browser-enable"));
  7717. }
  7718.  
  7719. }, false)
  7720.  
  7721. if (isGMAvailable() && typeof GM_registerMenuCommand === 'function') {
  7722.  
  7723. let dialog = null;
  7724. function createDialog() {
  7725.  
  7726. const _themeProps_ = {
  7727. dialogBackgroundColor: '#f6f6f6',
  7728. dialogBackgroundColorDark: '#23252a',
  7729. backdropColor: '#b5b5b568',
  7730. textColor: '#111111',
  7731. textColorDark: '#f0f3f4',
  7732. zIndex: 60000,
  7733. fontSize: '10pt',
  7734. dialogMinWidth: '32px',
  7735. dialogMinHeight: '24px',
  7736. };
  7737.  
  7738. class VJSD extends VanillaJSDialog {
  7739.  
  7740. get themeProps() {
  7741. return _themeProps_
  7742. }
  7743.  
  7744. isDarkTheme() {
  7745. return document.documentElement.hasAttribute('dark');
  7746. }
  7747.  
  7748. onBeforeShow() {
  7749. const es = this.es;
  7750. if ('checkboxSelectionDisplay' in es) {
  7751. es.checkboxSelectionDisplay.textContent = '';
  7752. }
  7753. const setDefaultTabTick = (myDefaultTab) => {
  7754. for (const checkbox of document.getElementsByName('tabview-tab-default')) {
  7755. checkbox.checked = checkbox.value === myDefaultTab;
  7756. }
  7757. }
  7758. function getDefaultTabBtnSetting(store) {
  7759. if (!store) { } else {
  7760. let myDefaultTab = store[key_default_tab];
  7761. if (!myDefaultTab || typeof myDefaultTab !== 'string' || !/^\#[a-zA-Z\_\-\+]+$/.test(myDefaultTab)) {
  7762. } else {
  7763. if (document.querySelector(`.tab-btn[tyt-tab-content="${myDefaultTab}"]:not(.tab-btn-hidden)`)) return setDefaultTabTick(myDefaultTab);
  7764. }
  7765. }
  7766. setDefaultTabTick(null);
  7767. }
  7768. let store = getStore();
  7769. getDefaultTabBtnSetting(store);
  7770. }
  7771.  
  7772. onFirstCreation() {
  7773.  
  7774. const S = this.S; /* this is the global method */
  7775.  
  7776. /* on top of the setup function, override the icon widget on global method */
  7777. S.widgets.icon = (iconTag) => {
  7778. return S.ce('i', { className: 'vjsd-icon fa-solid fa-' + iconTag });
  7779. }
  7780.  
  7781. /* you might also overide `S.importCSS` by the use of Userscript Manager's import */
  7782. S.importCSS(
  7783. 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/fontawesome.min.css#sha512=SgaqKKxJDQ/tAUAAXzvxZz33rmn7leYDYfBP+YoMRSENhf3zJyx3SBASt/OfeQwBHA1nxMis7mM3EV/oYT6Fdw==',
  7784. // 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/brands.min.css',
  7785. 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/solid.min.css#sha512=yDUXOUWwbHH4ggxueDnC5vJv4tmfySpVdIcN1LksGZi8W8EVZv4uKGrQc0pVf66zS7LDhFJM7Zdeow1sw1/8Jw=='
  7786. );
  7787.  
  7788. /* load CSS files, etc - You might overide the `getTheme()` in VanillaJSDialog */
  7789. this.themeSetup();
  7790. }
  7791.  
  7792. /* init is called after setup function is called */
  7793. init() {
  7794. const S = this.S; /* this is the global method */
  7795.  
  7796. const es = this.es; /* this is a store for HTMLElements binded to this dialog */
  7797.  
  7798. es.dialog = S.ce('div', {
  7799. className: 'vjsd-dialog'
  7800. }, {
  7801. '__vjsd__': ''
  7802. });
  7803.  
  7804. es.dialog.append(
  7805. es.header = S.ce('div', {
  7806. className: 'vjsd-dialog-header vjsd-hflex'
  7807. }),
  7808. es.body = S.ce('div', {
  7809. className: 'vjsd-dialog-body vjsd-gap-2 vjsd-overscroll-none vjsd-vflex'
  7810. }),
  7811. es.footer = S.ce('div', {
  7812. className: 'vjsd-dialog-footer vjsd-hflex'
  7813. }),
  7814.  
  7815. );
  7816.  
  7817. es.header.append(
  7818. S.widgets.icon('circle-info', (a) => {
  7819.  
  7820. }),
  7821. S.widgets.title('Tabview Youtube - Change Default Tab', {
  7822. className: 'vjsd-flex-fill'
  7823. }),
  7824. S.widgets.buttonIcon('square-xmark', {
  7825. 'vjsd-clickable': '#dialogXmark'
  7826. })
  7827. );
  7828.  
  7829. const checkBoxChanged = () => {
  7830. let elmChoice1 = [...document.getElementsByName('tabview-tab-default')].filter(e => e.checked).map(e => e.value);
  7831. console.assert(elmChoice1.length <= 1);
  7832. es.checkboxSelectionDisplay.textContent = elmChoice1.length === 1 ? `The default tab will be set to ${elmChoice1[0]}` : `The default tab will be reset.`;
  7833. }
  7834.  
  7835. es.body.append(
  7836. S.widgets.labeledRadio('vjsd-checkbox1 vjsd-checkbox-tick', 'Info', (elmLabel, elmInput) => {
  7837. elmInput.name = 'tabview-tab-default';
  7838. elmInput.value = '#tab-info';
  7839. es.checkbox1 = elmInput;
  7840. elmInput.addEventListener('change', checkBoxChanged)
  7841. elmLabel.style.fontSize = '200%';
  7842. }),
  7843. S.widgets.labeledRadio('vjsd-checkbox1 vjsd-checkbox-tick', 'Comment', (elmLabel, elmInput) => {
  7844. elmInput.name = 'tabview-tab-default';
  7845. elmInput.value = '#tab-comments';
  7846. es.checkbox2 = elmInput;
  7847. elmInput.addEventListener('change', checkBoxChanged)
  7848. elmLabel.style.fontSize = '200%';
  7849. }),
  7850. S.widgets.labeledRadio('vjsd-checkbox1 vjsd-checkbox-tick', 'Video', (elmLabel, elmInput) => {
  7851. elmInput.name = 'tabview-tab-default';
  7852. elmInput.value = '#tab-videos';
  7853. es.checkbox3 = elmInput;
  7854. elmInput.addEventListener('change', checkBoxChanged)
  7855. elmLabel.style.fontSize = '200%';
  7856. }),
  7857. es.checkboxSelectionDisplay = S.ce('div', { className: 'vjsd-custom-widget' })
  7858. );
  7859.  
  7860. const onXMarkClicked = () => {
  7861. this.dismiss();
  7862. }
  7863.  
  7864. const onClearClicked = () => {
  7865. es.checkbox1.checked = false;
  7866. es.checkbox2.checked = false;
  7867. es.checkbox3.checked = false;
  7868. checkBoxChanged();
  7869. }
  7870.  
  7871. const onConfirmClicked = () => {
  7872. let myDefaultTab = null;
  7873. for (const checkbox of document.getElementsByName('tabview-tab-default')) {
  7874. if (checkbox.checked) myDefaultTab = checkbox.value;
  7875. }
  7876. myDefaultTab = myDefaultTab || null;
  7877. console.log(myDefaultTab)
  7878. setMyDefaultTab(myDefaultTab);
  7879. this.dismiss();
  7880. }
  7881.  
  7882. const onCancelClicked = () => {
  7883. this.dismiss();
  7884. }
  7885.  
  7886. es.footer.append(
  7887. es.clearButton = S.widgets.button('Clear', {
  7888. 'vjsd-clickable': '#clear'
  7889. }),
  7890. S.widgets.space(),
  7891. S.widgets.button('Cancel', {
  7892. 'vjsd-clickable': '#cancel'
  7893. }),
  7894. S.widgets.button('Confirm', {
  7895. 'vjsd-clickable': '#confirm'
  7896. }),
  7897. )
  7898.  
  7899. this.clickable('#cancel', onCancelClicked)
  7900. this.clickable('#clear', onClearClicked)
  7901. this.clickable('#confirm', onConfirmClicked)
  7902. this.clickable('#dialogXmark', onXMarkClicked);
  7903.  
  7904. this.backdrop = 'dismiss';
  7905. document.body.appendChild(es.dialog)
  7906. }
  7907. }
  7908.  
  7909. VJSD.setup1();
  7910. return new VJSD();
  7911. }
  7912.  
  7913. GM_registerMenuCommand("Change Default Tab", function () {
  7914. dialog = dialog || createDialog();
  7915. dialog.show();
  7916. });
  7917.  
  7918. /*
  7919. GM_registerMenuCommand("Default Tab: NULL", function () {
  7920. setMyDefaultTab(null);
  7921. });
  7922. GM_registerMenuCommand("Default Tab: Info", function () {
  7923. setMyDefaultTab("#tab-info");
  7924. });
  7925. GM_registerMenuCommand("Default Tab: Comments", function () {
  7926. setMyDefaultTab("#tab-comments");
  7927. });
  7928. GM_registerMenuCommand("Default Tab: Video", function () {
  7929. setMyDefaultTab("#tab-videos");
  7930. });
  7931. */
  7932. }
  7933.  
  7934.  
  7935. document.documentElement.setAttribute('plugin-tabview-youtube', `${scriptVersionForExternal}`)
  7936. if(document.documentElement.getAttribute('tabview-unwrapjs')){
  7937. document.dispatchEvent(new CustomEvent("tabview-plugin-loaded"))
  7938. }
  7939.  
  7940.  
  7941. // function nestedObjectFlatten(prefix, obj) {
  7942. // let ret = {};
  7943. // let _prefix = prefix ? `${prefix}.` : '';
  7944. // let isObject = (obj && typeof obj == 'object' && obj.constructor.name == 'Object');
  7945. // let isArray = (obj && typeof obj == 'object' && obj.constructor.name == 'Array');
  7946. // const f = (k, v) => {
  7947. // let isObject = (v && typeof v == 'object' && v.constructor.name == 'Object');
  7948. // let isArray = (v && typeof v == 'object' && v.constructor.name == 'Array');
  7949. // if (isObject || isArray) {
  7950. // let r = nestedObjectFlatten(k, v)
  7951. // for (const w in r) {
  7952. // ret[`${_prefix}${w}`] = r[w];
  7953. // }
  7954. // } else {
  7955. // ret[`${_prefix}${k}`] = v;
  7956. // }
  7957. // }
  7958. // if (isObject) {
  7959. // for (const k in obj) {
  7960. // let v = obj[k];
  7961. // f(k, v);
  7962. // }
  7963. // } else if (isArray) {
  7964. // let idx = 0;
  7965. // for (const v of obj) {
  7966. // let k = `[${idx}]`;
  7967. // f(k, v);
  7968. // idx++;
  7969. // }
  7970. // }
  7971. // return ret;
  7972. // }
  7973.  
  7974. /*
  7975.  
  7976. for(const p of document.querySelectorAll('ytd-watch-flexy *')){ let m = p.data; if(!m)continue; console.log(m)}
  7977.  
  7978. function objec
  7979.  
  7980. */
  7981.  
  7982.  
  7983. //Object.keys($0).filter(key=>!(key in $0.constructor.prototype))
  7984.  
  7985. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML'))
  7986. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML')).filter(k=>$0 instanceof window[k])
  7987.  
  7988.  
  7989. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  7990.  
  7991. /*
  7992. fix bug for comment section - version 1.8.7
  7993. This issue is the bug in browser's rendering
  7994. I guess, this is due to the lines clamp with display:-webkit-box
  7995. use stupid coding to let it re-render when its content become visible
  7996. /*
  7997.  
  7998. ytd-expander[should-use-number-of-lines][collapsed] > #content.ytd-expander {
  7999. color: var(--yt-spec-text-primary);
  8000. display: -webkit-box;
  8001. overflow: hidden;
  8002. max-height: none;
  8003. -webkit-box-orient: vertical;
  8004. -webkit-line-clamp: var(--ytd-expander-max-lines, 4);
  8005. }
  8006.  
  8007. // v1.8.36 imposed a effective solution for fixing this bug
  8008.  
  8009. */
  8010.  
  8011. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  8012.  
  8013.  
  8014. /**
  8015. *
  8016.  
  8017.  
  8018. f.initChildrenObserver=function(){var a=this;this.observer=new MutationObserver(function(){return a.childrenChanged()});
  8019. this.observer.observe(this.$.content,{subtree:!0,childList:!0,attributes:!0});this.childrenChanged()};
  8020. f.childrenChanged=function(){var a=this;this.alwaysToggleable?this.canToggle=this.alwaysToggleable:this.canToggleJobId||(this.canToggleJobId=window.requestAnimationFrame(function(){$h(function(){a.canToggleJobId=0;a.calculateCanCollapse()})}))};
  8021.  
  8022.  
  8023. f.onIronResize=function(){this.recomputeOnResize&&this.childrenChanged()};
  8024.  
  8025.  
  8026. onButtonClick_:function(){this.fire("yt-close-upsell-dialog")},
  8027. computeHasHeader_:function(a){return!!a.headerBackgroundImage}});var geb;var heb;var ieb;var jeb;var xI=function(){var a=L.apply(this,arguments)||this;a.alignAuto=!1;a.collapsed=!0;a.isToggled=!1;a.alwaysCollapsed=!1;a.canToggle=!0;a.collapsedHeight=80;a.disableToggle=!1;a.alwaysToggleable=!1;a.reversed=!1;a.shouldUseNumberOfLines=!1;a.recomputeOnResize=!1;a.canToggleJobId=0;return a};
  8028. n(xI,L);f=xI.prototype;f.alwaysToggleableChanged=function(){this.alwaysToggleable&&(this.canToggle=!0)};
  8029.  
  8030.  
  8031. f.calculateCanCollapse=function(){this.canToggle=this.shouldUseNumberOfLines?this.alwaysToggleable||this.$.content.offsetHeight<this.$.content.scrollHeight:this.alwaysToggleable||this.$.content.scrollHeight>this.collapsedHeight};
  8032. f.detachObserver=function(){this.observer&&this.observer.disconnect()};
  8033.  
  8034. *
  8035. *
  8036. *
  8037. */
  8038.  
  8039.  
  8040. })();
  8041. // console.timeEnd("Tabview Youtube Init Script")
  8042.  
  8043. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  8044.  
  8045. }
  8046.  
  8047.  
  8048. ;!(function $$() {
  8049. 'use strict';
  8050.  
  8051. if(document.documentElement==null) return window.requestAnimationFrame($$)
  8052.  
  8053. const cssTxt = GM_getResourceText("contentCSS");
  8054.  
  8055. function addStyle (styleText) {
  8056. const styleNode = document.createElement('style');
  8057. styleNode.textContent = styleText;
  8058. document.documentElement.appendChild(styleNode);
  8059. return styleNode;
  8060. }
  8061.  
  8062. addStyle (cssTxt);
  8063.  
  8064. main();
  8065.  
  8066. })();