Tabview Youtube

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

目前为 2023-05-17 提交的版本,查看 最新版本

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