Tabview Youtube

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

当前为 2023-10-09 提交的版本,查看 最新版本

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