Tabview Youtube

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

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

  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.61.2
  182. // @resource contentCSS https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/dada976f92eb760629531d3c4d6e24b82e3fefa4/css/style_content.css
  183. // @resource chatCSS https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/dada976f92eb760629531d3c4d6e24b82e3fefa4/css/style_chat.css
  184. // @resource controlCSS https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/dada976f92eb760629531d3c4d6e24b82e3fefa4/css/style_control.css
  185. // @resource injectionJS1 https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/dada976f92eb760629531d3c4d6e24b82e3fefa4/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. const iframe = document.querySelector('body iframe.style-scope.ytd-live-chat-frame#chatframe');
  2342. // console.log("iframe.xx",501,iframe)
  2343. if (iframe) Promise.resolve(iframe).then(iframeLoadProcess);
  2344.  
  2345. pageCheck();
  2346. if (global_columns_end_ito !== null) {
  2347. //to trigger observation at the time layout being changed
  2348. if ((new_layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) {
  2349. let endpos = document.querySelector('tabview-view-columns-endpos')
  2350. if (endpos !== null) {
  2351. global_columns_end_ito.observe(endpos)
  2352. }
  2353. } else {
  2354. global_columns_end_ito.disconnect();
  2355. }
  2356. }
  2357. setTimeout3(() => {
  2358. singleColumnScrolling(true); //initalize sticky
  2359. });
  2360. })
  2361. }
  2362.  
  2363. if (enableLivePopupCheck === true) {
  2364.  
  2365. const new_isTwoColumnsTheater = fT(new_layoutStatus, LAYOUT_TWO_COLUMNS | LAYOUT_THEATER, 0)
  2366.  
  2367. let currentIsTheaterPopupChat = new_isTwoColumnsTheater && new_isExpandedChat && isChatPopupedF()
  2368. if (!currentIsTheaterPopupChat) {
  2369. enableLivePopupCheck = false
  2370. document.dispatchEvent(new CustomEvent("tyt-close-popup"))
  2371. }
  2372.  
  2373. }
  2374.  
  2375.  
  2376. }
  2377.  
  2378. function fixLayoutStatus(x) {
  2379. const new_isExpandedChat = !(x & LAYOUT_CHATROOM_COLLAPSED) && (x & LAYOUT_CHATROOM)
  2380. return new_isExpandedChat ? (x | LAYOUT_CHATROOM_EXPANDED) : (x & ~LAYOUT_CHATROOM_EXPANDED);
  2381. }
  2382.  
  2383. const wls = new Proxy({
  2384. /** @type {number | null} */
  2385. layoutStatus: undefined
  2386. }, {
  2387. get: function (target, prop) {
  2388. return target[prop];
  2389. },
  2390. set: function (target, prop, value) {
  2391. if (prop == 'layoutStatus') {
  2392.  
  2393. if (value === 0) {
  2394. target[prop] = value;
  2395. return true;
  2396. } else if (target[prop] === value) {
  2397. return true;
  2398. } else {
  2399. if (!target.layoutStatus_pending) {
  2400. target.layoutStatus_pending = true;
  2401. const old_layoutStatus = target[prop];
  2402. target[prop] = value;
  2403. layoutStatusMutex.lockWith(unlock => {
  2404. target.layoutStatus_pending = false;
  2405. let new_layoutStatus = target[prop];
  2406. if (old_layoutStatus !== new_layoutStatus) {
  2407. layoutStatusChanged(old_layoutStatus, new_layoutStatus);
  2408. timeline.setTimeout(unlock, 40)
  2409. } else {
  2410. unlock();
  2411. }
  2412. })
  2413. return true;
  2414. }
  2415. }
  2416. }
  2417. target[prop] = value;
  2418. return true;
  2419. },
  2420. has: function (target, prop) {
  2421. return (prop in target);
  2422. }
  2423. });
  2424.  
  2425. 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>`
  2426.  
  2427. function isVideoPlaying(video) {
  2428. return video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  2429. }
  2430.  
  2431. function wAttr(elm, attr, kv) {
  2432. if (elm) {
  2433. if (kv === true) {
  2434. elm.setAttribute(attr, '');
  2435. } else if (kv === false) {
  2436. elm.removeAttribute(attr);
  2437. } else if (kv === null) {
  2438. //;
  2439. } else if (typeof kv == 'string') {
  2440. elm.setAttribute(attr, kv);
  2441. }
  2442. }
  2443. }
  2444.  
  2445. function setTabBtnVisible(tabBtn, toVisible) {
  2446. let doClassListChange = false;
  2447. if (tabBtn.getAttribute('tyt-tab-content') === '#tab-comments') {
  2448. isCommentsTabBtnHidden = !toVisible;
  2449. if ((hiddenTabsByUserCSS & 2) !== 2) {
  2450. doClassListChange = true;
  2451. }
  2452. } else {
  2453. doClassListChange = true;
  2454. }
  2455. if (doClassListChange) {
  2456. if (toVisible) {
  2457. tabBtn.classList.remove("tab-btn-hidden");
  2458. } else {
  2459. tabBtn.classList.add("tab-btn-hidden");
  2460. }
  2461. }
  2462. }
  2463.  
  2464. function hideTabBtn(tabBtn) {
  2465. //console.log('hideTabBtn', tabBtn)
  2466. let isActiveBefore = tabBtn.classList.contains('active');
  2467. setTabBtnVisible(tabBtn, false);
  2468. if (isActiveBefore) {
  2469. setToActiveTab();
  2470. }
  2471. }
  2472.  
  2473. // function hasAttribute(obj, key) {
  2474. // return obj && obj.hasAttribute(key);
  2475. // }
  2476.  
  2477. function isTheater() {
  2478. const cssElm = es.ytdFlexy;
  2479. return (cssElm && cssElm.hasAttribute('theater'))
  2480. }
  2481.  
  2482. function isFullScreen() {
  2483. const cssElm = es.ytdFlexy;
  2484. return (cssElm && cssElm.hasAttribute('fullscreen'))
  2485. }
  2486.  
  2487. function isChatExpand() {
  2488. const cssElm = es.ytdFlexy;
  2489. return cssElm && (cssElm.getAttribute('tyt-chat') || '').charAt(0) === '+'
  2490. }
  2491.  
  2492. function isWideScreenWithTwoColumns() {
  2493. const cssElm = es.ytdFlexy;
  2494. return (cssElm && cssElm.hasAttribute('is-two-columns_'))
  2495. }
  2496.  
  2497.  
  2498. function isAnyActiveTab() {
  2499. return document.querySelector('#right-tabs .tab-btn.active') !== null
  2500. }
  2501. // function isAnyActiveTab2() {
  2502. // return document.querySelectorAll('#right-tabs .tab-btn.active').length > 0
  2503. // }
  2504.  
  2505. function isEngagementPanelExpanded() { //note: not checking the visual elements
  2506. const cssElm = es.ytdFlexy;
  2507. return (cssElm && +cssElm.getAttribute('tyt-ep-visible') > 0)
  2508. }
  2509.  
  2510. function isDonationShelfExpanded() {
  2511. const cssElm = es.ytdFlexy;
  2512. return (cssElm && cssElm.hasAttribute('tyt-donation-shelf'))
  2513. }
  2514.  
  2515. const engagementIdMap = new Map();
  2516. let engagementIdNext = 1; // max 1 << 62
  2517.  
  2518. function engagement_panels_() {
  2519.  
  2520. let res = [];
  2521. // let shownRes = [];
  2522.  
  2523. let v = 0;
  2524. // let k = 1;
  2525. // let count = 0;
  2526.  
  2527. for (const ePanel of document.querySelectorAll(
  2528. `ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility]:not([hidden])`
  2529. )) {
  2530. let targetId = ePanel.getAttribute('target-id')
  2531. if (typeof targetId !== 'string') continue;
  2532. let eId = engagementIdMap.get(targetId)
  2533. if (!eId) {
  2534. engagementIdMap.set(targetId, eId = engagementIdNext)
  2535. if (engagementIdNext === (1 << 62)) {
  2536. engagementIdNext = 1;
  2537. console.warn('engagementId reached 1 << 62')
  2538. } else {
  2539. engagementIdNext = engagementIdNext << 1;
  2540. }
  2541. }
  2542. // console.log(55,eId, targetId)
  2543.  
  2544. let visibility = ePanel.getAttribute('visibility') //ENGAGEMENT_PANEL_VISIBILITY_EXPANDED //ENGAGEMENT_PANEL_VISIBILITY_HIDDEN
  2545.  
  2546. let k = eId
  2547. switch (visibility) {
  2548. case 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED':
  2549. v |= k;
  2550. // count++;
  2551. // shownRes.push(ePanel)
  2552. res.push({ ePanel, k, visible: true });
  2553. break;
  2554. case 'ENGAGEMENT_PANEL_VISIBILITY_HIDDEN':
  2555. res.push({ ePanel, k, visible: false });
  2556. break;
  2557. default:
  2558. res.push({ ePanel, k, visible: false });
  2559. }
  2560.  
  2561. //k = k << 1;
  2562.  
  2563. }
  2564. return { list: res, value: v };
  2565. // return { list: res, value: v, count: count, shownRes };
  2566. }
  2567.  
  2568.  
  2569. function ytBtnOpenEngagementPanel(/** @type {number | string} */ panel_id) {
  2570.  
  2571. // console.log(panel_id)
  2572. if (typeof panel_id == 'string') {
  2573. panel_id = panel_id.replace('#engagement-panel-', '');
  2574. panel_id = parseInt(panel_id);
  2575. }
  2576. if (panel_id >= 0) { } else return false;
  2577.  
  2578. let panels = engagement_panels_();
  2579. // console.log(panels)
  2580.  
  2581. let actions = []
  2582. for (const { ePanel, k, visible } of panels.list) {
  2583. if ((panel_id & k) === k) {
  2584. if (!visible) {
  2585. actions.push({
  2586. panelId: ePanel.getAttribute('target-id'),
  2587. toShow: true
  2588. })
  2589. }
  2590. } else {
  2591. if (visible) {
  2592. actions.push({
  2593. panelId: ePanel.getAttribute('target-id'),
  2594. toHide: true
  2595. })
  2596. }
  2597. }
  2598. }
  2599.  
  2600. if (actions.length > 0) {
  2601. // console.log(4545,actions)
  2602. const _actions = actions;
  2603. scriptletDeferred.debounce(() => {
  2604. document.dispatchEvent(new CustomEvent('tyt-engagement-panel-visibility-change', {
  2605. detail: _actions
  2606. }));
  2607. });
  2608. }
  2609. actions = null;
  2610.  
  2611. }
  2612.  
  2613. function ytBtnCloseEngagementPanel(/** @type {HTMLElement} */ s) {
  2614. //ePanel.setAttribute('visibility',"ENGAGEMENT_PANEL_VISIBILITY_HIDDEN");
  2615.  
  2616. let panelId = s.getAttribute('target-id')
  2617. scriptletDeferred.debounce(() => {
  2618. document.dispatchEvent(new CustomEvent('tyt-engagement-panel-visibility-change', {
  2619. detail: {
  2620. panelId,
  2621. toHide: true
  2622. }
  2623. }))
  2624. })
  2625.  
  2626. }
  2627.  
  2628. function ytBtnCloseEngagementPanels() {
  2629. if (isEngagementPanelExpanded()) {
  2630. for (const s of document.querySelectorAll(
  2631. `ytd-watch-flexy[flexy][tyt-tab] #panels.ytd-watch-flexy ytd-engagement-panel-section-list-renderer[target-id][visibility]:not([hidden])`
  2632. )) {
  2633. if (s.getAttribute('visibility') == "ENGAGEMENT_PANEL_VISIBILITY_EXPANDED") ytBtnCloseEngagementPanel(s);
  2634. }
  2635. }
  2636. }
  2637.  
  2638. function openDonationShelf() {
  2639. if (!isDonationShelfExpanded()) {
  2640. let btn = document.querySelector('#tyt-donation-shelf-toggle-btn')
  2641. if (btn) {
  2642. btn.click();
  2643. return true;
  2644. }
  2645. }
  2646. return false;
  2647. }
  2648. function closeDonationShelf() {
  2649. if (isDonationShelfExpanded()) {
  2650. let btn = document.querySelector('#tyt-donation-shelf-toggle-btn')
  2651. if (btn) {
  2652. btn.click();
  2653. return true;
  2654. }
  2655. }
  2656. return false;
  2657. }
  2658.  
  2659. function ytBtnSetTheater() {
  2660. if (!isTheater()) {
  2661. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  2662. if (sizeBtn) sizeBtn.click();
  2663. }
  2664. }
  2665.  
  2666. function ytBtnCancelTheater() {
  2667. if (isTheater()) {
  2668. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  2669. if (sizeBtn) sizeBtn.click();
  2670. }
  2671. }
  2672.  
  2673. function ytBtnExpandChat() {
  2674. let button = document.querySelector('ytd-live-chat-frame#chat[collapsed] > .ytd-live-chat-frame#show-hide-button')
  2675. if (button) {
  2676. button =
  2677. querySelectorFromAnchor.call(button, 'div.yt-spec-touch-feedback-shape') ||
  2678. querySelectorFromAnchor.call(button, 'ytd-toggle-button-renderer');
  2679. if (button) button.click();
  2680. }
  2681. }
  2682.  
  2683. function ytBtnCollapseChat() {
  2684. let button = document.querySelector('ytd-live-chat-frame#chat:not([collapsed]) > .ytd-live-chat-frame#show-hide-button')
  2685. if (button) {
  2686. button =
  2687. querySelectorFromAnchor.call(button, 'div.yt-spec-touch-feedback-shape') ||
  2688. querySelectorFromAnchor.call(button, 'ytd-toggle-button-renderer');
  2689. if (button) button.click();
  2690. }
  2691. }
  2692.  
  2693.  
  2694. async function makeVideosAutoLoad2() {
  2695. let sVideosList = document.querySelector('ytd-watch-flexy #tab-videos [placeholder-videos]');
  2696.  
  2697. if (!sVideosList) return null;
  2698.  
  2699. //let ab = sVideosList.getAttribute('tabview-videos-autoload')
  2700. await Promise.resolve(0);
  2701.  
  2702. let endPosDOM = document.querySelector('tabview-view-videos-endpos')
  2703. if (endPosDOM) endPosDOM.remove(); // just in case
  2704. endPosDOM = document.createElement('tabview-view-videos-endpos')
  2705. insertAfterTo(endPosDOM, sVideosList);
  2706.  
  2707. await Promise.resolve(0);
  2708.  
  2709.  
  2710. //sVideosList.setAttribute('tabview-videos-autoload', '1')
  2711.  
  2712. // _console.log(9333)
  2713. if (!sVideosITO) {
  2714.  
  2715. sVideosITO = new IntersectionObserver((entries) => {
  2716.  
  2717. if ((wls.layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) return;
  2718.  
  2719. // _console.log(9334, entries)
  2720. if (entries.length !== 1) return;
  2721. if (entries[0].isIntersecting !== true) return;
  2722. let elm = ((entries[0] || 0).target || 0);
  2723. if (!elm) return;
  2724. elm = null;
  2725. entries = null;
  2726.  
  2727. new Promise(resolve => {
  2728.  
  2729. // compatibile with Search While Watching Video
  2730. 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]');
  2731. if (isSearchGeneratedWithHiddenContinuation) return;
  2732.  
  2733. // native YouTube coding use different way to handle custom videos, unknown condition for the continutation loading.
  2734. 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"]')
  2735. if (isOtherChipSelected) return;
  2736.  
  2737. setTimeout(resolve, 30); // delay required to allow YouTube generate the continuation elements
  2738.  
  2739.  
  2740. }).then(() => {
  2741.  
  2742. let res = setVideosTwoColumns(2 | 4, true)
  2743.  
  2744. // _console.log(9335, res)
  2745.  
  2746. if (res.m2 && res.m3) {
  2747. const m4 = closestDOM.call(res.m2, 'ytd-continuation-item-renderer');
  2748.  
  2749. if (m4) {
  2750.  
  2751. const m5 = querySelectorFromAnchor.call(m4, 'ytd-button-renderer.style-scope.ytd-continuation-item-renderer, yt-button-renderer.style-scope.ytd-continuation-item-renderer');
  2752.  
  2753. // YouTube coding bug - correct is 'ytd-button-renderer'. If the page is redirected under single column mode, the tag become 'yt-button-renderer'
  2754. // under 'yt-button-renderer', the
  2755.  
  2756. const m6 = querySelectorFromAnchorX(m5, 'button.yt-spec-button-shape-next--call-to-action'); // main
  2757.  
  2758. // _console.log(9337, m4, m5, m6)
  2759.  
  2760. if (m6) {
  2761. m6.click() // generic solution
  2762. } else if (m5) {
  2763. m5.click(); // not sure
  2764. } else {
  2765. m4.dispatchEvent(new Event('yt-service-request-sent-button-renderer')); // only for correct YouTube coding
  2766. }
  2767. }
  2768. }
  2769. res = null;
  2770.  
  2771. });
  2772.  
  2773. }, {
  2774. rootMargin: `0px`, // refer to css margin-top:-30vh
  2775. threshold: [0]
  2776. })
  2777. sVideosITO.observe(endPosDOM);
  2778. } else {
  2779. sVideosITO.disconnect();
  2780. sVideosITO.observe(endPosDOM);
  2781. }
  2782.  
  2783.  
  2784. }
  2785.  
  2786.  
  2787. function fixTabs() {
  2788.  
  2789. scriptletDeferred.debounce(() => {
  2790.  
  2791.  
  2792. // if(document.documentElement.hasAttribute('p355')) return;
  2793.  
  2794. if (!scriptEnable) return;
  2795.  
  2796. let queryElement = document.querySelector('*:not(#tab-videos) > #related.ytd-watch-flexy > ytd-watch-next-secondary-results-renderer');
  2797.  
  2798. let isRelocated = !!queryElement;
  2799.  
  2800. if (isRelocated) {
  2801. // if(1885) return;
  2802.  
  2803. // _console.log(3202, 2)
  2804.  
  2805. let relatedElm = closestDOM.call(queryElement, '#related.ytd-watch-flexy'); // NOT NULL
  2806.  
  2807. let right_tabs = document.querySelector('#right-tabs'); // can be NULL
  2808.  
  2809. let tab_videos = querySelectorFromAnchorX(right_tabs, "#tab-videos"); // can be NULL
  2810.  
  2811. if (tab_videos !== null) {
  2812.  
  2813. // _console.log(3202, 4)
  2814.  
  2815. 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')
  2816. if (target_container) elementAppend.call(target_container, right_tabs) // last-child
  2817.  
  2818. elementAppend.call(tab_videos, relatedElm);
  2819. // no any other element set these attr. only init / relocation
  2820. relatedElm.setAttribute('placeholder-for-youtube-play-next-queue', '')
  2821. relatedElm.setAttribute('placeholder-videos', '')
  2822.  
  2823. makeVideosAutoLoad2();
  2824.  
  2825. }
  2826.  
  2827. }
  2828.  
  2829. /** @type {HTMLElement | null} */
  2830. check1885();
  2831. if (!chatController.allowChatControl) return;
  2832.  
  2833. let chatroom = null;
  2834. if (chatroom = document.querySelector('ytd-live-chat-frame#chat')) {
  2835.  
  2836. const container = chatroom.parentNode.id === 'chat-container' ? chatroom.parentNode : chatroom;
  2837.  
  2838. let pHolderElm = document.querySelector('tabview-view-pholder[data-positioner="before|#chat"]');
  2839.  
  2840. if (!pHolderElm || pHolderElm.nextElementSibling !== container) {
  2841.  
  2842.  
  2843. if (pHolderElm) pHolderElm.remove();
  2844.  
  2845.  
  2846.  
  2847. // if (1885 && document.body.hasAttribute('data-ytlstm-theater-mode')) {
  2848.  
  2849. // } else
  2850. if (document.querySelector('.YouTubeLiveFilledUpView')) {
  2851. // no relocation
  2852. } else {
  2853.  
  2854. let rightTabs = document.querySelector('#right-tabs');
  2855. if (rightTabs) {
  2856. insertBeforeTo(container, rightTabs);
  2857. }
  2858.  
  2859. }
  2860.  
  2861. if (!pHolderElm) {
  2862. pHolderElm = document.createElement('tabview-view-pholder');
  2863. pHolderElm.setAttribute('data-positioner', 'before|#chat');
  2864. }
  2865.  
  2866. insertBeforeTo(pHolderElm, container)
  2867. }
  2868.  
  2869. }
  2870.  
  2871.  
  2872. })
  2873.  
  2874. }
  2875.  
  2876.  
  2877. async function isDocumentInFullScreenMode() {
  2878. return document.fullscreenElement !== null;
  2879. }
  2880. async function energizedByVideoTimeUpdate() {
  2881.  
  2882. const isFullscreen = await isDocumentInFullScreenMode();
  2883. if (isFullscreen) return;
  2884.  
  2885. // force browser to load the videostream during playing (primarily for music videos)
  2886. // both background and foreground
  2887.  
  2888. _updateTimeAccum++;
  2889.  
  2890. if ((_updateTimeAccum + _viTimeNum) % 11 === 0) {
  2891. // console.log(document.querySelector('video').currentTime) // 2.55, 2.64, 3.12, ...
  2892. // about 2.66s
  2893.  
  2894. if (_viTimeNum > 211) {
  2895. // around 30.9s ~ 31.9s
  2896. _viTimeNum = 200;
  2897. _updateTimeAccum = (_updateTimeAccum % 8) + 1; // reset to 1 ~ 8
  2898. postMessage({ tabviewEnergized: true }, 'https://www.youtube.com'); // post message to make alive
  2899. }
  2900.  
  2901. document.head.dataset.viTime = `${_viTimeNum + 1}`;
  2902. await Promise.resolve(0)
  2903. _viTimeNum = +document.head.dataset.viTime || 0;
  2904. }
  2905.  
  2906.  
  2907. }
  2908.  
  2909. function autoCompletePosCreate() {
  2910.  
  2911. let positioner = document.createElement("tabview-view-autocomplete-pos");
  2912. let oldPositioner = document.querySelector("tabview-view-autocomplete-pos");
  2913. if (oldPositioner) oldPositioner.remove();
  2914. return positioner
  2915. }
  2916.  
  2917. function handlerAutoCompleteExist() {
  2918. // Youtube - Search While Watching Video
  2919.  
  2920. if (document.querySelector('autocomplete-holder')) return;
  2921.  
  2922. /** @type {HTMLElement} */
  2923. let searchBox, autoComplete;
  2924. searchBox = this;
  2925. this.removeEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false)
  2926. let domId = this.getAttribute('data-autocomplete-results-id')
  2927.  
  2928. autoComplete = document.querySelector(`[data-autocomplete-input-id="${domId}"]`)
  2929.  
  2930. if (!domId || !searchBox) return;
  2931.  
  2932. let positioner = nodePrevSibling(searchBox);
  2933. if (!positioner || positioner.nodeName.toLowerCase() !== "tabview-view-autocomplete-pos") {
  2934. positioner = autoCompletePosCreate();
  2935. insertBeforeTo(positioner, searchBox);
  2936. }
  2937. prependTo(autoComplete, positioner);
  2938.  
  2939. setupSearchBox(searchBox, positioner);
  2940.  
  2941. }
  2942.  
  2943. async function setupSearchBox(searchBox, positioner) {
  2944.  
  2945. let h = searchBox.offsetHeight + 'px'
  2946.  
  2947. positioner.style.setProperty('--tyt-swwv-searchbox-h', h)
  2948.  
  2949. mtf_autocomplete_search()
  2950.  
  2951. }
  2952.  
  2953. function mtf_autocomplete_search() {
  2954. // Youtube - Search While Watching Video
  2955.  
  2956. /** @type {HTMLElement | null} */
  2957. const ytdFlexyElm = es.ytdFlexy;
  2958. if (!scriptEnable || !ytdFlexyElm) return;
  2959.  
  2960. 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])')
  2961.  
  2962. if (autocomplete) {
  2963.  
  2964. const searchBox = document.querySelector('[placeholder-for-youtube-play-next-queue] input#suggestions-search')
  2965.  
  2966.  
  2967. if (searchBox) {
  2968.  
  2969. const rAutoComplete = mWeakRef(autocomplete);
  2970.  
  2971. function setVisible(autocomplete, b) {
  2972. autocomplete.style.display = (b ? 'block' : 'none');
  2973. }
  2974.  
  2975. function isContentNotEmpty(searchbox, autocomplete) {
  2976. return (searchbox.value || '').length > 0 && (autocomplete.textContent || '').length > 0;
  2977. }
  2978.  
  2979. nodeParent(autocomplete).setAttribute('position-fixed-by-tabview-youtube', '');
  2980. autocomplete.setAttribute('position-fixed-by-tabview-youtube', '');
  2981. autocomplete.setAttribute('userscript-scrollbar-render', '')
  2982.  
  2983. //let cancelClickToggle = false;
  2984.  
  2985. if (!searchBox.hasAttribute('is-set-click-to-toggle')) {
  2986. searchBox.setAttribute('is-set-click-to-toggle', '')
  2987.  
  2988. searchBox.addEventListener('click', function () {
  2989.  
  2990. Promise.resolve(0).then(() => {
  2991.  
  2992. const autocomplete = kRef(rAutoComplete);
  2993.  
  2994. if (!autocomplete) return;
  2995.  
  2996. const isNotEmpty = isContentNotEmpty(this, autocomplete);
  2997.  
  2998. if (isNotEmpty) {
  2999.  
  3000. let elmVisible = isDOMVisible(autocomplete);
  3001.  
  3002. if (elmVisible) {
  3003. setVisible(autocomplete, false)
  3004. }
  3005. else {
  3006. setVisible(autocomplete, true)
  3007. }
  3008.  
  3009. }
  3010.  
  3011. })
  3012.  
  3013. }, bubblePassive)
  3014.  
  3015. let cacheScrollIntoView = null;
  3016. let rafXC = 0;
  3017. searchBox.addEventListener('keydown', function (evt) {
  3018. //cancelClickToggle = true;
  3019. switch (evt.code) {
  3020. case 'ArrowUp':
  3021. case 'ArrowDown':
  3022.  
  3023. let t = Date.now();
  3024. if (rafXC === 0) {
  3025. getRAFPromise().then(() => {
  3026. rafXC = 0;
  3027. let d = Date.now();
  3028. if (d - t > 300) return;
  3029.  
  3030. const autocomplete = kRef(rAutoComplete);
  3031. if (!autocomplete) return;
  3032.  
  3033. let selected = querySelectorFromAnchor.call(autocomplete, '.autocomplete-suggestion.selected');
  3034. let bool = selected && selected !== cacheScrollIntoView;
  3035. cacheScrollIntoView = selected;
  3036. if (bool) {
  3037.  
  3038. try {
  3039. selected.scrollIntoView({ block: "nearest", inline: "nearest" });
  3040. } catch (e) { }
  3041.  
  3042. }
  3043.  
  3044. });
  3045. rafXC = 1;
  3046. }
  3047. default:
  3048. //
  3049. }
  3050.  
  3051.  
  3052. }, bubblePassive)
  3053.  
  3054. searchBox.addEventListener('tyt-autocomplete-suggestions-change', function (evt) {
  3055.  
  3056. //cancelClickToggle = true;
  3057. if (evt.target !== document.activeElement) return;
  3058. setTimeout(() => {
  3059. const autocomplete = document.querySelector(`.autocomplete-suggestions[data-autocomplete-input-id="${this.getAttribute('data-autocomplete-results-id')}"]`);
  3060. if (!autocomplete) return;
  3061. const isNotEmpty = isContentNotEmpty(this, autocomplete);
  3062. if (isNotEmpty) {
  3063. // dont detect visibility; just set to visible
  3064. setVisible(autocomplete, true);
  3065. }
  3066. }, 20);
  3067.  
  3068. }, bubblePassive)
  3069.  
  3070. }
  3071.  
  3072. }
  3073.  
  3074. }
  3075.  
  3076. }
  3077.  
  3078. const insertBeforeTo = HTMLElement.prototype.before ? (elm, target) => {
  3079. if (!target || !elm) return null;
  3080. // using before
  3081. HTMLElement.prototype.before.call(target, elm);
  3082. return true;
  3083. } : (elm, target) => {
  3084. if (!target || !elm) return null;
  3085. // using insertBefore
  3086. try {
  3087. HTMLElement.prototype.insertBefore.call(nodeParent(target), elm, target);
  3088. return true;
  3089. } catch (e) {
  3090. console.log('element insert failed in old browser CE')
  3091. }
  3092. return false;
  3093. }
  3094.  
  3095. const insertAfterTo = HTMLElement.prototype.after ? (elm, target) => {
  3096. if (!target || !elm) return null;
  3097. // using after
  3098. HTMLElement.prototype.after.call(target, elm);
  3099. return true;
  3100. } : (elm, target) => {
  3101. if (!target || !elm) return null;
  3102. // using insertBefore
  3103. try {
  3104. HTMLElement.prototype.insertBefore.call(nodeParent(target), elm, nodeNextSibling(target));
  3105. return true;
  3106. } catch (e) {
  3107. console.log('element insert failed in old browser CE')
  3108. }
  3109. return false;
  3110. }
  3111.  
  3112. const prependTo = HTMLElement.prototype.prepend ? (elm, target) => {
  3113. if (!target || !elm) return null;
  3114. // using prepend
  3115. HTMLElement.prototype.prepend.call(target, elm);
  3116. return true;
  3117. } : (elm, target) => {
  3118. if (!target || !elm) return null;
  3119. // using insertBefore
  3120. try {
  3121. HTMLElement.prototype.insertBefore.call(target, elm, nodeFirstChild(target));
  3122. return true;
  3123. } catch (e) {
  3124. console.log('element insert failed in old browser CE')
  3125. }
  3126. return false;
  3127. }
  3128.  
  3129. const appends = HTMLElement.prototype.append ? (target, ...args) => {
  3130. HTMLElement.prototype.append.call(target, ...args);
  3131. return true;
  3132. } : (target, ...args) => {
  3133. for (const s of args) {
  3134. target.appendChild(s)
  3135. }
  3136. return true;
  3137. }
  3138.  
  3139.  
  3140.  
  3141.  
  3142. function getWrapper(wrapperId) {
  3143. let wrapper = document.getElementById(wrapperId);
  3144. if (!wrapper) {
  3145. wrapper = document.createElement('div');
  3146. wrapper.id = wrapperId;
  3147. }
  3148. return wrapper;
  3149. }
  3150.  
  3151. // continuous check for element relocation
  3152. // fired at begining & window resize, etc
  3153. // might moved to #primary
  3154. function mtf_append_playlist(/** @type {HTMLElement | null} */ playlist) {
  3155.  
  3156. if (playlist === null) {
  3157. playlist = document.querySelector('ytd-watch-flexy[playlist] *:not(#tabview-playlist-wrapper) > ytd-playlist-panel-renderer.style-scope.ytd-watch-flexy#playlist:not(.ytd-miniplayer)');
  3158. // this playlist is highly possible to have '#items'
  3159. if (!playlist) return;
  3160. }
  3161.  
  3162. /** @type {HTMLElement | null} */
  3163. const ytdFlexyElm = es.ytdFlexy;
  3164. if (!scriptEnable || !ytdFlexyElm) return;
  3165.  
  3166. let items = querySelectorFromAnchor.call(playlist, "*:not(#tabview-playlist-wrapper) > ytd-playlist-panel-renderer#playlist:not(.ytd-miniplayer) #items.ytd-playlist-panel-renderer:not(:empty)");
  3167.  
  3168. if (items !== null && playlist.nodeName.toUpperCase() === 'YTD-PLAYLIST-PANEL-RENDERER') {
  3169.  
  3170. let tab_list = document.querySelector("#tab-list");
  3171.  
  3172. if (!tab_list) return;
  3173.  
  3174. let w = getWrapper("tabview-playlist-wrapper");
  3175. let docFrag = new DocumentFragment();
  3176. // avoid immediate reflow for append playlist before append to tab_list
  3177. docFrag.appendChild(w);
  3178. elementAppend.call(w, playlist);
  3179. elementAppend.call(tab_list, docFrag);
  3180. docFrag = null;
  3181. w = null;
  3182.  
  3183. }
  3184. }
  3185.  
  3186.  
  3187. function getCountHText(elm) {
  3188. return `${pageFetchedDataVideoId || 0}...${elm.textContent}`
  3189. }
  3190.  
  3191. // content fix - info & playlist
  3192. // fired at begining, and keep for in case any change
  3193. async function mtf_fix_details() {
  3194.  
  3195. if (!scriptEnable) return 0; // in case
  3196.  
  3197. await scriptletDeferred.d();
  3198. await Promise.all([
  3199. Promise.resolve().then(()=> {
  3200.  
  3201. 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])');
  3202.  
  3203. if (contentToggleBtn) {
  3204.  
  3205. const domElement = contentToggleBtn;
  3206. contentToggleBtn = null;
  3207. // if(!domElement.parentElement) return; // not working in pseudo custom element - parentNode = documentFragment
  3208. const expander = closestDOM.call(domElement, 'ytd-watch-flexy #tab-info ytd-expander')
  3209.  
  3210. if (!expander || expander.nodeType !== 1) return; // checking whether it is still on the page
  3211.  
  3212. if (expander.style.getPropertyValue('--ytd-expander-collapsed-height')) {
  3213. expander.style.setProperty('--ytd-expander-collapsed-height', '')
  3214. }
  3215. expander.dispatchEvent(new CustomEvent("tabview-expander-config"));
  3216.  
  3217. }
  3218.  
  3219. }),
  3220.  
  3221. Promise.resolve().then(()=> {
  3222.  
  3223.  
  3224. let strcturedInfo = document.querySelector('ytd-watch-flexy #tab-info ytd-structured-description-content-renderer.style-scope.ytd-video-secondary-info-renderer[hidden]')
  3225. if (strcturedInfo) {
  3226.  
  3227.  
  3228. strcturedInfo.removeAttribute('hidden');
  3229.  
  3230.  
  3231. setTimeout(() => {
  3232.  
  3233.  
  3234. let e = closestDOM.call(strcturedInfo, 'ytd-watch-flexy #tab-info ytd-expander');
  3235.  
  3236. if (!e) return;
  3237. let s = querySelectorAllFromAnchor.call(e, '#tab-info .more-button.style-scope.ytd-video-secondary-info-renderer[role="button"]');
  3238. if (s.length === 1) {
  3239. let sp = nodeParent(s[0]);
  3240. if (sp.nodeName.toUpperCase() === 'TP-YT-PAPER-BUTTON') {
  3241. sp.click();
  3242. }
  3243. }
  3244.  
  3245. }, 300)
  3246.  
  3247. }
  3248.  
  3249.  
  3250. }),
  3251.  
  3252. Promise.resolve().then(() => {
  3253.  
  3254.  
  3255. // just in case the playlist is collapsed
  3256. let playlist = document.querySelector('#tab-list ytd-playlist-panel-renderer#playlist')
  3257. if (playlist && playlist.matches('[collapsed], [collapsible]')) {
  3258.  
  3259.  
  3260.  
  3261. const domElement = playlist;
  3262. playlist = null;
  3263. // if(!domElement.parentElement || domElement.nodeType!==1) return; // not working in pseudo custom element - parentNode = documentFragment
  3264. const tablist = closestDOM.call(domElement, 'ytd-watch-flexy #tab-list')
  3265.  
  3266. if (!tablist || tablist.nodeType !== 1) return; // checking whether it is still on the page
  3267.  
  3268. if (domElement.hasAttribute('collapsed')) wAttr(domElement, 'collapsed', false);
  3269. if (domElement.hasAttribute('collapsible')) wAttr(domElement, 'collapsible', false);
  3270.  
  3271. }
  3272.  
  3273.  
  3274. }),
  3275.  
  3276. Promise.resolve().then(() => {
  3277.  
  3278.  
  3279. let subscribersCount = document.querySelector('#primary.ytd-watch-flexy #below ytd-watch-metadata #owner #owner-sub-count');
  3280.  
  3281. if (subscribersCount) {
  3282. if (!subscribersCount.hasAttribute('title')) {
  3283. // assume YouTube native coding would not implement [title]
  3284.  
  3285. let ytdWatchMetaDataElm = closestDOM.call(subscribersCount, 'body #primary.ytd-watch-flexy #below ytd-watch-metadata:not([tabview-uploader-hover])');
  3286. if (ytdWatchMetaDataElm) {
  3287. ytdWatchMetaDataElm.setAttribute('tabview-uploader-hover', '')
  3288. let _h = 0;
  3289. ytdWatchMetaDataElm.addEventListener('transitionend', function (evt) {
  3290. // no css selector rule required; no delay js function call required
  3291.  
  3292. let selection = evt.propertyName === 'background-position-y' ? 1 : evt.propertyName === 'background-position-x' ? 2 : 0;
  3293.  
  3294. if (selection && evt.target) {
  3295. let cssRoot = this; // no querySelector is required
  3296. if (cssRoot.classList.contains('tabview-uploader-hover')) {
  3297. if (evt.target.id !== 'owner') return;
  3298. cssRoot.classList.toggle('tabview-uploader-hover', false);
  3299. }
  3300. }
  3301.  
  3302. if (selection === 1) { // string comparision only
  3303.  
  3304. // If the cursor initially stayed at the owner info area,
  3305. // the mechanism will be broken
  3306. // so implement the true leave detection at their parent
  3307.  
  3308. let isHover = evt.elapsedTime < 0.03; // 50ms @normal; 10ms @hover;
  3309.  
  3310. let cssRoot = this; // no querySelector is required
  3311. if (!isHover) {
  3312. // 50ms is slowest than sub element leave effect
  3313. if (_h > 0) cssRoot.classList.toggle('tabview-uploader-hover', false) // even the order is incorrect, removal of class is safe.
  3314. _h = 0; // in case
  3315. } else if (isHover) {
  3316. // 10ms is faster than sub element hover effect
  3317. // no removal of class in case browser's transition implemention order is incorrect
  3318. _h = 0; // in case
  3319. }
  3320.  
  3321. } else if (selection === 2) { // string comparision only
  3322.  
  3323. //from one element to another element; hover effect of 2nd element transition end first.
  3324. // _h: 0 -> 1 -> 2 -> 1
  3325.  
  3326. let isHover = evt.elapsedTime < 0.03; // 40ms @normal; 20ms @hover;
  3327. if (isHover) _h++; else _h--;
  3328. let cssRoot = this; // no querySelector is required
  3329. if (_h <= 0) {
  3330. cssRoot.classList.toggle('tabview-uploader-hover', false)
  3331. _h = 0; // in case
  3332. } else if (_h === 1) {
  3333. cssRoot.classList.toggle('tabview-uploader-hover', true)
  3334. }
  3335.  
  3336. }
  3337.  
  3338. }, capturePassive) // capture the hover effect inside the cssRoot
  3339. }
  3340.  
  3341. }
  3342. subscribersCount.setAttribute('title', subscribersCount.textContent); // set at every page update
  3343.  
  3344. }
  3345.  
  3346. })
  3347.  
  3348.  
  3349. ]);
  3350.  
  3351.  
  3352. }
  3353.  
  3354.  
  3355. const innerCommentsFuncs = [
  3356. // comments
  3357. function () {
  3358.  
  3359. let elm = kRef(this.elm);
  3360. // _console.log(2907, 1, !!elm)
  3361. if (!elm) return;
  3362.  
  3363. let span = document.querySelector("span#tyt-cm-count")
  3364. let r = '0';
  3365. let txt = elm.textContent
  3366. if (typeof txt == 'string') {
  3367. let m = txt.match(/[\d\,\.\s]+/)
  3368. if (m) {
  3369. let d = +m[0].replace(/\D+/g, '');
  3370. let ds = d.toLocaleString(document.documentElement.lang);
  3371. let rtxt = txt.replace(ds, '')
  3372. if (rtxt !== txt && !/\d/.test(rtxt)) {
  3373. r = ds;
  3374. }
  3375. }
  3376. }
  3377.  
  3378. if (span) {
  3379. let tab_btn = closestDOM.call(span, '.tab-btn[tyt-tab-content="#tab-comments"]')
  3380. if (tab_btn) tab_btn.setAttribute('loaded-comment', 'normal')
  3381. span.textContent = r;
  3382. }
  3383.  
  3384. setCommentSection(1);
  3385. m_last_count = getCountHText(elm);
  3386. // _console.log(2907, 2, m_last_count)
  3387. return true;
  3388. },
  3389. // message
  3390. function () {
  3391.  
  3392. let elm = kRef(this.elm);
  3393. // _console.log(2907, 2, !!elm)
  3394. if (!elm) return;
  3395.  
  3396. let span = document.querySelector("span#tyt-cm-count")
  3397. if (span) {
  3398. let tab_btn = closestDOM.call(span, '.tab-btn[tyt-tab-content="#tab-comments"]')
  3399. if (tab_btn) tab_btn.setAttribute('loaded-comment', 'message')
  3400. span.textContent = '\u200B';
  3401. }
  3402.  
  3403. setCommentSection(1);
  3404. m_last_count = getCountHText(elm);
  3405. // _console.log(2907, 2, m_last_count)
  3406. return true;
  3407. }
  3408. ]
  3409.  
  3410.  
  3411. let innerDOMCommentsCountTextCache = null;
  3412. /**
  3413. *
  3414. * @param {boolean} [requireResultCaching]
  3415. * @returns
  3416. */
  3417. function innerDOMCommentsCountLoader(requireResultCaching) {
  3418. // independent of tabs initialization
  3419. // f() is executed after tabs being ready
  3420.  
  3421. /** @type {HTMLElement | null} */
  3422. const ytdFlexyElm = es.ytdFlexy;
  3423. if (!scriptEnable || !ytdFlexyElm) return;
  3424.  
  3425. // _console.log(3434, pageType)
  3426. if (pageType !== 'watch') return;
  3427.  
  3428. /** @type {HTMLElement | null} */
  3429. const qtElm = document.querySelector('ytd-comments#comments');
  3430. if (!qtElm) return;
  3431.  
  3432. /** @type {Array<HTMLElement>} */
  3433. 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');
  3434.  
  3435. const eTime = +`${Date.now() - mTime}00`;
  3436.  
  3437. let res = new Array(qmElms.length);
  3438. res.newFound = false;
  3439.  
  3440.  
  3441. let ci = 0;
  3442. let latest = -1;
  3443.  
  3444. let retrival = cmTime;
  3445. cmTime = eTime;
  3446.  
  3447. for (const qmElm of qmElms) {
  3448.  
  3449. let mgz = 0
  3450. if (qmElm.id === 'count') {
  3451. //#count.ytd-comments-header-renderer
  3452. mgz = 1;
  3453.  
  3454. } else if ((qmElm.textContent || '').trim()) {
  3455. //ytd-message-renderer.ytd-item-section-renderer
  3456. mgz = 2;
  3457. // it is possible to get the message before the header generation.
  3458. // sample link - https://www.youtube.com/watch?v=PVUZ8Nvr1ic
  3459. // sample link - https://www.youtube.com/watch?v=yz8AiQc1Bk8
  3460. }
  3461.  
  3462. if (mgz > 0) {
  3463.  
  3464.  
  3465. let lastUpdate = loadedCommentsDT.get(qmElm) || 0;
  3466. let diff = retrival - lastUpdate
  3467. // _console.log(2907, diff)
  3468. let isNew = (diff > 4 || diff < -4);
  3469. if (!isNew) {
  3470. loadedCommentsDT.set(qmElm, eTime);
  3471. } else {
  3472. loadedCommentsDT.set(qmElm, eTime + 1);
  3473. res.newFound = true;
  3474. latest = ci;
  3475. }
  3476.  
  3477. res[ci] = {
  3478. elm: mWeakRef(qmElm),
  3479. isNew: isNew,
  3480. isLatest: false, //set afterwards
  3481. f: innerCommentsFuncs[mgz - 1]
  3482. }
  3483.  
  3484. if (DEBUG_LOG) {
  3485. res[ci].status = mgz;
  3486. res[ci].text = qmElm.textContent;
  3487. }
  3488.  
  3489. ci++;
  3490.  
  3491. }
  3492.  
  3493. }
  3494. if (res.length > ci) res.length = ci;
  3495.  
  3496. if (latest >= 0) {
  3497.  
  3498. res[latest].isLatest = true;
  3499.  
  3500.  
  3501. let elm = kRef(res[latest].elm);
  3502. if (elm)
  3503. innerDOMCommentsCountTextCache = elm.textContent;
  3504.  
  3505. } else if (res.length === 1) {
  3506.  
  3507. let qmElm = kRef(res[0].elm);
  3508. let t = null;
  3509. if (qmElm) {
  3510.  
  3511. let t = qmElm.textContent;
  3512. if (t !== innerDOMCommentsCountTextCache) {
  3513.  
  3514.  
  3515. loadedCommentsDT.set(qmElm, eTime + 1);
  3516. res.newFound = true;
  3517.  
  3518. res[0].isNew = true;
  3519. latest = 0;
  3520.  
  3521. res[latest].isLatest = true;
  3522.  
  3523. }
  3524.  
  3525. innerDOMCommentsCountTextCache = t;
  3526.  
  3527.  
  3528. }
  3529.  
  3530.  
  3531. }
  3532.  
  3533.  
  3534. // _console.log(2908, res, Q.comments_section_loaded)
  3535.  
  3536. // _console.log(696, res.map(e => ({
  3537.  
  3538. // text: kRef(e.elm).textContent,
  3539. // isNew: e.isNew,
  3540. // isLatest: e.isLatest
  3541.  
  3542. // })))
  3543.  
  3544. if (requireResultCaching) {
  3545. resultCommentsCountCaching(res);
  3546. }
  3547.  
  3548. return res;
  3549.  
  3550. }
  3551.  
  3552. function restoreFetching() {
  3553.  
  3554.  
  3555. if (mtf_forceCheckLiveVideo_disable === 2) return;
  3556.  
  3557.  
  3558. const ytdFlexyElm = es.ytdFlexy;
  3559. if (!ytdFlexyElm) return;
  3560.  
  3561. // _console.log(2901)
  3562.  
  3563. if ((ytdFlexyElm.getAttribute('tyt-comments') || '').indexOf('K') >= 0) return;
  3564.  
  3565. // _console.log(2902)
  3566.  
  3567. let visibleComments = querySelectorFromAnchor.call(ytdFlexyElm, 'ytd-comments#comments:not([hidden])')
  3568. if (!visibleComments) return;
  3569.  
  3570. // _console.log(2903)
  3571.  
  3572.  
  3573. ytdFlexyElm.setAttribute('tyt-comments', 'Kz');
  3574.  
  3575. const tabBtn = document.querySelector('[tyt-tab-content="#tab-comments"]');
  3576. let span = querySelectorFromAnchor.call(tabBtn, 'span#tyt-cm-count');
  3577. tabBtn.removeAttribute('loaded-comment')
  3578. span.innerHTML = '';
  3579.  
  3580. if (tabBtn) {
  3581. setTabBtnVisible(tabBtn, true);
  3582. }
  3583.  
  3584. // _console.log(2905)
  3585.  
  3586.  
  3587. }
  3588.  
  3589. function checkAndMakeNewCommentFetch() {
  3590. if (renderDeferred.resolved && Q.comments_section_loaded === 0 && fetchCounts.new && !fetchCounts.fetched) {
  3591. fetchCounts.new.f();
  3592. fetchCounts.fetched = true;
  3593. fetchCommentsFinished();
  3594. // _console.log(9972, 'fetched = true')
  3595. }
  3596. }
  3597. function onCommentsReady(e) {
  3598. // e => from commentsHeaderAppended
  3599. let b = false;
  3600. if (e && mtf_forceCheckLiveVideo_disable !== 2 && document.querySelector('ytd-comments#comments:not([hidden])')) {
  3601. // 'YTD-COMMENTS-HEADER-RENDERER', native DOM
  3602. setCommentSection(0);
  3603. checkAndMakeNewCommentFetch();
  3604. b = true;
  3605. }
  3606. _onCommentsReady(b);
  3607. }
  3608. function _onCommentsReady(b) {
  3609. if (mtf_forceCheckLiveVideo_disable !== 2) {
  3610. if (document.querySelector('ytd-comments#comments').hasAttribute('hidden')) {
  3611. // unavailable but not due to live chat
  3612. _disableComments();
  3613. } else if (Q.comments_section_loaded === 0) {
  3614. if (b || (comments_loader & 3) === 3) {
  3615. getFinalComments();
  3616. }
  3617. }
  3618. }
  3619. }
  3620.  
  3621. const resultCommentsCountCaching = (res) => {
  3622. // update fetchCounts by res
  3623. // indepedent of previous state of fetchCounts
  3624. // _console.log(2908, 10, res)
  3625. if (!res) return;
  3626. fetchCounts.count = res.length;
  3627. //if(fetchCounts.new && !document.documentElement.contains(fetchCounts.new.elm)) fetchCounts.new = null;
  3628. //if(fetchCounts.base && !document.documentElement.contains(fetchCounts.base.elm)) fetchCounts.base = null;
  3629. if (fetchCounts.new) return;
  3630. let newFound = res.newFound;
  3631. if (!newFound) {
  3632. if (res.length === 1) {
  3633. fetchCounts.base = res[0];
  3634. return false;
  3635. }
  3636. } else if (res.length === 1) {
  3637. fetchCounts.new = res[0];
  3638. return true;
  3639. } else if (res.length > 1) {
  3640. for (const entry of res) {
  3641. if (entry.isLatest === true && entry.isNew) {
  3642. fetchCounts.new = entry;
  3643. return true;
  3644. }
  3645. }
  3646. }
  3647. }
  3648.  
  3649. const domInit_comments = () => {
  3650.  
  3651.  
  3652. let comments = document.querySelector(`ytd-comments#comments:not([o3r-${sa_comments}])`);
  3653. if (!comments) return;
  3654.  
  3655. // once per {ytd-comments#comments} detection
  3656.  
  3657. const ytdFlexyElm = es.ytdFlexy;
  3658. if (!scriptEnable || !ytdFlexyElm) return;
  3659.  
  3660. if (mtoVisibility_Comments.bindElement(comments)) {
  3661. mtoVisibility_Comments.observer.check(9);
  3662. }
  3663.  
  3664.  
  3665. };
  3666.  
  3667. const skIdFixChatToggleBtnEventDispatch = ControllerID();
  3668. const fixLiveChatToggleButtonDispatchEvent = () => {
  3669. scriptletDeferred.debounce(() => {
  3670. document.dispatchEvent(new CustomEvent("tabview-fix-live-chat-toggle-btn"));
  3671. }, skIdFixChatToggleBtnEventDispatch);
  3672. }
  3673.  
  3674.  
  3675.  
  3676. const eventDispatcher = (evtName) => {
  3677. const erid = ControllerID();
  3678. return (evtNode) => {
  3679. scriptletDeferred.debounce(() => {
  3680. const b = !(evtNode instanceof HTMLElement) || evtNode.isConnected === true;
  3681. b && evtNode.dispatchEvent(new CustomEvent(evtName));
  3682. }, erid);
  3683. }
  3684. }
  3685.  
  3686. let chatroomAttrCollapseCount = 0;
  3687.  
  3688. // const dpeForceChatRenderOnChatExpanded = eventDispatcher("tabview-force-chat-render-on-chat-expanded");
  3689.  
  3690. // const dpeNewUrlChat = eventDispatcher("tabview-chat-fix-url-on-new-video-page");
  3691. const dpeFixUrlChatWhenOnloadWithEmptyBody = eventDispatcher("tabview-chat-fix-url-onload-with-empty-body");
  3692.  
  3693. const dpeIframeReady = eventDispatcher('tabview-chatroom-ready');
  3694.  
  3695. const FP = {
  3696.  
  3697. mtf_attrPlaylist: (attrName, newValue) => {
  3698. //attr mutation checker - {ytd-playlist-panel-renderer#playlist} \single
  3699. //::attr ~ hidden
  3700. //console.log(1210)
  3701.  
  3702. // _console.log(21311)
  3703. if (!scriptEnable) return;
  3704. if (pageType !== 'watch') return;
  3705. /** @type {HTMLElement|null} */
  3706. let cssElm = es.ytdFlexy;
  3707. if (!cssElm) return;
  3708.  
  3709. // _console.log(21312)
  3710.  
  3711. let playlist = document.querySelector('#tab-list ytd-playlist-panel-renderer#playlist'); // can be null if it is manually triggered
  3712. let isAnyPlaylistExist = playlist && !playlist.hasAttribute('hidden');
  3713. const tabBtn = document.querySelector('[tyt-tab-content="#tab-list"]');
  3714. //console.log(1212.2, isPlaylistHidden, playlist.getAttribute('hidden'))
  3715. if (tabBtn) {
  3716. //console.log('attr playlist changed')
  3717. let isPlaylistTabHidden = tabBtn.classList.contains('tab-btn-hidden')
  3718. if (isPlaylistTabHidden && isAnyPlaylistExist) {
  3719. //console.log('attr playlist changed - no hide')
  3720. tabBtn.classList.remove("tab-btn-hidden");
  3721. } else if (!isPlaylistTabHidden && !isAnyPlaylistExist) {
  3722. //console.log('attr playlist changed - add hide')
  3723. hideTabBtn(tabBtn);
  3724. }
  3725. }
  3726. /* visible layout for triggering hidden removal */
  3727.  
  3728. },
  3729. mtf_attrComments: (attrName, newValue) => {
  3730. //attr mutation checker - {ytd-comments#comments} \single
  3731. //::attr ~ hidden
  3732.  
  3733. // *** consider this can happen immediately after pop state. timeout / interval might clear out.
  3734.  
  3735. renderDeferred.resolved && innerDOMCommentsCountLoader(true);
  3736. // this is triggered by mutationobserver, the comment count update might have ouccred
  3737.  
  3738. if (pageType !== 'watch') return;
  3739.  
  3740. let comments = document.querySelector('ytd-comments#comments')
  3741. const tabBtn = document.querySelector('[tyt-tab-content="#tab-comments"]');
  3742. if (!comments || !tabBtn) return;
  3743. let isCommentHidden = comments.hasAttribute('hidden')
  3744. //console.log('attr comments changed')
  3745.  
  3746.  
  3747. const ytdFlexyElm = es.ytdFlexy;
  3748. if (!scriptEnable || !ytdFlexyElm) return;
  3749.  
  3750. if (mtf_forceCheckLiveVideo_disable === 2) {
  3751.  
  3752. } else if (!isCommentHidden) {
  3753.  
  3754. ytdFlexyElm.setAttribute('tyt-comments', 'Kv');
  3755. if (!fetchCounts.fetched) {
  3756. emptyCommentSection();
  3757. }
  3758. //_console.log(9360, 71);
  3759. setTabBtnVisible(tabBtn, true); //if contains
  3760.  
  3761. } else if (isCommentHidden) {
  3762.  
  3763. ytdFlexyElm.setAttribute('tyt-comments', 'Kh');
  3764. if (pageType === 'watch' && Q.comments_section_loaded === 1) {
  3765. emptyCommentSection();
  3766. // _console.log(9360, 72);
  3767. }
  3768.  
  3769. }
  3770.  
  3771.  
  3772. },
  3773.  
  3774. mtf_attrChatroom: () => {
  3775. //attr mutation checker - {ytd-live-chat-frame#chat} \single
  3776. //::attr ~ collapsed
  3777.  
  3778. const ytdFlexyElm = es.ytdFlexy;
  3779. if (!scriptEnable || !ytdFlexyElm) return;
  3780. if (pageType !== 'watch') return;
  3781.  
  3782. setToggleBtnTxt();
  3783.  
  3784. layoutStatusMutex.lockWith(unlock => {
  3785.  
  3786. const chatBlock = document.querySelector('ytd-live-chat-frame#chat')
  3787. /** @type {HTMLElement | null} */
  3788. const cssElm = es.ytdFlexy;
  3789.  
  3790. if (!chatBlock || !cssElm) {
  3791. unlock();
  3792. return;
  3793. }
  3794.  
  3795. if (pageType !== 'watch') {
  3796. unlock();
  3797. return;
  3798. }
  3799.  
  3800. let newAttrV = '';
  3801. //mtf_attrChatroom => chat exist => tyt-chat non-null
  3802.  
  3803. let isCollapsed = !!chatBlock.hasAttribute('collapsed');
  3804.  
  3805. let currentAttr = cssElm.getAttribute('tyt-chat');
  3806.  
  3807. if (currentAttr !== null) { //string // [+-]?[az]+[az\$]+
  3808. let isPlusMinus = currentAttr.charCodeAt(0) < 46; // 43 OR 45
  3809. if (isPlusMinus) newAttrV = currentAttr.substring(1);
  3810. }
  3811.  
  3812. if (isCollapsed) newAttrV = `-${newAttrV}`;
  3813. if (!isCollapsed) newAttrV = `+${newAttrV}`;
  3814.  
  3815. wAttr(cssElm, 'tyt-chat', newAttrV);
  3816.  
  3817.  
  3818. if (typeof newAttrV === 'string' && !isCollapsed) lstTab.lastPanel = '#chatroom';
  3819.  
  3820. if (!isCollapsed && isAnyActiveTab() && isWideScreenWithTwoColumns() && !isTheater()) {
  3821. switchTabActivity(null);
  3822. timeline.setTimeout(unlock, 40);
  3823. } else {
  3824. unlock();
  3825. }
  3826.  
  3827. if (isCollapsed) {
  3828. ++chatroomAttrCollapseCount;
  3829. // chatBlock.removeAttribute('tyt-iframe-loaded');
  3830. chatBlock.classList.remove('tyt-chat-frame-ready');
  3831. // console.log(922,1)
  3832. // buggy; this section might not be correctly executed.
  3833. // guess no collapse change but still iframe will distory and reload.
  3834. let btn = document.querySelector('tyt-iframe-popup-btn')
  3835. if (btn) btn.remove();
  3836. } else {
  3837.  
  3838. const iframe = querySelectorFromAnchor.call(chatBlock, 'body iframe.style-scope.ytd-live-chat-frame#chatframe');
  3839. // console.log("iframe.xx",501,iframe)
  3840. if (iframe) Promise.resolve(iframe).then(iframeLoadProcess); // fix empty
  3841.  
  3842.  
  3843. /*
  3844. console.log("iframe.xx",1243,0)
  3845.  
  3846. if (pageFetchedDataVideoId && chatroomAttrCollapseCount !== newVideoPageCACC && newVideoPageCACC >= 0) {
  3847. console.log("iframe.xx",1243,1)
  3848.  
  3849. console.debug('[tyt] forceChatRenderOnChatExpanded')
  3850. const _chatBlock = chatBlock;
  3851. const tyid = dpeChatRefreshCounter();
  3852. setTimeout(() => {
  3853. if (pageFetchedDataVideoId && chatroomAttrCollapseCount !== newVideoPageCACC && newVideoPageCACC >= 0) {
  3854. if (tyid !== +dpeChatRefreshCounter) return;
  3855. dpeChatRefreshCounter();
  3856. const chat = document.querySelector('ytd-live-chat-frame#chat');
  3857. const chatBlock = _chatBlock;
  3858. if (chat === chatBlock && !chatBlock.hasAttribute('collapsed')) {
  3859. // dpeForceChatRenderOnChatExpanded(chatBlock);
  3860. const iframe = querySelectorFromAnchor.call(chat, 'iframe');
  3861. console.log("iframe.xx",1244,iframe)
  3862. if (iframe) iframeLoadProcess(iframe);
  3863. }
  3864. }
  3865. }, 67);
  3866. }
  3867. */
  3868. }
  3869.  
  3870. fixLiveChatToggleButtonDispatchEvent();
  3871.  
  3872. })
  3873.  
  3874.  
  3875. },
  3876.  
  3877. mtf_attrEngagementPanel: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  3878. //attr mutation checker - {ytd-engagement-panel-section-list-renderer} \mutiple
  3879. //::attr ~ visibility
  3880.  
  3881. const cssElm = es.ytdFlexy;
  3882. if (!scriptEnable || !cssElm) return;
  3883. let found = null
  3884. if (mutations === 9) {
  3885. found = observer
  3886. } else {
  3887. 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])')) {
  3888. // do nothing
  3889. } else {
  3890. mtoVisibility_EngagementPanel.clear(true)
  3891. storeLastPanel = null;
  3892. wAttr(cssElm, 'tyt-ep-visible', false);
  3893. }
  3894. return
  3895. }
  3896. let nextValue = engagement_panels_().value;
  3897. let previousValue = +cssElm.getAttribute('tyt-ep-visible') || 0;
  3898. if (nextValue === 0 || previousValue === nextValue) return
  3899. cssElm.setAttribute('tyt-ep-visible', nextValue);
  3900. lstTab.lastPanel = `#engagement-panel-${nextValue}`;
  3901. storeLastPanel = mWeakRef(found)
  3902. discardableFn(() => {
  3903. if (es.storeLastPanel !== found) return
  3904. layoutStatusMutex.lockWith(unlock => {
  3905. if (es.storeLastPanel === found && whenEngagemenetPanelVisible()) {
  3906. timeline.setTimeout(unlock, 40);
  3907. } else {
  3908. unlock();
  3909. }
  3910. });
  3911. });
  3912. }
  3913.  
  3914. }
  3915.  
  3916.  
  3917. function variableResets() {
  3918.  
  3919. // reset variables when it is confirmed a new page is loaded
  3920.  
  3921. lstTab =
  3922. {
  3923. lastTab: null, //tab-xxx
  3924. lastPanel: null,
  3925. last: null
  3926. };
  3927.  
  3928. scriptEnable = false;
  3929. ytdFlexy = null;
  3930. wls.layoutStatus = 0;
  3931.  
  3932. mtoVisibility_Playlist.clear(true)
  3933. mtoVisibility_Comments.clear(true)
  3934.  
  3935. mtoVisibility_Chatroom.clear(true)
  3936. mtoFlexyAttr.clear(true)
  3937. mtoBodyAttr.clear(true)
  3938.  
  3939.  
  3940. mtf_chatBlockQ = null;
  3941.  
  3942. }
  3943.  
  3944.  
  3945.  
  3946. function contentExtractor(elm) {
  3947. if (!(elm instanceof HTMLElement)) {
  3948. return null;
  3949. }
  3950. let m = elm.textContent;
  3951. let isEmpty = m.trim().length === 0;
  3952. if (isEmpty) return null;
  3953. let s = elm.nodeName;
  3954. let id = elm.id;
  3955. if (id) s += '#' + id;
  3956. return s + '\n' + m;
  3957. }
  3958.  
  3959. async function checkDuplicatedMetaRecommendation() {
  3960. let mainContent0 = document.querySelector('#primary.ytd-watch-flexy #above-the-fold.ytd-watch-metadata');
  3961. let mainContent1 = document.querySelector('#tab-info ytd-expander > #content');
  3962. if (mainContent0 && mainContent1) {
  3963. const hashedContents = new Set();
  3964. for (let s1 = elementNextSibling(mainContent1); s1 instanceof HTMLElement; s1 = elementNextSibling(s1)) {
  3965. let m = contentExtractor(s1);
  3966. if (m === null) continue;
  3967. hashedContents.add(m);
  3968. }
  3969.  
  3970. for (let s0 = elementNextSibling(mainContent0); s0 instanceof HTMLElement; s0 = elementNextSibling(s0)) {
  3971. let m = contentExtractor(s0);
  3972. if (m !== null && hashedContents.has(m)) {
  3973. s0.classList.add('tyt-hidden-duplicated-meta');
  3974. } else {
  3975. s0.classList.remove('tyt-hidden-duplicated-meta');
  3976. }
  3977. }
  3978. hashedContents.clear();
  3979. }
  3980. }
  3981.  
  3982. const elementMapper = new WeakMap();
  3983.  
  3984.  
  3985. const isContentDuplicationCheckAllow = () => {
  3986. return document.querySelectorAll('[tyt-info-expander-placeholder]').length === 1 && document.querySelectorAll('[tyt-info-expander-content]').length === 1;
  3987. }
  3988.  
  3989. let waitForContentReady = new PromiseExternal(); // dummy initial value
  3990.  
  3991. async function removeContentMismatch() {
  3992.  
  3993. if (!document.querySelector('#tab-info')) return;
  3994. const dmysOnPage = document.querySelectorAll('[tyt-info-expander-placeholder]');
  3995. if (dmysOnPage.length === 1) {
  3996.  
  3997. const dmyElm = dmysOnPage[0];
  3998. const expander = elementMapper.get(dmyElm);
  3999. if (!expander) return;
  4000.  
  4001. for (const s of document.querySelectorAll('[tyt-info-expander-content]')) {
  4002. if (expander !== s) s.remove();
  4003. }
  4004. if (expander.isConnected === false) {
  4005. document.querySelector('#tab-info').appendChild(expander);
  4006. }
  4007.  
  4008. isContentDuplicationCheckAllow() && waitForContentReady.resolve();
  4009.  
  4010. }
  4011.  
  4012.  
  4013. }
  4014.  
  4015. function getWord(tag) {
  4016. return langWords[pageLang][tag] || langWords['en'][tag] || '';
  4017. }
  4018.  
  4019.  
  4020. function getTabsHTML() {
  4021.  
  4022. const sTabBtnVideos = `${svgElm(16, 16, 90, 90, svgVideos)}<span>${getWord('videos')}</span>`;
  4023. const sTabBtnInfo = `${svgElm(16, 16, 60, 60, svgInfo)}<span>${getWord('info')}</span>`;
  4024. const sTabBtnPlayList = `${svgElm(16, 16, 20, 20, svgPlayList)}<span>${getWord('playlist')}</span>`;
  4025.  
  4026. let str1 = `
  4027. <paper-ripple class="style-scope yt-icon-button">
  4028. <div id="background" class="style-scope paper-ripple" style="opacity:0;"></div>
  4029. <div id="waves" class="style-scope paper-ripple"></div>
  4030. </paper-ripple>
  4031. `;
  4032.  
  4033. let str_fbtns = `
  4034. <div class="font-size-right">
  4035. <div class="font-size-btn font-size-plus" tyt-di="8rdLQ">
  4036. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  4037. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  4038. <path d="M12 25H38M25 12V38"/>
  4039. </svg>
  4040. </div><div class="font-size-btn font-size-minus" tyt-di="8rdLQ">
  4041. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  4042. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  4043. <path d="M12 25h26"/>
  4044. </svg>
  4045. </div>
  4046. </div>
  4047. `.replace(/[\r\n]+/g, '');
  4048.  
  4049. const str_tabs = [
  4050. `<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>`,
  4051. `<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>`,
  4052. `<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>`,
  4053. `<a id="tab-btn5" tyt-di="q9Kjc" tyt-tab-content="#tab-list" class="tab-btn tab-btn-hidden">${sTabBtnPlayList}${str1}${str_fbtns}</a>`
  4054. ].join('');
  4055.  
  4056. let addHTML = `
  4057. <div id="right-tabs">
  4058. <tabview-view-pos-thead></tabview-view-pos-thead>
  4059. <header>
  4060. <div id="material-tabs">
  4061. ${str_tabs}
  4062. </div>
  4063. </header>
  4064. <div class="tab-content">
  4065. <div id="tab-info" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  4066. <div id="tab-comments" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  4067. <div id="tab-videos" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  4068. <div id="tab-list" class="tab-content-cld tab-content-hidden" tyt-hidden userscript-scrollbar-render></div>
  4069. </div>
  4070. </div>
  4071. `;
  4072.  
  4073. return addHTML;
  4074.  
  4075. }
  4076.  
  4077.  
  4078. function getLang() {
  4079.  
  4080. let lang = 'en';
  4081. let htmlLang = ((document || 0).documentElement || 0).lang || '';
  4082. switch (htmlLang) {
  4083. case 'en':
  4084. case 'en-GB':
  4085. lang = 'en';
  4086. break;
  4087. case 'de':
  4088. case 'de-DE':
  4089. lang = 'du';
  4090. break;
  4091. case 'fr':
  4092. case 'fr-CA':
  4093. case 'fr-FR':
  4094. lang = 'fr';
  4095. break;
  4096. case 'zh-Hant':
  4097. case 'zh-Hant-HK':
  4098. case 'zh-Hant-TW':
  4099. lang = 'tw';
  4100. break;
  4101. case 'zh-Hans':
  4102. case 'zh-Hans-CN':
  4103. lang = 'cn';
  4104. break;
  4105. case 'ja':
  4106. case 'ja-JP':
  4107. lang = 'jp';
  4108. break;
  4109. case 'ko':
  4110. case 'ko-KR':
  4111. lang = 'kr';
  4112. break;
  4113. case 'ru':
  4114. case 'ru-RU':
  4115. lang = 'ru';
  4116. break;
  4117. default:
  4118. lang = 'en';
  4119. }
  4120.  
  4121. return lang;
  4122.  
  4123. }
  4124.  
  4125. function getLangForPage() {
  4126.  
  4127. let lang = getLang();
  4128.  
  4129. if (langWords[lang]) pageLang = lang; else pageLang = 'en';
  4130.  
  4131. }
  4132.  
  4133. // function checkEvtTarget(evt, nodeNames) {
  4134. // return nodeNames.includes((((evt || 0).target || 0).nodeName || 0));
  4135. // }
  4136.  
  4137. function pageCheck() {
  4138. // yt-player-updated
  4139. // yt-page-data-updated
  4140. // [is-two-columns_] attr changed => layout changed
  4141.  
  4142. /** @type {HTMLElement | null} */
  4143. const ytdFlexyElm = es.ytdFlexy;
  4144. if (!scriptEnable || !ytdFlexyElm) return;
  4145.  
  4146. const rootDom = document.documentElement;
  4147. rootDom.setAttribute('sxmq8', rootDom.getAttribute('sxmq8') === '1' ? '0' : '1');
  4148.  
  4149. let comments = querySelectorFromAnchor.call(ytdFlexyElm, '#primary.ytd-watch-flexy ytd-watch-metadata ~ ytd-comments#comments');
  4150. if (comments) {
  4151. let tabComments = document.querySelector('#tab-comments');
  4152. if (tabComments) {
  4153. elementAppend.call(tabComments, comments);
  4154. }
  4155. }
  4156.  
  4157. mtf_append_playlist(null); // playlist relocated after layout changed
  4158.  
  4159. fixTabs();
  4160.  
  4161. mtf_autocomplete_search();
  4162.  
  4163. }
  4164.  
  4165. function globalHook(eventType, func) {
  4166. if (!func) return;
  4167.  
  4168. const count = (globalHook_hashs[eventType] || 0) + 1;
  4169.  
  4170. globalHook_hashs[eventType] = count;
  4171.  
  4172. const s = globalHook_symbols[count - 1] || (globalHook_symbols[count - 1] = Symbol());
  4173.  
  4174. document.addEventListener(eventType, function (evt) {
  4175. if (evt[s]) return;
  4176. evt[s] = true;
  4177. Promise.resolve().then(() => {
  4178. func(evt);
  4179. })
  4180.  
  4181. }, capturePassive)
  4182.  
  4183. }
  4184.  
  4185. async function makeHeaderFloat() {
  4186. if (isMakeHeaderFloatCalled) return;
  4187. isMakeHeaderFloatCalled = true;
  4188. await Promise.resolve(0);
  4189.  
  4190.  
  4191. const [header, headerP, navElm] = await Promise.all([
  4192. Promise.resolve().then(() => document.querySelector("#right-tabs header")),
  4193.  
  4194. Promise.resolve().then(() => document.querySelector("#right-tabs tabview-view-pos-thead")),
  4195.  
  4196. Promise.resolve().then(() => document.querySelector('#masthead-container, #masthead'))
  4197.  
  4198. ]);
  4199.  
  4200.  
  4201. let ito_dt = 0;
  4202. let ito = new IntersectionObserver((entries) => {
  4203.  
  4204. let xyStatus = null;
  4205.  
  4206. //console.log(entries);
  4207.  
  4208. let xRect = null;
  4209. let rRect = null;
  4210.  
  4211. for (const entry of entries) {
  4212. if (!entry.boundingClientRect || !entry.rootBounds) continue; // disconnected from DOM tree
  4213. if (!entry.isIntersecting && entry.boundingClientRect.y <= entry.rootBounds.top && entry.boundingClientRect.y < entry.rootBounds.bottom) {
  4214. xyStatus = 2;
  4215. xRect = entry.boundingClientRect;
  4216. rRect = entry.rootBounds;
  4217. } else if (entry.isIntersecting && entry.boundingClientRect.y >= entry.rootBounds.top && entry.boundingClientRect.y < entry.rootBounds.bottom) {
  4218. xyStatus = 1;
  4219. xRect = entry.boundingClientRect;
  4220. rRect = entry.rootBounds;
  4221. }
  4222. }
  4223. let p = wls.layoutStatus;
  4224. //console.log(document.documentElement.clientWidth)
  4225. if (xyStatus !== null) {
  4226.  
  4227. if (xyStatus === 2 && isStickyHeaderEnabled === true) {
  4228.  
  4229. } else if (xyStatus === 1 && isStickyHeaderEnabled === false) {
  4230.  
  4231. } else {
  4232. singleColumnScrolling2(xyStatus, xRect.width, {
  4233. left: xRect.left,
  4234. right: rRect.width - xRect.right
  4235. });
  4236. }
  4237.  
  4238. }
  4239.  
  4240. let tdt = Date.now();
  4241. ito_dt = tdt;
  4242. setTimeout(() => {
  4243. if (ito_dt !== tdt) return;
  4244. if (p !== wls.layoutStatus) singleColumnScrolling();
  4245. }, 300)
  4246.  
  4247. },
  4248. {
  4249. rootMargin: `0px 0px 0px 0px`,
  4250. threshold: [0]
  4251. })
  4252.  
  4253. ito.observe(headerP)
  4254.  
  4255. }
  4256.  
  4257. function setupVideoTitleHover(){
  4258. let h1 = document.querySelector('#below h1.ytd-watch-metadata yt-formatted-string');
  4259. if (h1) {
  4260.  
  4261.  
  4262. let s = '';
  4263.  
  4264. try {
  4265. if (formatDates && Object.keys(formatDates).length > 0) {
  4266.  
  4267. function getDurationInfo(bd1, bd2) {
  4268.  
  4269. let bdd = bd2 - bd1
  4270. let hrs = Math.floor(bdd / 3600000)
  4271. bdd = bdd - hrs * 3600000
  4272. let mins = Math.round(bdd / 60000)
  4273. let seconds = null
  4274. if (mins < 10 && hrs === 0) {
  4275. mins = Math.floor(bdd / 60000)
  4276. bdd = bdd - mins * 60000
  4277. seconds = Math.round(bdd / 1000)
  4278. if (seconds === 0) seconds = null
  4279. }
  4280.  
  4281. return { hrs, mins, seconds }
  4282.  
  4283. }
  4284.  
  4285. const formatDateResult = getFormatDateResultFunc();
  4286.  
  4287. if (formatDates.broadcastBeginAt && formatDates.isLiveNow === false) {
  4288.  
  4289. let bd1 = new KDate(formatDates.broadcastBeginAt)
  4290. let bd2 = formatDates.broadcastEndAt ? new KDate(formatDates.broadcastEndAt) : null
  4291.  
  4292. let isSameDay = 0
  4293. if (bd2 && bd1.toLocaleDateString() === bd2.toLocaleDateString()) {
  4294. isSameDay = 1
  4295.  
  4296. } else if (bd2 && +bd2 > +bd1 && bd2 - bd1 < 86400000) {
  4297.  
  4298. if (bd1.getHours() >= 6 && bd2.getHours() < 6) {
  4299. isSameDay = 2
  4300. }
  4301.  
  4302. }
  4303.  
  4304. let durationInfo = getDurationInfo(bd1, bd2)
  4305. if (isSameDay > 0) {
  4306.  
  4307. bd2.dayBack = (isSameDay === 2)
  4308.  
  4309. s = formatDateResult(0x200, { bd1, bd2, isSameDay, durationInfo, formatDates })
  4310.  
  4311. } else if (bd2 && isSameDay === 0) {
  4312.  
  4313. s = formatDateResult(0x210, { bd1, bd2, isSameDay, durationInfo, formatDates })
  4314.  
  4315. }
  4316.  
  4317.  
  4318. } else if (formatDates.broadcastBeginAt && formatDates.isLiveNow === true) {
  4319.  
  4320. let bd1 = new KDate(formatDates.broadcastBeginAt)
  4321.  
  4322. s = formatDateResult(0x300, { bd1, formatDates })
  4323.  
  4324. } else {
  4325. if (formatDates.uploadDate) {
  4326.  
  4327. if (formatDates.publishDate && formatDates.publishDate !== formatDates.uploadDate) {
  4328.  
  4329. s = formatDateResult(0x600, { formatDates })
  4330. } else {
  4331. s = formatDateResult(0x610, { formatDates })
  4332.  
  4333. }
  4334. } else if (!formatDates.uploadDate && formatDates.publishDate) {
  4335.  
  4336. s = formatDateResult(0x700, { formatDates })
  4337.  
  4338.  
  4339. }
  4340. }
  4341.  
  4342.  
  4343. }
  4344. } catch (e) {
  4345. s = '';
  4346. }
  4347.  
  4348. if (s) {
  4349. h1.setAttribute('data-title-details', s)
  4350. } else {
  4351. h1.removeAttribute('data-title-details')
  4352. }
  4353.  
  4354. }
  4355.  
  4356. }
  4357.  
  4358. const skPlayListDataReassign = ControllerID();
  4359.  
  4360. function checkPlaylistForInitialization() {
  4361. // if the page url is with playlist; renderer event might not occur.
  4362.  
  4363. // playlist already added to dom; this is to set the visibility event and change hidden status
  4364.  
  4365. let m_playlist = document.querySelector(`#tab-list ytd-playlist-panel-renderer#playlist:not([o3r-${sa_playlist}])`)
  4366.  
  4367. // once per {ytd-playlist-panel-renderer#playlist} detection
  4368.  
  4369. // _console.log(3902, !!m_playlist)
  4370.  
  4371. const ytdFlexyElm = es.ytdFlexy;
  4372. if (!scriptEnable || !ytdFlexyElm) { }
  4373. else if (m_playlist) {
  4374.  
  4375. if (mtoVisibility_Playlist.bindElement(m_playlist)) {
  4376. mtoVisibility_Playlist.observer.check(9); // delay check required for browser bug - hidden changed not triggered
  4377. }
  4378. let playlist_wr = mWeakRef(m_playlist);
  4379. scriptletDeferred.debounce(() => {
  4380. let m_playlist = kRef(playlist_wr);
  4381. playlist_wr = null;
  4382. if (m_playlist && m_playlist.isConnected === true) {
  4383. m_playlist.dispatchEvent(new CustomEvent("tabview-yt-data-reassign"));
  4384. }
  4385. m_playlist = null;
  4386. }, skPlayListDataReassign)
  4387. m_playlist = null;
  4388.  
  4389. }
  4390.  
  4391. FP.mtf_attrPlaylist();
  4392.  
  4393. Promise.resolve(0).then(() => {
  4394. // ['tab-btn', 'tab-btn', 'tab-btn active', 'tab-btn tab-btn-hidden']
  4395. // bug
  4396. const ytdFlexyElm = es.ytdFlexy;
  4397. if (!scriptEnable || !ytdFlexyElm) return;
  4398. if (!switchTabActivity_lastTab && (ytdFlexyElm.getAttribute('tyt-tab') + '').indexOf('#tab-') === 0 && location.pathname === '/watch') {
  4399. if (/[\?\&]list=[\w\-\_]+/.test(location.search)) {
  4400. if (setToActiveTab('#tab-list')) switchTabActivity_lastTab = '#tab-list';
  4401. } else if (/[\?\&]lc=[\w\-\_]+/.test(location.search)) {
  4402. if (setToActiveTab('#tab-comments')) switchTabActivity_lastTab = '#tab-comments';
  4403. }
  4404. }
  4405. })
  4406.  
  4407. }
  4408.  
  4409.  
  4410. const _pageBeingInit = function () {
  4411.  
  4412. psId(); // add one
  4413.  
  4414. fetchCounts = {
  4415. base: null,
  4416. new: null,
  4417. fetched: false,
  4418. count: null
  4419. }
  4420. pageFetchedDataVideoId = null;
  4421. chatroomDetails = null;
  4422. }
  4423.  
  4424. const pageBeingInit = function () {
  4425. // trigger at pageSeq1/2: yt-navigate-start / yt-navigate-cache / yt-navigate-redirect / yt-page-data-fetched
  4426.  
  4427. // call regardless pageType
  4428. // run once on / before pageSeq2 (yt-page-data-fetched)
  4429.  
  4430. const rootDom = document.documentElement;
  4431. // rootDom.setAttribute('sxmq7', rootDom.getAttribute('sxmq7') === '1' ? '0' : '1');
  4432. rootDom.setAttribute('sxmq8', rootDom.getAttribute('sxmq8') === '1' ? '0' : '1');
  4433. rootDom.removeAttribute('pnzgu');
  4434.  
  4435. infoContentDS = 0;
  4436. renderIdentifier(); // add 1
  4437. renderDeferred.reset(); // clear quene of pending renderDeferreds
  4438.  
  4439.  
  4440. if (!scriptletDeferred.resolved && (firstLoadStatus & 2) === 2) {
  4441. // insert on first pageBeingInit(), regardless pageType
  4442. firstLoadStatus -= 2;
  4443. script_inject_js1.inject();
  4444. } else if (pageRendered === 2) { // (pageRendered = 2 after pageSeq2)
  4445. // reset on 2nd+ pageBeingInit(), regardless pageType
  4446. pageRendered = 0;
  4447. let elmPL = document.querySelector('tabview-view-ploader');
  4448. if (elmPL) elmPL.remove();
  4449. // tabview-view-ploader is appended in pageBeingFetched (pageSeq2: yt-page-data-fetched)
  4450. }
  4451.  
  4452. if (tabsDeferred.resolved) {
  4453. comments_loader = 1;
  4454. tabsDeferred.reset(); // tabsDeferred.resolve() again in yt-navigate-finish[page=watch]
  4455. if ((firstLoadStatus & 8) === 0) {
  4456. innerDOMCommentsCountLoader(false); //ensure the previous record is saved
  4457. // no need to cache to the rendering state
  4458. _pageBeingInit();
  4459. }
  4460. // _console.log('pageBeingInit', firstLoadStatus)
  4461. }
  4462.  
  4463. };
  4464.  
  4465. function getFinalComments() {
  4466.  
  4467. comments_loader = 0;
  4468.  
  4469. let ei = 0;
  4470.  
  4471. function execute() {
  4472. //sync -> animateLoadDeferred.resolved always true
  4473.  
  4474. if (!renderDeferred.resolved) return;
  4475.  
  4476. // _console.log(2323)
  4477.  
  4478. if (Q.comments_section_loaded !== 0) return;
  4479. if (fetchCounts.fetched) return;
  4480.  
  4481.  
  4482. let ret = innerDOMCommentsCountLoader(true);
  4483.  
  4484. if (fetchCounts.new && !fetchCounts.fetched) {
  4485. if (fetchCounts.new.f()) {
  4486. fetchCounts.fetched = true;
  4487. fetchCommentsFinished();
  4488. // _console.log(9972, 'fetched = true')
  4489. }
  4490. return;
  4491. }
  4492.  
  4493.  
  4494. ei++;
  4495.  
  4496. if (fetchCounts.base && !fetchCounts.new && !fetchCounts.fetched && fetchCounts.count === 1) {
  4497.  
  4498.  
  4499. let elm = kRef(fetchCounts.base.elm);
  4500. let txt = elm ? getCountHText(elm) : null;
  4501. let condi1 = ei > 7;
  4502. let condi2 = txt === m_last_count;
  4503. if (condi1 || condi2) {
  4504.  
  4505. if (fetchCounts.base.f()) {
  4506. fetchCounts.fetched = true;
  4507. fetchCommentsFinished();
  4508. // _console.log(9972, 'fetched = true')
  4509. }
  4510.  
  4511. }
  4512.  
  4513. }
  4514.  
  4515. if (!fetchCounts.fetched) {
  4516. if (ei > 7) {
  4517. let elm = ret.length === 1 ? kRef(ret[0].elm) : null;
  4518. let txt = elm ? getCountHText(elm) : null;
  4519. if (elm && txt !== m_last_count) {
  4520. fetchCounts.base = null;
  4521. fetchCounts.new = ret[0];
  4522. fetchCounts.new.f();
  4523. fetchCounts.fetched = true;
  4524. // _console.log(9979, 'fetched = true')
  4525. fetchCommentsFinished();
  4526. }
  4527. return;
  4528. }
  4529. return true;
  4530. }
  4531.  
  4532. }
  4533.  
  4534.  
  4535. async function alCheckFn(ks) {
  4536.  
  4537. let alCheckCount = 9;
  4538. let alCheckInterval = 420;
  4539.  
  4540. do {
  4541.  
  4542. if (+renderIdentifier !== ks) break;
  4543. if (alCheckCount === 0) break;
  4544. if (execute() !== true) break;
  4545. --alCheckCount;
  4546.  
  4547. await new Promise(r => setTimeout(r, alCheckInterval));
  4548.  
  4549. } while (true)
  4550.  
  4551. }
  4552. let ks = +renderIdentifier;
  4553. renderDeferred.debounce(() => {
  4554. if (ks !== +renderIdentifier) return
  4555. if (mvideoState & 32) return;
  4556. mvideoState |= 32;
  4557. alCheckFn(ks);
  4558.  
  4559. });
  4560.  
  4561.  
  4562. }
  4563.  
  4564. const skIdInfoboxTooltipFix = ControllerID();
  4565.  
  4566. const { removeDuplicateInfoFn, setHiddenStateForDesc } = (() => {
  4567.  
  4568. let g_check_detail_A = 0;
  4569. let checkDuplicateRes = null;
  4570. function setHiddenStateForDesc() {
  4571. let ytdFlexyElm = es.ytdFlexy
  4572. if (!ytdFlexyElm) return
  4573. let hiddenBool = !document.fullscreenElement ? ytdFlexyElm.classList.contains('tabview-info-duplicated') : false
  4574. let elm
  4575. elm = document.querySelector('.tabview-info-duplicated-checked[flexy] ytd-text-inline-expander#description-inline-expander #plain-snippet-text')
  4576. if (elm) {
  4577. wAttr(elm, 'hidden', hiddenBool)
  4578. }
  4579. elm = document.querySelector('.tabview-info-duplicated-checked[flexy] ytd-text-inline-expander#description-inline-expander #formatted-snippet-text')
  4580. if (elm) {
  4581. wAttr(elm, 'hidden', hiddenBool)
  4582. }
  4583. }
  4584. function checkDuplicatedInfo_then(isCheck, checkDuplicateRes) {
  4585.  
  4586. const ytdFlexyElm = es.ytdFlexy;
  4587. if (!ytdFlexyElm) return; //unlikely
  4588.  
  4589. let cssbool_c1 = false, cssbool_c2 = false;
  4590. if (isCheck === 5) {
  4591.  
  4592. if (ytdFlexyElm.matches('.tabview-info-duplicated[flexy]')) {
  4593. cssbool_c1 = !!querySelectorFromAnchor.call(ytdFlexyElm, '#description.style-scope.ytd-watch-metadata > #description-inner:only-child');
  4594. cssbool_c2 = !!querySelectorFromAnchor.call(ytdFlexyElm, '#tab-info ytd-expander #description.ytd-video-secondary-info-renderer');
  4595. }
  4596.  
  4597. if (typeof checkDuplicateRes === 'boolean') {
  4598. setHiddenStateForDesc();
  4599. }
  4600. }
  4601.  
  4602. ytdFlexyElm.setAttribute('tyt-has', `${cssbool_c1 ? 'A' : 'a'}${cssbool_c2 ? 'B' : 'b'}`);
  4603.  
  4604. }
  4605.  
  4606. async function contentPairSet(firstElement, secondElement) {
  4607.  
  4608. // const firstElementSelector = "ytd-text-inline-expander#description-inline-expander";
  4609. // const secondElementSelector = "#tab-info ytd-expander #description";
  4610.  
  4611. // const firstElement = document.querySelector(firstElementSelector);
  4612. // const secondElement = document.querySelector(secondElementSelector);
  4613. if (firstElement && secondElement) {
  4614.  
  4615. // checked that e1 e2 shall be considered with matching pair
  4616. firstElement.setAttribute('tyt-du744', '');
  4617. secondElement.setAttribute('tyt-du744', '');
  4618. }
  4619.  
  4620. }
  4621.  
  4622. async function checkDuplicatedInfoAug2023() {
  4623. const firstElementSelector = "ytd-text-inline-expander#description-inline-expander";
  4624. const secondElementSelector = "#tab-info ytd-expander #description";
  4625. const firstElement = document.querySelector(firstElementSelector);
  4626. const secondElement = document.querySelector(secondElementSelector);
  4627.  
  4628. // dont detect the content change of main info box
  4629. // if second info box is checked okay before, skip
  4630. if (firstElement.hasAttribute('tyt-du744') || secondElement.hasAttribute('tyt-du744')) return true; // assume still ok as we checked before
  4631. if (!firstElement || !secondElement) return false;
  4632. if (firstElement.hasAttribute('hidden') || secondElement.hasAttribute('hidden')) return false;
  4633. const asyncGetContent = async (n) => {
  4634. return n.textContent;
  4635. }
  4636. const getTextContentArr = async (element) => {
  4637. let contentArray = [];
  4638. for (let currentNode = nodeFirstChild(element); currentNode; currentNode = nodeNextSibling(currentNode)) {
  4639. if (currentNode.nodeType === Node.ELEMENT_NODE) {
  4640. if (currentNode.nodeName === "STYLE") {
  4641. // <style is-scoped>
  4642. continue;
  4643. }
  4644. if (currentNode.getAttribute('role') === 'button') { // .role is not working in Firefox
  4645. // tp-yt-paper-button#expand-sizer
  4646. // currentNode.matches('#collapse[role="button"]:not([hidden])')
  4647. continue;
  4648. }
  4649. if (currentNode.hasAttribute("hidden")) {
  4650. continue;
  4651. }
  4652. if (currentNode.id === "snippet") {
  4653. let allHidden = true;
  4654. for (let child = nodeFirstChild(currentNode); child; child = nodeNextSibling(child)) {
  4655. if (child.nodeName === "STYLE") {
  4656. // <style is-scoped>
  4657. continue;
  4658. }
  4659. if (child.hasAttribute("hidden")) {
  4660. continue;
  4661. }
  4662. let trimmedTextContent = await asyncGetContent(child);
  4663. trimmedTextContent = trimmedTextContent.trim();
  4664. if (trimmedTextContent.length === 0) continue;
  4665. allHidden = false;
  4666. break;
  4667. }
  4668. if (allHidden) {
  4669. continue;
  4670. }
  4671. }
  4672. } else if (currentNode.nodeType === Node.TEXT_NODE) {
  4673. } else {
  4674. continue;
  4675. }
  4676. let trimmedTextContent = await asyncGetContent(currentNode);
  4677. trimmedTextContent = trimmedTextContent.trim();
  4678. if (trimmedTextContent.length > 0) {
  4679. trimmedTextContent = trimmedTextContent.replace(/\n[\n\x20]+\n/g, '\n\n');
  4680. // "白州大根\n \n チャンネル登録者数 698人\n \n \n\n\n 動画\n \n\n\n \n \n概要"
  4681. // "白州大根\n \n チャンネル登録者数 698人\n \n \n\n\n 動画\n \n \n概要"
  4682. contentArray.push(trimmedTextContent);
  4683. }
  4684. }
  4685. return contentArray;
  4686. };
  4687. const [firstElementTextArr, secondElementTextArr] = await Promise.all([getTextContentArr(firstElement), getTextContentArr(secondElement)]);
  4688. function isSubset(arr1, arr2) {
  4689. const set = new Set(arr2);
  4690. const r = arr1.every(item => set.has(item));
  4691. set.clear();
  4692. return r;
  4693. }
  4694.  
  4695. const result = isSubset(firstElementTextArr, secondElementTextArr);
  4696.  
  4697. if (result) {
  4698.  
  4699. contentPairSet(firstElement, secondElement);
  4700.  
  4701. }
  4702.  
  4703. return result;
  4704. }
  4705.  
  4706. async function checkDuplicatedInfo() {
  4707.  
  4708. const ytdFlexyElm = es.ytdFlexy;
  4709. if (!ytdFlexyElm) return; //unlikely
  4710.  
  4711. const targetDuplicatedInfoPanel = document.querySelector('ytd-text-inline-expander#description-inline-expander:not([hidden])');
  4712. if (targetDuplicatedInfoPanel && !closestDOM.call(targetDuplicatedInfoPanel, '[hidden]')) { } else {
  4713. return; // the layout is not required to have this checking.
  4714. }
  4715.  
  4716. let t = Date.now();
  4717. g_check_detail_A = t;
  4718.  
  4719. ytdFlexyElm.classList.toggle('tabview-info-duplicated', true) // hide first;
  4720. let infoDuplicated = false;
  4721.  
  4722. try {
  4723. await new Promise(resolve => setTimeout(resolve, 1)); // mcrcr might be not yet initalized
  4724.  
  4725.  
  4726. if (g_check_detail_A !== t) return;
  4727.  
  4728.  
  4729. let clicked = false;
  4730. await Promise.all([...document.querySelectorAll('ytd-text-inline-expander#description-inline-expander #expand[role="button"]:not([hidden])')].map(button => {
  4731. return Promise.resolve().then(() => {
  4732. button.click();
  4733. clicked = true;
  4734. });
  4735. }));
  4736.  
  4737. await Promise.resolve(0);
  4738.  
  4739. infoDuplicated = await checkDuplicatedInfoAug2023();
  4740.  
  4741. if (infoDuplicated === false && clicked) {
  4742.  
  4743. await Promise.all([...document.querySelectorAll('ytd-text-inline-expander#description-inline-expander #collapse[role="button"]:not([hidden])')].map(button => {
  4744. return Promise.resolve().then(() => {
  4745. button.click();
  4746. });
  4747. }));
  4748.  
  4749. }
  4750.  
  4751. } catch (e) {
  4752.  
  4753. ytdFlexyElm.classList.toggle('tabview-info-duplicated', false) // error => unhide
  4754. }
  4755.  
  4756. console.debug('[tyt] Have any details with duplicated information been found?', (infoDuplicated ? 'Yes' : 'No'));
  4757. if (g_check_detail_A !== t) return;
  4758.  
  4759. //ytdFlexyElm.classList.toggle('tabview-info-duplicated', infoDuplicated)
  4760. checkDuplicateRes = infoDuplicated;
  4761.  
  4762. return 5; // other than 5, duplicated check = false
  4763.  
  4764. };
  4765.  
  4766. const removeDuplicateInfoFn = () => {
  4767.  
  4768. checkDuplicateRes = null;
  4769. async function alCheckFn(ks) {
  4770.  
  4771. let alCheckCount = 4;
  4772. let alCheckInterval = 270;
  4773.  
  4774. checkDuplicateRes = null;
  4775. let descExpandState = null;
  4776. const descToggleBtnSelector = '#collapse[role="button"]:not([hidden]), #expand[role="button"]:not([hidden])';
  4777. const descMetaExpander = closestDOMX(document.querySelector('ytd-watch-metadata ytd-text-inline-expander#description-inline-expander'), 'ytd-watch-metadata');
  4778. 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
  4779. const descToggleBtnA = querySelectorFromAnchorX(descMetaLines, descToggleBtnSelector);
  4780.  
  4781. if (descToggleBtnA) {
  4782. if (descMetaExpander.hasAttribute('description-collapsed') && descToggleBtnA.id === 'expand') {
  4783. descExpandState = false;
  4784. } else if (!descMetaExpander.hasAttribute('description-collapsed') && descToggleBtnA.id === 'collapse') {
  4785. descExpandState = true;
  4786. }
  4787. }
  4788. if (descMetaExpander) {
  4789. descMetaExpander.classList.add('tyt-tmp-hide-metainfo');
  4790. }
  4791.  
  4792. try {
  4793.  
  4794. do {
  4795. // await removeOldExpanders();
  4796. // await removeContentMismatch();
  4797. await getRAFPromise().then();
  4798.  
  4799. if (+renderIdentifier !== ks) break;
  4800. if (alCheckCount === 0) break;
  4801. if (checkDuplicateRes === true) break;
  4802. checkDuplicateRes = null;
  4803.  
  4804. let res = await checkDuplicatedInfo(); //async
  4805. if (res === 5) {
  4806.  
  4807. const ytdFlexyElm = es.ytdFlexy;
  4808. if (ytdFlexyElm) {
  4809. if (checkDuplicateRes === true || (checkDuplicateRes === false && alCheckCount === 1)) {
  4810. ytdFlexyElm.classList.toggle('tabview-info-duplicated', checkDuplicateRes)
  4811. ytdFlexyElm.classList.toggle('tabview-info-duplicated-checked', true)
  4812. checkDuplicatedInfo_then(res, checkDuplicateRes);
  4813. scriptletDeferred.debounce(() => {
  4814. document.dispatchEvent(new CustomEvent('tabview-fix-info-box-tooltip'));
  4815. }, skIdInfoboxTooltipFix);
  4816. }
  4817. }
  4818.  
  4819. }
  4820. --alCheckCount;
  4821.  
  4822. if (checkDuplicateRes === true) break;
  4823.  
  4824. await new Promise(r => setTimeout(r, alCheckInterval));
  4825.  
  4826. } while (true)
  4827.  
  4828. await Promise.resolve(0)
  4829.  
  4830. const descToggleBtnB = typeof descExpandState === 'boolean' ? querySelectorFromAnchorX(descMetaLines, descToggleBtnSelector) : null;
  4831. if (descToggleBtnB) {
  4832.  
  4833. const isCollapsed = descMetaExpander.hasAttribute('description-collapsed');
  4834. const id = descToggleBtnB.id;
  4835. const b = descExpandState ? (isCollapsed && id === 'expand') : (!isCollapsed && id === 'collapse');
  4836.  
  4837. if (b) {
  4838. descToggleBtnB.click();
  4839. }
  4840.  
  4841. }
  4842.  
  4843.  
  4844.  
  4845.  
  4846. } catch (e) {
  4847.  
  4848. console.warn(e)
  4849.  
  4850. }
  4851.  
  4852. if (descMetaExpander) {
  4853. descMetaExpander.classList.remove('tyt-tmp-hide-metainfo');
  4854.  
  4855. await Promise.resolve(0)
  4856.  
  4857. const detailsIntersectioner = querySelectorFromAnchor.call(descMetaExpander, '#info-container.style-scope.ytd-watch-metadata');
  4858. if (detailsIntersectioner) {
  4859. Promise.resolve(detailsIntersectioner).then(dom => {
  4860. if (dom) mtoObservationDetails.bindElement(dom);
  4861. })
  4862. }
  4863.  
  4864. }
  4865.  
  4866.  
  4867.  
  4868. }
  4869. let ks = +renderIdentifier;
  4870. renderDeferred.debounce(() => {
  4871. if (ks !== +renderIdentifier) return
  4872. if (document.fullscreenElement) return;
  4873. if (mvideoState & 1) return;
  4874. mvideoState |= 1;
  4875. alCheckFn(ks);
  4876.  
  4877. });
  4878. }
  4879.  
  4880. return { removeDuplicateInfoFn, setHiddenStateForDesc };
  4881.  
  4882. })();
  4883.  
  4884. async function deferredDuplicatedMetaCheckerFn() {
  4885.  
  4886. await scriptletDeferred.d();
  4887.  
  4888. if (REMOVE_DUPLICATE_META_RECOMMENDATION) {
  4889.  
  4890. checkDuplicatedMetaRecommendation();
  4891.  
  4892. }
  4893.  
  4894.  
  4895. waitForContentReady = new PromiseExternal();
  4896.  
  4897. isContentDuplicationCheckAllow() ? waitForContentReady.resolve() : (await waitForContentReady.then());
  4898. await removeContentMismatch(); // play safe
  4899.  
  4900. removeDuplicateInfoFn();
  4901.  
  4902. }
  4903.  
  4904.  
  4905. // setupChatFrameDOM (v1) - removed in 2023.07.06 since it is buggy for page changing. subject to further review
  4906. function setupChatFrameDOM(node) {
  4907. // this function calls 3 times per each new video page
  4908.  
  4909. // 'tyt-chat' is initialized in setupChatFrameDisplayState1()
  4910.  
  4911. if (!chatroomDetails) return;
  4912. let liveChatFrame = node || document.querySelector('ytd-live-chat-frame#chat')
  4913. if (liveChatFrame) {
  4914.  
  4915. // every per [new] {ytd-live-chat-frame#chat} detection - reset after mini-playview
  4916.  
  4917. let ytdFlexyElm = es.ytdFlexy;
  4918. if (scriptEnable && ytdFlexyElm) {
  4919. if (mtoVisibility_Chatroom.bindElement(liveChatFrame)) {
  4920. mtoVisibility_Chatroom.observer.check(9)
  4921. }
  4922. }
  4923.  
  4924. liveChatFrame = null;
  4925. ytdFlexyElm = null;
  4926.  
  4927. setToggleBtnTxt(); // immediate update when page changed
  4928.  
  4929. if (node !== null) {
  4930. // button might not yet be rendered
  4931. getRAFPromise().then(setToggleBtnTxt); // bool = true must be front page
  4932. } else {
  4933.  
  4934. // this is due to page change
  4935. layoutStatusMutex.lockWith(unlock => {
  4936. if (!document.fullscreenElement) fixTheaterChat1A();
  4937. setTimeout(unlock, 17);
  4938. });
  4939.  
  4940. }
  4941.  
  4942. }
  4943.  
  4944. }
  4945.  
  4946. function whenEngagemenetPanelVisible() {
  4947.  
  4948. const layoutStatus = wls.layoutStatus;
  4949. if ((layoutStatus & (LAYOUT_TWO_COLUMNS | LAYOUT_THEATER)) === LAYOUT_TWO_COLUMNS) {
  4950.  
  4951. if (layoutStatus & LAYOUT_TAB_EXPANDED) {
  4952. switchTabActivity(null);
  4953. return true;
  4954. } else if (layoutStatus & LAYOUT_CHATROOM_EXPANDED) {
  4955. ytBtnCollapseChat();
  4956. return true;
  4957. }
  4958.  
  4959. }
  4960.  
  4961. return false;
  4962.  
  4963. }
  4964.  
  4965.  
  4966. function removeFocusOnLeave(evt) {
  4967. let node = (evt || 0).target || 0
  4968. let activeElement = document.activeElement || 0
  4969. if (node.nodeType === 1 && activeElement.nodeType === 1) {
  4970. Promise.resolve().then(() => {
  4971. if (node.contains(activeElement)) {
  4972. activeElement.blur();
  4973. }
  4974. })
  4975. }
  4976. }
  4977.  
  4978. async function setupVideo(node) {
  4979. // this can be fired even in background without tabs rendered
  4980. const attrKey = 'gM7Cp'
  4981. let video = querySelectorFromAnchor.call(node, `#movie_player video[src]:not([${attrKey}])`);
  4982. if (video) {
  4983. video.setAttribute(attrKey, '')
  4984.  
  4985. video.addEventListener('timeupdate', (evt) => {
  4986. energizedByVideoTimeUpdate();
  4987. }, bubblePassive);
  4988.  
  4989. video.addEventListener('ended', (evt) => {
  4990. // scrollIntoView => auto start next video
  4991. // otherwise it cannot auto paly next
  4992. if (pageType === 'watch') {
  4993. let elm = evt.target;
  4994. Promise.resolve(elm).then((elm) => {
  4995. if (pageType === 'watch') {
  4996. let scrollElm = closestDOM.call(elm, '#player') || closestDOM.call(elm, '#ytd-player') || elm;
  4997. // background applicable
  4998. scrollElm.scrollIntoView(false);
  4999. scrollElm = null
  5000. }
  5001. elm = null
  5002. });
  5003. }
  5004.  
  5005. }, bubblePassive)
  5006.  
  5007. }
  5008. }
  5009.  
  5010.  
  5011. globalHook('yt-player-updated', (evt) => {
  5012.  
  5013. const node = ((evt || 0).target) || 0
  5014.  
  5015. if (node.nodeType !== 1) return;
  5016.  
  5017. const nodeName = node.nodeName.toUpperCase();
  5018.  
  5019. // _console.log(evt.target.nodeName, 904, evt.type);
  5020.  
  5021. if (nodeName !== 'YTD-PLAYER') return
  5022.  
  5023. setupVideo(node)
  5024.  
  5025. discardableFn(()=>{ // might discarded since it runs earlier than tabs insertion
  5026.  
  5027. if (!scriptEnable) return
  5028.  
  5029. checkAndMakeNewCommentFetch();
  5030. pageCheck();
  5031.  
  5032. domInit_comments();
  5033. setupChatFrameDOM(null);
  5034.  
  5035. });
  5036.  
  5037.  
  5038. });
  5039.  
  5040. const appendExpander = () => {
  5041.  
  5042. const rid = `${+renderIdentifier}`; // string type integer id
  5043.  
  5044. const targets = document.querySelectorAll(`[bsptu="${rid}"]`); // ignore all appearance in previous paging
  5045. if (!targets.length) return;
  5046. for (const target of targets) {
  5047. // expect only one node; other measures for more than one node
  5048.  
  5049. const nodeName = target.nodeName.toLowerCase();
  5050.  
  5051. let dummy = nodeName === 'yt-dummy-532' ? target : null;
  5052. let expander0 = dummy ? elementMapper.get(dummy) : null;
  5053. if (expander0 && closestDOM.call(expander0, '#tab-info')) continue;
  5054. const expander = expander0 || (nodeName === 'ytd-expander' ? target : null);
  5055. if (expander) {
  5056.  
  5057. // once per $$native-info-description$$ {#meta-contents ytd-expander} detection
  5058. // append the detailed meta contents to the tab-info
  5059.  
  5060. const tabInfo = document.querySelector("#tab-info");
  5061. if (tabInfo) {
  5062.  
  5063. if (!expander.hasAttribute('tyt-info-expander-content')) {
  5064. expander.setAttribute('tyt-info-expander-content', '');
  5065. const dmy = document.createElement('yt-dummy-532'); // to detemine the content change by youtube engine
  5066. dmy.setAttribute('tyt-info-expander-placeholder', '');
  5067. expander.replaceWith(dmy);
  5068. elementMapper.set(expander, dmy); // interlink
  5069. elementMapper.set(dmy, expander); // interlink
  5070.  
  5071. const parentRoot = closestDOM.call(dmy, '[hidden]'); // only detect if the traditional block is hidden
  5072. if (parentRoot) {
  5073. moInfoContent.observe(parentRoot.parentNode, { subtree: true, childList: true });
  5074. }
  5075.  
  5076. }
  5077. elementAppend.call(tabInfo, expander);
  5078. }
  5079.  
  5080.  
  5081.  
  5082.  
  5083. removeContentMismatch();
  5084.  
  5085.  
  5086. }
  5087.  
  5088.  
  5089. }
  5090. }
  5091.  
  5092. let infoContentDS = 0;
  5093.  
  5094.  
  5095. const infoContentForTab = () => {
  5096.  
  5097. if (mvideoState & 2) return;
  5098. mvideoState |= 2;
  5099.  
  5100. document.documentElement.removeAttribute('pnzgu'); // just in case
  5101. appendExpander();
  5102. if (REMOVE_DUPLICATE_META_RECOMMENDATION) checkDuplicatedMetaRecommendation();
  5103.  
  5104. mtf_fix_details().then(() => {
  5105. setToggleInfo();
  5106. renderDeferred.debounce(() => {
  5107. if (mvideoState & 8) return;
  5108. mvideoState |= 8;
  5109. setTimeout(() => {
  5110. //dispatchWindowResize(); //try to omit
  5111. dispatchWindowResize(); //add once for safe
  5112. manualResizeT();
  5113. }, 420)
  5114. }, renderIdentifier)
  5115.  
  5116.  
  5117. let secondary = document.querySelector('#columns.ytd-watch-flexy #secondary.ytd-watch-flexy');
  5118.  
  5119. let columns = closestDOMX(secondary, '#columns.ytd-watch-flexy');
  5120.  
  5121. setupHoverSlider(secondary, columns)
  5122.  
  5123. let tabInfo = document.querySelector('#tab-info');
  5124. addTabExpander(tabInfo);
  5125.  
  5126. let tabComments = document.querySelector('#tab-comments');
  5127. addTabExpander(tabComments);
  5128.  
  5129.  
  5130. document.documentElement.setAttribute('pnzgu', '');
  5131.  
  5132. }).catch(console.warn);
  5133.  
  5134.  
  5135.  
  5136. }
  5137.  
  5138.  
  5139. function tabviewControllerFn(controllerId, val) {
  5140. val = +val;
  5141. if (val > -1 && val >= 0) {
  5142. if (controllerId === 'tabviewTabsHideController') {
  5143. hiddenTabsByUserCSS = val;
  5144.  
  5145. let btn;
  5146. btn = document.querySelector('[tyt-tab-content="#tab-info"]')
  5147. if (btn) btn.classList.toggle('tab-btn-hidden', ((hiddenTabsByUserCSS & 1) === 1));
  5148.  
  5149. btn = document.querySelector('[tyt-tab-content="#tab-comments"]')
  5150. if (btn) {
  5151. if ((hiddenTabsByUserCSS & 2) === 2) {
  5152. btn.classList.toggle('tab-btn-hidden', true);
  5153. } else {
  5154. btn.classList.toggle('tab-btn-hidden', isCommentsTabBtnHidden);
  5155. }
  5156. }
  5157. btn = document.querySelector('[tyt-tab-content="#tab-videos"]');
  5158. if (btn) btn.classList.toggle('tab-btn-hidden', ((hiddenTabsByUserCSS & 4) === 4));
  5159.  
  5160. let activeHiddenBtn = document.querySelector('[tyt-tab-content^="#"].active.tab-btn-hidden');
  5161. if (activeHiddenBtn) {
  5162. setToActiveTab();
  5163. }
  5164.  
  5165. } else if (controllerId === 'tabviewDefaultTabController') {
  5166. defaultTabByUserCSS = val;
  5167. if (setupDefaultTabBtnSetting) setupDefaultTabBtnSetting();
  5168. }
  5169. }
  5170. }
  5171.  
  5172.  
  5173. /** @type {Map<string, Function>} */
  5174. let handleDOMAppearFN = new Map();
  5175. function handleDOMAppear( /** @type {string} */ fn, /** @type { listener: (this: Document, ev: AnimationEvent ) => any } */ func) {
  5176. if (handleDOMAppearFN.size === 0) {
  5177. document.addEventListener('animationstart', (evt) => {
  5178. const animationName = evt.animationName;
  5179. if (!animationName) return;
  5180. let idx = -1;
  5181. let func = handleDOMAppearFN.get(animationName);
  5182. if (func) func(evt);
  5183. else {
  5184. let idx = animationName.indexOf('Controller-');
  5185. if (idx > 0) {
  5186. let j = idx + 'Controller'.length;
  5187. tabviewControllerFn(animationName.substring(0, j), animationName.substring(j + 1));
  5188. }
  5189. }
  5190. }, capturePassive)
  5191. } else {
  5192. if (handleDOMAppearFN.has(fn)) return;
  5193. }
  5194. handleDOMAppearFN.set(fn, func);
  5195. }
  5196.  
  5197.  
  5198.  
  5199. const moInfoContent = new MutationObserver(()=>{
  5200.  
  5201. removeContentMismatch();
  5202. });
  5203. function ytMicroEventsInit() {
  5204.  
  5205. // _console.log(902);
  5206.  
  5207. handleDOMAppear('videosDOMAppended', function (evt) {
  5208. videosDeferred.resolve();
  5209. })
  5210.  
  5211. handleDOMAppear('liveChatFrameDOMAppended', (evt) => {
  5212. // $$ html[tyt-deferred] ytd-live-chat-frame#chat $$
  5213.  
  5214. let node = evt.target;
  5215. if (node) setupChatFrameDOM(node); // front page
  5216.  
  5217. });
  5218.  
  5219. const skIdPageRenderedEventDispatch = ControllerID();
  5220.  
  5221. handleDOMAppear('pageLoaderAnimation', (evt) => {
  5222.  
  5223. pageRendered = 2;
  5224. renderDeferred.resolve();
  5225. console.debug('[tyt] pageRendered');
  5226.  
  5227. scriptletDeferred.debounce(() => {
  5228. document.dispatchEvent(new CustomEvent('tabview-page-rendered'));
  5229. setTimeout(() => {
  5230. document.dispatchEvent(new CustomEvent("yt-watch-comments-ready")); // immediately render comments when tab is switched from background
  5231. }, 80);
  5232. }, skIdPageRenderedEventDispatch);
  5233.  
  5234. });
  5235.  
  5236.  
  5237.  
  5238. const metaContentSetup = () => {
  5239. setupVideoTitleHover();
  5240. let ks = +renderIdentifier;
  5241. scriptletDeferred.debounce(()=>{
  5242. if(ks === +renderIdentifier) infoContentForTab();
  5243. });
  5244. };
  5245.  
  5246. const wmId1 = ControllerID();
  5247. const wmHandler1 = (evt) => {
  5248. renderDeferred.debounce(() => {
  5249. infoContentDS |= 1;
  5250. if (infoContentDS === 3) {
  5251. infoContentDS |= 4;
  5252. Promise.resolve().then(metaContentSetup);
  5253. }
  5254. }, wmId1);
  5255. }
  5256. handleDOMAppear('watchMetaFrameReady1', wmHandler1);
  5257. handleDOMAppear('watchMetaFrameReady2', wmHandler1);
  5258.  
  5259. const wmId2 = ControllerID();
  5260. const wmHandler2 = (evt) => {
  5261. const target = evt.target;
  5262. renderDeferred.debounce(() => {
  5263. infoContentDS |= 2;
  5264. target.isConnected && target.setAttribute('bsptu', +renderIdentifier);
  5265. if (infoContentDS === 3) {
  5266. infoContentDS |= 4;
  5267. Promise.resolve().then(metaContentSetup);
  5268. }
  5269. }, wmId2);
  5270. }
  5271. handleDOMAppear('watchMetaContentReady1', wmHandler2);
  5272. handleDOMAppear('watchMetaContentReady2', wmHandler2);
  5273.  
  5274. handleDOMAppear('fixInvisibleInfoBug', (evt) => evt.target.removeAttribute('hidden'));
  5275.  
  5276.  
  5277. handleDOMAppear('commentsHeaderAppended1', onCommentsReady);
  5278. handleDOMAppear('commentsHeaderAppended2', onCommentsReady);
  5279.  
  5280. handleDOMAppear('fixPlaylistLocation1', (evt)=>{ // used as a fallback to play safe. overall strategy to be reviewed
  5281.  
  5282. const n = evt.target;
  5283. if (closestDOM.call(n, '#tab-list')) return;
  5284.  
  5285. mtf_append_playlist(n); // the true playlist is appended to the #tab-list
  5286. checkPlaylistForInitialization();
  5287.  
  5288. });
  5289.  
  5290. const onChatFrameToggleBtnAppended = (evt) => {
  5291. // $$ html[tyt-deferred] ytd-live-chat-frame#chat>.ytd-live-chat-frame#show-hide-button $$
  5292. // $$ except html[tyt-deferred] ytd-live-chat-frame#chat>.ytd-live-chat-frame#show-hide-button:first-child $$
  5293.  
  5294. const button = evt.target;
  5295.  
  5296. if (!button || button.nodeType !== 1) return;
  5297.  
  5298. /** @type {HTMLElement | null} */
  5299. const ytdFlexyElm = es.ytdFlexy;
  5300. if (!scriptEnable || !ytdFlexyElm) return;
  5301.  
  5302. prependTo(button, nodeParent(button));
  5303.  
  5304. };
  5305.  
  5306. handleDOMAppear('chatFrameToggleBtnAppended1', onChatFrameToggleBtnAppended);
  5307. handleDOMAppear('chatFrameToggleBtnAppended2', onChatFrameToggleBtnAppended);
  5308.  
  5309.  
  5310. handleDOMAppear('epDOMAppended', async (evt) => {
  5311. try {
  5312. let node = evt.target;
  5313.  
  5314. 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])')
  5315.  
  5316. if (eps && eps.length > 0) {
  5317.  
  5318. if (eps.length > 1) {
  5319. let p = 0;
  5320. for (const ep of eps) {
  5321. if (ep !== node) {
  5322. ytBtnCloseEngagementPanel(ep)
  5323. p++
  5324. }
  5325. }
  5326. if (p > 0) {
  5327. await Promise.resolve(0)
  5328. }
  5329. }
  5330.  
  5331. FP.mtf_attrEngagementPanel(9, node);
  5332.  
  5333. Promise.resolve().then(() => {
  5334.  
  5335. mtoVisibility_EngagementPanel.bindElement(node, {
  5336. attributes: true,
  5337. attributeFilter: ['visibility'],
  5338. attributeOldValue: true
  5339. })
  5340.  
  5341. node.removeEventListener('mouseleave', removeFocusOnLeave, false)
  5342. node.addEventListener('mouseleave', removeFocusOnLeave, false)
  5343.  
  5344. })
  5345.  
  5346. }
  5347.  
  5348.  
  5349. } catch (e) { }
  5350.  
  5351. })
  5352.  
  5353. handleDOMAppear('playlistRowDOMSelected', (evt) => {
  5354. if (!evt) return;
  5355. let target = evt.target;
  5356. if (!target) return;
  5357. let items = nodeParent(target);
  5358. if (!items || items.id !== 'items') return;
  5359. let m = /\/watch\?v=[^\&]+\&/.exec(location.href || '')
  5360. if (!m) return;
  5361. let s = m[0] + "";
  5362. if (!s || s.length <= 10) return;
  5363. let correctAnchor = querySelectorFromAnchor.call(items, `ytd-playlist-panel-video-renderer a[href*="${s}"]`);
  5364. if (!correctAnchor || target.contains(correctAnchor)) return;
  5365. let correctRow = closestDOM.call(correctAnchor, 'ytd-playlist-panel-video-renderer');
  5366. if (!correctRow) return;
  5367. target.removeAttribute('selected');
  5368. correctRow.setAttribute('selected', '');
  5369. });
  5370.  
  5371. let _tabviewSiderAnimated = false;
  5372.  
  5373. handleDOMAppear('tabviewSiderAnimation', (evt) => {
  5374. if (!_tabviewSiderAnimated) {
  5375. _tabviewSiderAnimated = true;
  5376. dispatchCommentRowResize();
  5377. }
  5378. })
  5379.  
  5380. handleDOMAppear('tabviewSiderAnimationNone', (evt) => {
  5381. if (_tabviewSiderAnimated) {
  5382. _tabviewSiderAnimated = false;
  5383. dispatchCommentRowResize();
  5384. }
  5385. })
  5386.  
  5387. handleDOMAppear('SearchWhileWatchAutocomplete', (evt) => { // Youtube - Search While Watching Video
  5388. let elm = evt.target;
  5389. if(elm.hasAttribute('tyt-found')) return;
  5390. elm.setAttribute('tyt-found', '');
  5391. let container = document.createElement('div');
  5392. container.id = 'suggestions-search-container';
  5393. elm.replaceWith(container);
  5394. container.appendChild(elm);
  5395. elm.addEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false);
  5396. scriptletDeferred.debounce(() => {
  5397. elm.isConnected && elm.dispatchEvent(new CustomEvent('tabview-fix-autocomplete'));
  5398. elm = null;
  5399. });
  5400. })
  5401.  
  5402. handleDOMAppear('oldYtIconPinAppeared', (evt) => {
  5403. /* added in May 2023 - 2023.05.19 */
  5404.  
  5405. /*
  5406. from
  5407. <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>
  5408.  
  5409. to
  5410. <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>
  5411.  
  5412. */
  5413.  
  5414. let svg = evt.target;
  5415. let p = document.createElement('template');
  5416. 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>';
  5417. svg.replaceWith(p.content.firstChild);
  5418.  
  5419.  
  5420. })
  5421.  
  5422.  
  5423. globalHook('yt-rendererstamper-finished', (evt) => {
  5424.  
  5425. if (!scriptEnable && tabsDeferred.resolved) { return }
  5426. // might occur before initialization
  5427.  
  5428. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5429.  
  5430. let node = evt.target;
  5431. const nodeName = node.nodeName.toUpperCase();
  5432.  
  5433. if (nodeName === 'YTD-PLAYLIST-PANEL-RENDERER' || nodeName === 'YTD-COMMENTS-HEADER-RENDERER') {
  5434.  
  5435. discardableFn(() => {
  5436.  
  5437. const n = node;
  5438. node = null;
  5439.  
  5440. if (nodeName === 'YTD-PLAYLIST-PANEL-RENDERER') {
  5441. mtf_append_playlist(n); // the true playlist is appended to the #tab-list
  5442. checkPlaylistForInitialization();
  5443. } else if (nodeName === 'YTD-COMMENTS-HEADER-RENDERER') {
  5444. if ((comments_loader & 3) === 3) getFinalComments();
  5445. }
  5446.  
  5447. });
  5448.  
  5449. }
  5450.  
  5451.  
  5452. });
  5453.  
  5454. if (REMOVE_DUPLICATE_INFO) {
  5455.  
  5456. handleDOMAppear('deferredDuplicatedMetaChecker', () => {
  5457.  
  5458. deferredDuplicatedMetaCheckerFn();
  5459.  
  5460. });
  5461.  
  5462. }
  5463.  
  5464. globalHook('yt-page-data-updated', (evt) => {
  5465.  
  5466. // if (!scriptEnable && tabsDeferred.resolved) { return }
  5467. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5468.  
  5469. discardableFn(() => { // might discard if yt-navigate-finish not yet called
  5470. // if the page is navigated by history back-and-forth, not all engagement panels can be catched in rendering event.
  5471.  
  5472. if (!scriptEnable) return;
  5473.  
  5474. checkAndMakeNewCommentFetch();
  5475. pageCheck();
  5476. setupChatFrameDOM(null);
  5477. checkPlaylistForInitialization();
  5478.  
  5479. });
  5480.  
  5481. });
  5482.  
  5483.  
  5484.  
  5485. async function onWatchCommentsReady(b) {
  5486. await tabsInsertedPromise.then();
  5487. await scriptletDeferred.d();
  5488. checkAndMakeNewCommentFetch();
  5489.  
  5490. if (b) {
  5491. domInit_comments();
  5492. _onCommentsReady();
  5493. }
  5494.  
  5495. }
  5496.  
  5497. globalHook('yt-watch-comments-ready', (evt) => {
  5498.  
  5499. if (!scriptEnable && tabsDeferred.resolved) { return }
  5500. if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5501.  
  5502. const nodeName = evt.target.nodeName.toUpperCase()
  5503.  
  5504. comments_loader = comments_loader | 2;
  5505.  
  5506. onWatchCommentsReady(nodeName === 'YTD-WATCH-FLEXY');
  5507.  
  5508. });
  5509.  
  5510.  
  5511. window.addEventListener("message", (evt) => {
  5512. if (!scriptEnable && tabsDeferred.resolved) { return }
  5513. if (evt.origin === location.origin && evt.data.tabview) {
  5514. let data = evt.data.tabview;
  5515. if (data.eventType === "yt-page-type-changed") {
  5516. let detail = data.eventDetail
  5517. let { newPageType, oldPageType } = detail;
  5518. if (newPageType && oldPageType) {
  5519. let bool = false;
  5520. if (newPageType == 'ytd-watch-flexy') {
  5521. bool = true;
  5522. pageType = 'watch';
  5523. } else if (newPageType == 'ytd-browse') {
  5524. pageType = 'browse';
  5525. }
  5526. document.documentElement.classList.toggle('tabview-normal-player', bool)
  5527. }
  5528. }
  5529. }
  5530. }, bubblePassive);
  5531.  
  5532. const skIdFixPopupRefit = ControllerID();
  5533.  
  5534. globalHook('data-changed', (evt) => {
  5535.  
  5536. if (!scriptEnable && tabsDeferred.resolved) { return }
  5537.  
  5538. let nodeName = (((evt || 0).target || 0).nodeName || '').toUpperCase()
  5539.  
  5540. if (nodeName !== 'YTD-THUMBNAIL-OVERLAY-TOGGLE-BUTTON-RENDERER') return;
  5541.  
  5542. scriptletDeferred.debounce(() => {
  5543. document.dispatchEvent(new CustomEvent("tabview-fix-popup-refit"));
  5544. }, skIdFixPopupRefit);
  5545.  
  5546. });
  5547.  
  5548.  
  5549. // DEBUG_LOG && globalHook('yt-rendererstamper-finished', (evt) => {
  5550.  
  5551. // if (!scriptEnable && tabsDeferred.resolved) { return }
  5552. // // might occur before initialization
  5553.  
  5554. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5555.  
  5556. // const nodeName = evt.target.nodeName.toUpperCase();
  5557.  
  5558. // // const S_GENERAL_RENDERERS = ['YTD-TOGGLE-BUTTON-RENDERER','YTD-MENU-RENDERER']
  5559. // if (S_GENERAL_RENDERERS.includes(nodeName)) {
  5560. // return;
  5561. // }
  5562.  
  5563. // // _console.log(evt.target.nodeName, 904, evt.type, evt.detail);
  5564.  
  5565. // });
  5566.  
  5567. // DEBUG_LOG && globalHook('data-changed', (evt) => {
  5568.  
  5569. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5570.  
  5571. // let nodeName = evt.target.nodeName.toUpperCase()
  5572. // // _console.log(nodeName, evt.type)
  5573.  
  5574. // if (nodeName === 'YTD-ITEM-SECTION-RENDERER' || nodeName === 'YTD-COMMENTS') {
  5575.  
  5576. // _console.log(344)
  5577.  
  5578. // }
  5579.  
  5580. // })
  5581.  
  5582. // DEBUG_LOG && globalHook('yt-navigate', (evt) => {
  5583.  
  5584. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5585. // _console.log(evt.target.nodeName, evt.type)
  5586.  
  5587. // })
  5588.  
  5589. // DEBUG_LOG && globalHook('ytd-playlist-lockup-now-playing-active', (evt) => {
  5590.  
  5591. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5592. // _console.log(evt.target.nodeName, evt.type)
  5593.  
  5594.  
  5595. // })
  5596.  
  5597. // DEBUG_LOG && globalHook('yt-service-request-completed', (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. // DEBUG_LOG && globalHook('yt-commerce-action-done', (evt) => {
  5606.  
  5607. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5608. // _console.log(evt.target.nodeName, evt.type)
  5609.  
  5610.  
  5611. // })
  5612.  
  5613. // DEBUG_LOG && globalHook('yt-execute-service-endpoint', (evt) => {
  5614.  
  5615. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5616. // _console.log(evt.target.nodeName, evt.type)
  5617.  
  5618.  
  5619. // })
  5620.  
  5621.  
  5622. // DEBUG_LOG && globalHook('yt-request-panel-mode-change', (evt) => {
  5623.  
  5624. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5625. // _console.log(evt.target.nodeName, evt.type)
  5626.  
  5627.  
  5628. // })
  5629.  
  5630.  
  5631. // DEBUG_LOG && globalHook('yt-visibility-refresh', (evt) => {
  5632.  
  5633. // if (!evt || !evt.target /*|| evt.target.nodeType !== 1*/) return;
  5634. // _console.log(evt.target.nodeName || '', evt.type)
  5635.  
  5636. // const ytdFlexyElm = es.ytdFlexy;
  5637. // _console.log(2784, evt.type, (ytdFlexyElm ? ytdFlexyElm.hasAttribute('hidden') : null), evt.detail)
  5638.  
  5639. // _console.log(evt.detail)
  5640.  
  5641.  
  5642. // })
  5643.  
  5644. // DEBUG_LOG && globalHook('yt-request-panel-mode-change', (evt) => {
  5645.  
  5646. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5647. // _console.log(evt.target.nodeName, evt.type)
  5648.  
  5649.  
  5650. // })
  5651.  
  5652. // DEBUG_LOG && globalHook('app-reset-layout', (evt) => {
  5653.  
  5654. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5655. // _console.log(evt.target.nodeName, evt.type)
  5656.  
  5657.  
  5658. // })
  5659. // DEBUG_LOG && globalHook('yt-guide-close', (evt) => {
  5660.  
  5661. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5662. // _console.log(evt.target.nodeName, evt.type)
  5663.  
  5664.  
  5665. // })
  5666. // DEBUG_LOG && globalHook('yt-page-data-will-change', (evt) => {
  5667.  
  5668. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5669. // _console.log(evt.target.nodeName, evt.type)
  5670.  
  5671.  
  5672. // })
  5673.  
  5674. // DEBUG_LOG && globalHook('yt-retrieve-location', (evt) => {
  5675.  
  5676. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5677. // _console.log(evt.target.nodeName, evt.type)
  5678.  
  5679.  
  5680. // })
  5681.  
  5682. // DEBUG_LOG && globalHook('yt-refit', (evt) => {
  5683.  
  5684. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5685. // _console.log(evt.target.nodeName, evt.type)
  5686.  
  5687. // })
  5688.  
  5689. // DEBUG_LOG && globalHook('addon-attached', (evt) => {
  5690.  
  5691. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5692. // _console.log(evt.target.nodeName, evt.type)
  5693.  
  5694. // })
  5695.  
  5696. // DEBUG_LOG && globalHook('yt-live-chat-context-menu-opened', (evt) => {
  5697.  
  5698. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5699. // _console.log(evt.target.nodeName, evt.type)
  5700.  
  5701. // })
  5702.  
  5703. // DEBUG_LOG && globalHook('yt-live-chat-context-menu-closed', (evt) => {
  5704.  
  5705. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5706. // _console.log(evt.target.nodeName, evt.type)
  5707.  
  5708. // })
  5709.  
  5710. // DEBUG_LOG && globalHook('yt-commentbox-resize', (evt) => {
  5711.  
  5712. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5713. // _console.log(evt.target.nodeName, evt.type)
  5714. // })
  5715.  
  5716. // DEBUG_LOG && globalHook('yt-rich-grid-layout-refreshed', (evt) => {
  5717.  
  5718. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5719. // _console.log(2327, evt.target.nodeName, evt.type)
  5720. // })
  5721.  
  5722. // DEBUG_LOG && globalHook('animationend', (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. // DEBUG_LOG && globalHook('yt-dismissible-item-dismissed', (evt) => {
  5731.  
  5732. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5733. // _console.log(evt.target.nodeName, evt.type)
  5734.  
  5735.  
  5736. // })
  5737.  
  5738. // DEBUG_LOG && globalHook('yt-dismissible-item-undismissed', function (evt) {
  5739.  
  5740. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5741. // _console.log(evt.target.nodeName, evt.type)
  5742.  
  5743.  
  5744. // })
  5745.  
  5746.  
  5747. // DEBUG_LOG && globalHook('yt-load-next-continuation', function (evt) {
  5748.  
  5749. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5750. // _console.log(evt.target.nodeName, evt.type)
  5751.  
  5752.  
  5753. // })
  5754.  
  5755.  
  5756. // DEBUG_LOG && globalHook('yt-load-reload-continuation', function (evt) {
  5757.  
  5758. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5759. // _console.log(evt.target.nodeName, evt.type)
  5760.  
  5761.  
  5762. // })
  5763.  
  5764. // DEBUG_LOG && globalHook('yt-toggle-button', function (evt) {
  5765.  
  5766. // if (!evt || !evt.target || evt.target.nodeType !== 1) return;
  5767. // _console.log(evt.target.nodeName, evt.type)
  5768.  
  5769.  
  5770. // })
  5771.  
  5772.  
  5773. }
  5774.  
  5775.  
  5776. function chatFrameContentDocument() {
  5777. // non-null if iframe exist && contentDocument && readyState = complete
  5778. /** @type {HTMLIFrameElement | null} */
  5779. let iframe = document.querySelector('ytd-live-chat-frame iframe#chatframe');
  5780. if (!iframe) return null; //iframe must be there
  5781. /** @type {Document | null} */
  5782. let cDoc = null;
  5783. try {
  5784. cDoc = iframe.contentDocument;
  5785. } catch (e) { }
  5786. if (!cDoc) return null;
  5787. if (cDoc.readyState != 'complete') return null; //we must wait for its completion
  5788.  
  5789. return cDoc;
  5790.  
  5791. }
  5792.  
  5793. function chatFrameElement(/** @type {string} */ cssSelector) {
  5794. let cDoc = chatFrameContentDocument();
  5795. if (!cDoc) return null;
  5796. /** @type {HTMLElement | null} */
  5797. let elm = null;
  5798. try {
  5799. elm = cDoc.querySelector(cssSelector)
  5800. } catch (e) {
  5801. console.log('iframe error', e)
  5802. }
  5803. return elm;
  5804. }
  5805.  
  5806. const iframeLoadControllerId = ControllerID();
  5807.  
  5808. // const iframeLoadHookHandler = function (evt) {
  5809.  
  5810. // const isIframe = (((evt || 0).target || 0).nodeName === 'IFRAME');
  5811. // const iframe = isIframe ? evt.target : null;
  5812.  
  5813. // if (!iframe || !iframe.matches('body iframe.style-scope.ytd-live-chat-frame#chatframe')) {
  5814. // return;
  5815. // }
  5816.  
  5817. // Promise.resolve(iframe).then(iframeLoadProcess);
  5818.  
  5819. // };
  5820.  
  5821. const onIframeSrcReplaced = function (evt) {
  5822. const isIframe = (((evt || 0).target || 0).nodeName === 'IFRAME');
  5823. const iframe = isIframe ? evt.target : null;
  5824. if (!iframe || !iframe.matches('body iframe.style-scope.ytd-live-chat-frame#chatframe')) {
  5825. return;
  5826. }
  5827. Promise.resolve(iframe).then(iframeLoadProcess); // in order to set ready
  5828. };
  5829.  
  5830. const iframeLoadProcessWS = new WeakSet(); // avoid duplicate calling on the same iframe
  5831. const iframeLoadProcess = async function (_iframe) {
  5832.  
  5833. const iframe = _iframe;
  5834.  
  5835. iframeLoadProcessWS.add(iframe);
  5836.  
  5837. await scriptletDeferred.d();
  5838. await tabsInsertedPromise.then();
  5839. await getRAFPromise().then();
  5840. await renderDeferred.d();
  5841.  
  5842. if (!iframeLoadProcessWS.has(iframe)) return;
  5843. iframeLoadProcessWS.delete(iframe);
  5844.  
  5845. if (iframe.isConnected !== true) return;
  5846.  
  5847. // console.log("iframe.xx",1235, iframe)
  5848.  
  5849. const chat = closestDOM.call(iframe, 'ytd-live-chat-frame#chat');
  5850.  
  5851. // console.log('chat', chat)
  5852. if (!chat) return;
  5853. // console.log("iframe.xx",1236, chat)
  5854.  
  5855. if (chat.hasAttribute('collapsed')) return;
  5856. console.debug('[tyt.iframe] loaded 10');
  5857.  
  5858. const tid = iframeLoadControllerId();
  5859. // console.log("iframe.xx",1237, chat)
  5860.  
  5861.  
  5862. const cDoc = await new Promise((resolve) => {
  5863.  
  5864. let timeoutCount = 250;
  5865. let cid = 0;
  5866. const tf = () => {
  5867. let exitLoop;
  5868. if (tid !== +iframeLoadControllerId || --timeoutCount < 0) {
  5869. exitLoop = true;
  5870. } else if (chat.isConnected === true && iframe.isConnected === true && !chat.hasAttribute('collapsed')) {
  5871. exitLoop = false;
  5872. } else {
  5873. exitLoop = true;
  5874. }
  5875.  
  5876. let cDoc = null;
  5877. if (!exitLoop) {
  5878.  
  5879. if (HTMLElement.prototype.closest.call(iframe, '[hidden]')) return;
  5880. if (!HTMLElement.prototype.closest.call(iframe, '#columns.style-scope.ytd-watch-flexy')) return;
  5881. try {
  5882. cDoc = iframe.contentDocument;
  5883. } catch (e) {
  5884. }
  5885. if (!cDoc) return;
  5886. // if (cDoc.readyState === 'loading') return;
  5887. if (!cDoc.body) return;
  5888.  
  5889. }
  5890.  
  5891. resolve && resolve(cDoc);
  5892. resolve = null;
  5893. cid && clearInterval(cid);
  5894. cid = 0;
  5895.  
  5896. }
  5897. tf();
  5898. if (resolve !== null) {
  5899. cid = setInterval(tf, 17);
  5900. }
  5901.  
  5902.  
  5903. }).catch(console.warn);
  5904.  
  5905. console.debug('[tyt.iframe] loaded 11');
  5906. if (tid !== +iframeLoadControllerId || !cDoc) {
  5907. return;
  5908. }
  5909.  
  5910. console.debug('[tyt.iframe] loaded 12');
  5911.  
  5912. if (chat.hasAttribute('collapsed') || iframe.isConnected !== true) {
  5913. return;
  5914. }
  5915.  
  5916. if (cDoc && (cDoc.readyState === 'loading' || !(cDoc.body || 0).firstElementChild)) {
  5917. await new Promise(r => setTimeout(r, 50));
  5918. }
  5919.  
  5920. if (chat.hasAttribute('collapsed') || iframe.isConnected !== true) {
  5921. return;
  5922. }
  5923.  
  5924. console.debug('[tyt.iframe] loaded 13');
  5925.  
  5926. // console.log("iframe.xx",1238, chat)
  5927.  
  5928. const contentElement = (cDoc.body || 0).firstElementChild;
  5929.  
  5930. if (contentElement) {
  5931. console.debug('[tyt.iframe] loaded 20');
  5932.  
  5933. if (!scriptEnable || !isChatExpand()) return; // v4.13.19 - scriptEnable = true in background
  5934. if (!(iframe instanceof HTMLIFrameElement) || iframe.isConnected !== true) return; //prevent iframe is detached from the page
  5935. let isCorrectDoc = false;
  5936. try {
  5937. isCorrectDoc = iframe.contentDocument === cDoc;
  5938. } catch (e) { }
  5939. console.debug('[tyt.iframe] loaded 21');
  5940. if (isCorrectDoc) {
  5941. let chatFrame = closestDOM.call(iframe, 'ytd-live-chat-frame#chat');
  5942. if (chatFrame) {
  5943. console.debug('[tyt.iframe] loaded 22');
  5944. // chatFrame.setAttribute('tyt-iframe-loaded', '');
  5945. dpeIframeReady(chatFrame);
  5946. }
  5947. }
  5948.  
  5949. } else if (!contentElement) {
  5950. console.debug('[tyt.iframe] loaded 30');
  5951.  
  5952. // e.g. when restore from mini view to watch page
  5953.  
  5954. // tabview-chat-fix-url-onload-with-empty-body
  5955. iframe.removeEventListener('iframe-src-replaced', onIframeSrcReplaced, false);
  5956. iframe.addEventListener('iframe-src-replaced', onIframeSrcReplaced, false);
  5957. dpeFixUrlChatWhenOnloadWithEmptyBody(chat);
  5958.  
  5959. }
  5960.  
  5961.  
  5962. };
  5963.  
  5964. async function restorePIPforStickyHead() {
  5965. // after a trusted user action, PIP can be cancelled.
  5966. // this is to ensure enterPIP can be re-excecuted
  5967.  
  5968. if (isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation) {
  5969. userActivation = false;
  5970. exitPIP();
  5971. }
  5972. }
  5973.  
  5974. let videosDeferred = new Deferred();
  5975.  
  5976. let _navigateLoadDT = 0;
  5977.  
  5978. function delayedClickHandler() {
  5979.  
  5980. if (isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled) {
  5981. restorePIPforStickyHead();
  5982. } else if (!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && typeof IntersectionObserver == 'function') {
  5983. enablePIPforStickyHead();
  5984. }
  5985.  
  5986. }
  5987.  
  5988. function convertDefaultTabFromTmpToFinal(myDefaultTab_tmp) {
  5989.  
  5990. let myDefaultTab_final = null
  5991. if (myDefaultTab_tmp && typeof myDefaultTab_tmp === 'string' && /^\#[a-zA-Z\_\-\+]+$/.test(myDefaultTab_tmp)) {
  5992. if (document.querySelector(`.tab-btn[tyt-tab-content="${myDefaultTab_tmp}"]`)) myDefaultTab_final = myDefaultTab_tmp;
  5993. }
  5994.  
  5995. return myDefaultTab_final;
  5996. }
  5997.  
  5998. function getConfiguredDefaultTab(store) {
  5999. let myDefaultTab;
  6000. if (defaultTabByUserCSS === 1) {
  6001. myDefaultTab = '#tab-info';
  6002. } else if (defaultTabByUserCSS === 2) {
  6003. myDefaultTab = '#tab-comments';
  6004. } else if (defaultTabByUserCSS === 3) {
  6005. myDefaultTab = '#tab-videos';
  6006. } else {
  6007. store = store || getStore();
  6008. myDefaultTab = store[key_default_tab];
  6009. }
  6010. return myDefaultTab;
  6011. }
  6012.  
  6013. function setupTabBtns() {
  6014.  
  6015. const materialTab = document.querySelector("#material-tabs")
  6016. if (!materialTab) return;
  6017.  
  6018. if (tabsUiScript_setclick) return;
  6019. tabsUiScript_setclick = true;
  6020.  
  6021. let fontSizeBtnClick = null;
  6022.  
  6023. materialTab.addEventListener('click', async function (evt) {
  6024. const dom = evt.target;
  6025. if ((dom || 0).nodeType !== 1) return;
  6026.  
  6027. await getRAFPromise().then(); // prevent execution in background
  6028. await scriptletDeferred.d();
  6029.  
  6030. if (dom.isConnected !== true) return;
  6031.  
  6032. let b = isMiniviewForStickyHeadEnabled || (isStickyHeaderEnabled && typeof IntersectionObserver == 'function');
  6033. if (b) {
  6034. setTimeout(delayedClickHandler, 80);
  6035. }
  6036.  
  6037. const domInteraction = dom.getAttribute('tyt-di');
  6038. if (domInteraction === 'q9Kjc') {
  6039. handlerMaterialTabClick.call(dom, evt);
  6040. } else if (domInteraction === '8rdLQ') {
  6041. fontSizeBtnClick && fontSizeBtnClick.call(dom, evt);
  6042. }
  6043.  
  6044. }, true);
  6045.  
  6046. function updateCSS_fontsize(store) {
  6047.  
  6048. if (!store) return;
  6049.  
  6050. const ytdFlexyElm = es.ytdFlexy;
  6051. if (ytdFlexyElm) {
  6052. if (store['font-size-#tab-info']) ytdFlexyElm.style.setProperty('--ut2257-info', store['font-size-#tab-info'])
  6053. if (store['font-size-#tab-comments']) ytdFlexyElm.style.setProperty('--ut2257-comments', store['font-size-#tab-comments'])
  6054. if (store['font-size-#tab-videos']) ytdFlexyElm.style.setProperty('--ut2257-videos', store['font-size-#tab-videos'])
  6055. if (store['font-size-#tab-list']) ytdFlexyElm.style.setProperty('--ut2257-list', store['font-size-#tab-list'])
  6056. document.dispatchEvent(new CustomEvent("tabview-zoom-updated"));
  6057. }
  6058.  
  6059. }
  6060.  
  6061. fontSizeBtnClick = function (evt) {
  6062.  
  6063. evt.preventDefault();
  6064. evt.stopPropagation();
  6065. evt.stopImmediatePropagation();
  6066.  
  6067. /** @type {HTMLElement | null} */
  6068. let dom = evt.target;
  6069. if (!dom) return;
  6070.  
  6071. let value = dom.classList.contains('font-size-plus') ? 1 : dom.classList.contains('font-size-minus') ? -1 : 0;
  6072.  
  6073. let active_tab_content = closestDOM.call(dom, '[tyt-tab-content]').getAttribute('tyt-tab-content');
  6074.  
  6075. let store = getStore();
  6076. let settingKey = `font-size-${active_tab_content}`
  6077. if (!store[settingKey]) store[settingKey] = 1.0;
  6078. if (value < 0) store[settingKey] -= 0.05;
  6079. else if (value > 0) store[settingKey] += 0.05;
  6080. if (store[settingKey] < 0.1) store[settingKey] = 0.1;
  6081. else if (store[settingKey] > 10) store[settingKey] = 10.0;
  6082. setStore(store);
  6083.  
  6084. store = getStore();
  6085. updateCSS_fontsize(store);
  6086.  
  6087. }
  6088.  
  6089. function loadDefaultTabBtnSettingToMem(store) {
  6090. let myDefaultTab = getConfiguredDefaultTab(store);
  6091. myDefaultTab = myDefaultTab ? convertDefaultTabFromTmpToFinal(myDefaultTab) : null;
  6092. if (myDefaultTab) {
  6093. settings.defaultTab = myDefaultTab;
  6094. }
  6095. }
  6096.  
  6097. let store = getStore();
  6098. updateCSS_fontsize(store);
  6099. loadDefaultTabBtnSettingToMem(store);
  6100. setupDefaultTabBtnSetting = function () {
  6101. let myDefaultTab = getConfiguredDefaultTab();
  6102. myDefaultTab = myDefaultTab ? convertDefaultTabFromTmpToFinal(myDefaultTab) : null;
  6103. if (myDefaultTab) {
  6104. settings.defaultTab = myDefaultTab;
  6105. } else {
  6106. settings.defaultTab = SETTING_DEFAULT_TAB_0;
  6107. }
  6108. }
  6109.  
  6110. }
  6111.  
  6112. function setMyDefaultTab(myDefaultTab) {
  6113. myDefaultTab = convertDefaultTabFromTmpToFinal(myDefaultTab);
  6114. let store = getStore();
  6115. if (myDefaultTab) {
  6116. store[key_default_tab] = myDefaultTab;
  6117. settings.defaultTab = myDefaultTab;
  6118. } else {
  6119. delete store[key_default_tab];
  6120. settings.defaultTab = SETTING_DEFAULT_TAB_0;
  6121. }
  6122. setStore(store);
  6123. }
  6124.  
  6125. document.addEventListener('tabview-setMyDefaultTab', function (evt) {
  6126.  
  6127. let myDefaultTab_tmp = ((evt || 0).detail || 0).myDefaultTab
  6128.  
  6129. setMyDefaultTab(myDefaultTab_tmp)
  6130.  
  6131. }, false)
  6132.  
  6133. function loadFrameHandler(evt) {
  6134. let target = (evt || 0).target;
  6135. if (target instanceof HTMLIFrameElement && target.id === 'chatframe') {
  6136. fixLiveChatToggleButtonDispatchEvent();
  6137. }
  6138. }
  6139. async function onNavigationEndAsync() {
  6140.  
  6141. await scriptletDeferred.d();
  6142.  
  6143. if (pageType !== 'watch') return;
  6144.  
  6145. Promise.resolve().then(setupVideoTitleHover);
  6146.  
  6147. // infoContentSetup();
  6148.  
  6149. let tdt = Date.now();
  6150. _navigateLoadDT = tdt;
  6151.  
  6152. // avoid blocking the page when youtube is initializing the page
  6153. const promiseDelay = getRAFPromise().then();
  6154. const promiseVideoRendered = videosDeferred.d();
  6155.  
  6156. const verifyPageState = () => {
  6157. if (_navigateLoadDT !== tdt) {
  6158. return -400;
  6159. }
  6160. if (ytEventSequence !== 3) {
  6161. return -200;
  6162. }
  6163.  
  6164. const ytdFlexyElm = document.querySelector('ytd-watch-flexy:not([hidden])') || document.querySelector('ytd-watch-flexy');
  6165.  
  6166. if (!ytdFlexyElm) {
  6167. ytdFlexy = null;
  6168. return -100;
  6169. } else {
  6170. ytdFlexy = mWeakRef(ytdFlexyElm);
  6171. return 0;
  6172. }
  6173.  
  6174.  
  6175. }
  6176.  
  6177. let pgState = verifyPageState();
  6178. if (pgState < 0) return;
  6179.  
  6180. let scriptEnableTemp = scriptEnable;
  6181. scriptEnable = true; // avoid locking the other parts of script (see v4.13.19)
  6182. await Promise.all([promiseVideoRendered, promiseDelay]);
  6183. pgState = verifyPageState();
  6184. if (pgState < 0) {
  6185. scriptEnable = scriptEnableTemp;
  6186. if (!ytdFlexy) scriptEnable = false;
  6187. return;
  6188. }
  6189. pgState = null;
  6190. const ytdFlexyElm = kRef(ytdFlexy);
  6191.  
  6192. if (!ytdFlexyElm) {
  6193. ytdFlexy = null;
  6194. scriptEnable = false;
  6195. return;
  6196. }
  6197.  
  6198. fixLiveChatToggleButtonDispatchEvent();
  6199. document.removeEventListener('load', loadFrameHandler, true);
  6200. document.addEventListener('load', loadFrameHandler, true);
  6201.  
  6202. const related = querySelectorFromAnchor.call(ytdFlexyElm, "#related.ytd-watch-flexy");
  6203. if (!related) return;
  6204.  
  6205.  
  6206. if (!document.querySelector("#right-tabs")) {
  6207. getLangForPage();
  6208. let docTmp = document.createElement('template');
  6209. docTmp.innerHTML = getTabsHTML();
  6210. let newElm = docTmp.content.firstElementChild;
  6211. if (newElm !== null) {
  6212. insertBeforeTo(newElm, related);
  6213. querySelectorFromAnchor.call(newElm, '#material-tabs').addEventListener('mousemove', (evt) => {
  6214. evt.preventDefault();
  6215. evt.stopPropagation();
  6216. evt.stopImmediatePropagation();
  6217. }, true);
  6218. setupTabBtns();
  6219. console.debug('[tyt] #right-tabs inserted')
  6220. }
  6221. docTmp.textContent = '';
  6222. docTmp = null;
  6223. }
  6224.  
  6225. if (!ytdFlexyElm.hasAttribute('tyt-tab')) ytdFlexyElm.setAttribute('tyt-tab', '')
  6226.  
  6227. // append the next videos
  6228. // it exists as "related" is already here
  6229. fixTabs();
  6230.  
  6231. let switchToDefaultTabNotAllowed = false;
  6232.  
  6233. if (document.querySelector('ytd-watch-flexy[tyt-chat^="+"]')) {
  6234. switchToDefaultTabNotAllowed = true;
  6235. } 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])')) {
  6236. switchToDefaultTabNotAllowed = true;
  6237. } else if (document.querySelector('ytd-watch-flexy ytd-donation-shelf-renderer.ytd-watch-flexy:not([hidden]):not(:empty)')) {
  6238. switchToDefaultTabNotAllowed = true;
  6239. }
  6240.  
  6241. if (switchToDefaultTabNotAllowed) {
  6242. switchTabActivity(null);
  6243. } else {
  6244. setToActiveTab(); // just switch to the default tab
  6245. }
  6246.  
  6247.  
  6248. mtoFlexyAttr.clear(true)
  6249. mtoBodyAttr.clear(true)
  6250. mtf_checkFlexy()
  6251.  
  6252. document.documentElement.setAttribute('tyt-deferred', '')
  6253. tabsDeferred.resolve();
  6254. tabsInsertedPromise.resolve();
  6255. FP.mtf_attrEngagementPanel(); // check whether no visible panels
  6256.  
  6257.  
  6258. }
  6259.  
  6260.  
  6261. function fetchCommentsFinished() {
  6262. const ytdFlexyElm = es.ytdFlexy;
  6263. if (!scriptEnable || !ytdFlexyElm) return;
  6264. if (mtf_forceCheckLiveVideo_disable === 2) return;
  6265. ytdFlexyElm.setAttribute('tyt-comments', 'L');
  6266. _console.log(2909, 1)
  6267. }
  6268.  
  6269. function setCommentSection( /** @type {number} */ value) {
  6270.  
  6271. Q.comments_section_loaded = value;
  6272. if (value === 0 && fetchCounts) {
  6273. fetchCounts.fetched = false; // unknown bug
  6274. }
  6275.  
  6276. }
  6277.  
  6278.  
  6279. function emptyCommentSection() {
  6280. let tab_btn = document.querySelector('.tab-btn[tyt-tab-content="#tab-comments"]')
  6281. if (tab_btn) {
  6282. let span = querySelectorFromAnchor.call(tab_btn, 'span#tyt-cm-count');
  6283. tab_btn.removeAttribute('loaded-comment')
  6284. if (span) {
  6285. span.textContent = '';
  6286. }
  6287. }
  6288. setCommentSection(0);
  6289. _console.log(7233, 'comments_section_loaded = 0')
  6290. }
  6291.  
  6292.  
  6293. function _disableComments() {
  6294.  
  6295.  
  6296. _console.log(2909, 1)
  6297. if (!scriptEnable) return;
  6298. let cssElm = es.ytdFlexy;
  6299. if (!cssElm) return;
  6300.  
  6301. _console.log(2909, 2)
  6302.  
  6303.  
  6304. let comments = document.querySelector('ytd-comments#comments')
  6305. if (mtf_forceCheckLiveVideo_disable === 2) {
  6306. // earlier than DOM change
  6307. } else {
  6308. if (comments && !comments.hasAttribute('hidden')) return; // visible comments content)
  6309. }
  6310.  
  6311. _console.log(2909, 4)
  6312. if (Q.comments_section_loaded === 2) return; //already disabled
  6313.  
  6314. setCommentSection(2);
  6315.  
  6316. _console.log(2909, 5)
  6317.  
  6318. let tabBtn = document.querySelector('.tab-btn[tyt-tab-content="#tab-comments"]');
  6319. if (tabBtn) {
  6320. let span = querySelectorFromAnchor.call(tabBtn, 'span#tyt-cm-count');
  6321. tabBtn.removeAttribute('loaded-comment')
  6322. if (!tabBtn.classList.contains('tab-btn-hidden')) {
  6323. //console.log('hide', comments, comments && comments.hasAttribute('hidden'))
  6324. hideTabBtn(tabBtn)
  6325. }
  6326. if (span) {
  6327. span.textContent = '';
  6328. }
  6329. }
  6330.  
  6331. cssElm.setAttribute('tyt-comments', 'D');
  6332.  
  6333. _console.log(2909, 10)
  6334.  
  6335.  
  6336. }
  6337.  
  6338. function setToggleInfo() {
  6339.  
  6340. scriptletDeferred.d().then(() => {
  6341.  
  6342. let elem = document.querySelector('#primary.ytd-watch-flexy #below ytd-watch-metadata #info-container.ytd-watch-metadata:first-child:not([tyt-info-toggler])')
  6343. if (elem) {
  6344.  
  6345. elem.setAttribute('tyt-info-toggler', '')
  6346. elem.dispatchEvent(new CustomEvent('tyt-info-toggler'))
  6347.  
  6348. }
  6349.  
  6350. });
  6351. }
  6352.  
  6353.  
  6354. function flexyAttr_toggleFlag(mFlag, b, flag) {
  6355. return b ? (mFlag | flag) : (mFlag & ~flag);
  6356. }
  6357.  
  6358. function flexAttr_toLayoutStatus(nls, attributeName) {
  6359.  
  6360. let attrElm, b, v;
  6361. switch (attributeName) {
  6362. case 'theater':
  6363. b = isTheater();
  6364. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_THEATER);
  6365. break;
  6366. case 'tyt-chat':
  6367. attrElm = es.ytdFlexy;
  6368. v = attrElm.getAttribute('tyt-chat');
  6369.  
  6370. if (v !== null && v.charAt(0) === '-') {
  6371. nls = flexyAttr_toggleFlag(nls, true, LAYOUT_CHATROOM | LAYOUT_CHATROOM_COLLAPSED);
  6372. } else {
  6373. nls = flexyAttr_toggleFlag(nls, v !== null, LAYOUT_CHATROOM);
  6374. nls = flexyAttr_toggleFlag(nls, false, LAYOUT_CHATROOM_COLLAPSED);
  6375. }
  6376.  
  6377. break;
  6378. case 'is-two-columns_':
  6379. b = isWideScreenWithTwoColumns();
  6380. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_TWO_COLUMNS);
  6381. break;
  6382.  
  6383. case 'tyt-tab':
  6384. attrElm = es.ytdFlexy;
  6385. b = isNonEmptyString(attrElm.getAttribute('tyt-tab'));
  6386. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_TAB_EXPANDED);
  6387. break;
  6388.  
  6389. case 'fullscreen':
  6390. attrElm = es.ytdFlexy;
  6391. b = attrElm.hasAttribute('fullscreen');
  6392. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_FULLSCREEN);
  6393. break;
  6394.  
  6395. case 'tyt-ep-visible':
  6396. attrElm = es.ytdFlexy;
  6397. v = attrElm.getAttribute('tyt-ep-visible');
  6398. b = (+v > 0)
  6399. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_ENGAGEMENT_PANEL_EXPANDED);
  6400. break;
  6401.  
  6402. case 'tyt-donation-shelf':
  6403. attrElm = es.ytdFlexy;
  6404. b = attrElm.hasAttribute('tyt-donation-shelf');
  6405. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_DONATION_SHELF_EXPANDED);
  6406. break;
  6407.  
  6408. }
  6409.  
  6410. return nls;
  6411.  
  6412.  
  6413. }
  6414.  
  6415.  
  6416.  
  6417. function ito_details(entries, observer) {
  6418. if (!detailsTriggerReset) return;
  6419. if (!entries || entries.length !== 1) return; // unlikely
  6420. let entry = entries[0];
  6421. //console.log(entries)
  6422. if (entry.isIntersecting === true) {
  6423.  
  6424. if (fT(wls.layoutStatus, LAYOUT_TWO_COLUMNS | LAYOUT_FULLSCREEN, 0) === false) return;
  6425.  
  6426. let dom = entry.target;
  6427. if (!dom) return; //unlikely
  6428.  
  6429. let bool = false;
  6430. let descClickable = null;
  6431.  
  6432. if (fT(wls.layoutStatus, 0, LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED | LAYOUT_CHATROOM_EXPANDED | LAYOUT_TAB_EXPANDED) === false) {
  6433. descClickable = closestDOM.call(dom, '#description.item.style-scope.ytd-watch-metadata')
  6434. if (descClickable) {
  6435. detailsTriggerReset = false;
  6436. bool = true;
  6437. }
  6438. }
  6439.  
  6440. async function runAsync(dom, bool) {
  6441.  
  6442. if (bool) {
  6443. let descClickable = closestDOM.call(dom, '#description.item.style-scope.ytd-watch-metadata')
  6444. if (descClickable) {
  6445. descClickable.click();
  6446. }
  6447. }
  6448.  
  6449. await new Promise(r => setTimeout(r, 20));
  6450.  
  6451. let pInner, nw = null;
  6452. try {
  6453. let x = closestDOM.call(dom, '#description.item.style-scope.ytd-watch-metadata');
  6454. let h2 = x.offsetHeight;
  6455. pInner = closestDOM.call(x, '#primary-inner')
  6456. let h1 = pInner.offsetHeight;
  6457. x.setAttribute('userscript-scrollbar-render', '')
  6458. if (h1 > h2 && h2 > 0 && h1 > 0) nw = h1 - h2
  6459. } catch (e) { }
  6460. if (pInner) {
  6461. pInner.style.setProperty('--tyt-desc-top-h', `${nw ? nw : 0}px`)
  6462. }
  6463. }
  6464.  
  6465. runAsync(dom, bool);
  6466.  
  6467.  
  6468. }
  6469.  
  6470. }
  6471.  
  6472. function immediateCheck() {
  6473.  
  6474.  
  6475. if (!scriptEnable) return;
  6476.  
  6477. 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)) {
  6478. setToActiveTab();
  6479. }
  6480.  
  6481. }
  6482.  
  6483. // let _ctlPromise = null;
  6484. // const getCTLPromise = () => {
  6485. // if(!_ctlPromise) _ctlPromise = new PromiseExternal();
  6486.  
  6487. // const ytdFlexyElm = es.ytdFlexy;
  6488. // if (!scriptEnable || !ytdFlexyElm || !wls.layoutStatus) {
  6489. // _ctlPromise.resolve();
  6490. // }else{
  6491. // ytdFlexyElm.setAttribute('tyt-ctl', ytdFlexyElm.getAttribute('tyt-ctl') === '1' ? '0' : '1')
  6492. // }
  6493.  
  6494. // return _ctlPromise;
  6495. // };
  6496.  
  6497.  
  6498. // const triggerCTL = ()=>{
  6499. // _ctlPromise && _ctlPromise.resolve();
  6500. // _ctlPromise = null
  6501. // }
  6502.  
  6503. const mtf_attrFlexy = (mutations, observer) => {
  6504. // if(document.documentElement.hasAttribute('p355')) return;
  6505.  
  6506. //attr mutation checker - $$ytdFlexyElm$$ {ytd-watch-flexy} \single
  6507. //::attr
  6508. // ~ 'tyt-chat', 'theater', 'is-two-columns_',
  6509. // ~ 'tyt-tab', 'fullscreen', 'tyt-ep-visible',
  6510. // ~ 'hidden', 'is-extra-wide-video_'
  6511.  
  6512. //console.log(15330, scriptEnable, es.ytdFlexy, mutations)
  6513.  
  6514. if (!scriptEnable) return;
  6515.  
  6516. const cssElm = es.ytdFlexy;
  6517. if (!cssElm) return;
  6518.  
  6519. if (!mutations) return;
  6520.  
  6521.  
  6522. const old_layoutStatus = wls.layoutStatus
  6523. if (old_layoutStatus === 0) return;
  6524. let new_layoutStatus = old_layoutStatus;
  6525.  
  6526. let checkedChat = false;
  6527. let mss = 0;
  6528. let dcall = 0;
  6529. // let resolveCTL = false;
  6530. check1885();
  6531. if (!chatController.allowChatControl){
  6532.  
  6533. // for (const mutation of mutations) {
  6534.  
  6535. // if(mutation.attributeName === 'tyt-ctl') {
  6536. // resolveCTL = true;
  6537. // continue;
  6538. // }
  6539. // }
  6540. // if(resolveCTL) triggerCTL();
  6541. return;
  6542. }
  6543.  
  6544. for (const mutation of mutations) {
  6545.  
  6546. // if(mutation.attributeName === 'tyt-ctl') {
  6547. // resolveCTL = true;
  6548. // continue;
  6549. // }
  6550.  
  6551. // if(1885 && document.body.hasAttribute('data-ytlstm-theater-mode')) continue;
  6552. new_layoutStatus = flexAttr_toLayoutStatus(new_layoutStatus, mutation.attributeName);
  6553. // _console.log(8221, 18, mutation.attributeName)
  6554. if (mutation.attributeName === 'tyt-chat') {
  6555.  
  6556. if (!checkedChat) {
  6557. checkedChat = true; // avoid double call
  6558.  
  6559. if ((cssElm.getAttribute('tyt-chat') || '').indexOf('chat$live') >= 0) {
  6560. // assigned new attribute - "chat$live" => disable comments section
  6561.  
  6562. //console.log(3712,2)
  6563. _disableComments();
  6564. }
  6565.  
  6566. if (!cssElm.hasAttribute('tyt-chat')) {
  6567. // might or might not collapsed before
  6568. dcall |= 1;
  6569. }
  6570. }
  6571.  
  6572. } else if (mutation.attributeName === 'tyt-ep-visible') {
  6573. // assume any other active component such as tab content and chatroom
  6574.  
  6575. if (+(cssElm.getAttribute('tyt-ep-visible') || 0) === 0 && +mutation.oldValue > 0) {
  6576. dcall |= 2;
  6577. }
  6578.  
  6579. if (mss === 0) mss = 1;
  6580. else mss = -1;
  6581.  
  6582. } else if (mutation.attributeName === 'tyt-donation-shelf') {
  6583. // assume any other active component such as tab content and chatroom
  6584.  
  6585. // console.log(4545, cssElm.hasAttribute('tyt-donation-shelf'))
  6586. if (!(cssElm.hasAttribute('tyt-donation-shelf'))) {
  6587. dcall |= 4;
  6588. } else {
  6589. lstTab.lastPanel = '#donation-shelf'
  6590. switchTabActivity(null);
  6591. // console.log(55)
  6592. }
  6593. if (mss === 0) mss = 2;
  6594. else mss = -1;
  6595.  
  6596. } else if (mutation.attributeName === 'is-extra-wide-video_') {
  6597. setTimeout(() => {
  6598. updateFloatingSlider(); //required for hover slider // eg video after ads
  6599. }, 1);
  6600. }
  6601. }
  6602.  
  6603. new_layoutStatus = fixLayoutStatus(new_layoutStatus);
  6604.  
  6605. if (new_layoutStatus !== old_layoutStatus) {
  6606.  
  6607. if (fT(new_layoutStatus, LAYOUT_TWO_COLUMNS, LAYOUT_TAB_EXPANDED | LAYOUT_THEATER | LAYOUT_CHATROOM_EXPANDED)) {
  6608. if (mss === 1) {
  6609. if (fT(new_layoutStatus, LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED, 0)) {
  6610. closeDonationShelf();
  6611. }
  6612. } else if (mss === 2) {
  6613. if (fT(new_layoutStatus, LAYOUT_ENGAGEMENT_PANEL_EXPANDED | LAYOUT_DONATION_SHELF_EXPANDED, 0)) {
  6614. ytBtnCloseEngagementPanels();
  6615. }
  6616. }
  6617. }
  6618. wls.layoutStatus = new_layoutStatus
  6619.  
  6620. }
  6621.  
  6622. let timeout240 = new Promise(r => timeline.setTimeout(r, 240));
  6623. timeout240.then(immediateCheck);
  6624.  
  6625. // if(resolveCTL) triggerCTL();
  6626.  
  6627. }
  6628.  
  6629. const mtf_attrBody = (mutations, observer) => {
  6630.  
  6631. setTimeout(() => {
  6632.  
  6633. layoutStatusMutex.lockWith(unlock => {
  6634.  
  6635. check1885();
  6636. check1886();
  6637.  
  6638. if (chatController.allowChatControl) {
  6639. mtf_checkFlexy_(wls.layoutStatus);
  6640. fixTabs();
  6641. }
  6642.  
  6643. if (document.fullscreenElement) {
  6644. unlock();
  6645. } else if (wls.layoutStatus & LAYOUT_THEATER) {
  6646. if (chatController.allowChatControl) {
  6647. fixTheaterChat1A();
  6648. } else {
  6649. fixTheaterChat2A();
  6650. }
  6651. setTimeout(unlock, 17);
  6652. } else {
  6653. unlock();
  6654. }
  6655.  
  6656. });
  6657.  
  6658. }, 40);
  6659.  
  6660.  
  6661. }
  6662.  
  6663. function setupChatFrameDisplayState1(chatBlockR, initialDisplayState) {
  6664.  
  6665.  
  6666. const ytdFlexyElm = es.ytdFlexy;
  6667. if (!scriptEnable || !ytdFlexyElm) return;
  6668.  
  6669. let chatTypeChanged = mtf_chatBlockQ !== chatBlockR;
  6670.  
  6671. let attr_chatblock = chatBlockR === 1 ? 'chat$live' : chatBlockR === 3 ? 'chat$playback' : false;
  6672. let attr_chatcollapsed = false;
  6673.  
  6674.  
  6675. if (attr_chatblock) {
  6676. let chatFrame = document.querySelector('ytd-live-chat-frame#chat')
  6677. if (chatFrame) {
  6678. attr_chatcollapsed = chatFrame.hasAttribute('collapsed');
  6679. if (!attr_chatcollapsed) {
  6680.  
  6681. //nativeFunc(p,'setupPlayerProgressRelay')
  6682. //if(!p.isFrameReady)
  6683. //nativeFunc(p, "urlChanged")
  6684. //console.log(12399,1)
  6685. chatFrame.dispatchEvent(new CustomEvent("tabview-chatroom-newpage")); //possible empty iframe is shown
  6686.  
  6687. }
  6688. } else {
  6689. attr_chatcollapsed = initialDisplayState === 'LIVE_CHAT_DISPLAY_STATE_COLLAPSED' ? true : false;
  6690. }
  6691. }
  6692.  
  6693. if (chatTypeChanged) {
  6694. mtf_chatBlockQ = chatBlockR
  6695.  
  6696. // _console.log(932, 2, attr_chatblock, attr_chatcollapsed)
  6697.  
  6698. //LIVE_CHAT_DISPLAY_STATE_COLLAPSED
  6699. //LIVE_CHAT_DISPLAY_STATE_EXPANDED
  6700. let v = attr_chatblock
  6701. if (typeof attr_chatblock == 'string') {
  6702.  
  6703. if (attr_chatcollapsed === true) v = '-' + attr_chatblock
  6704. if (attr_chatcollapsed === false) v = '+' + attr_chatblock;
  6705. }
  6706. wAttr(ytdFlexyElm, 'tyt-chat', v)
  6707.  
  6708. // _console.log(932, 3, ytdFlexyElm.hasAttribute('tyt-chat'))
  6709.  
  6710.  
  6711. }
  6712.  
  6713. return { attr_chatblock, attr_chatcollapsed, chatTypeChanged }
  6714. }
  6715.  
  6716. function setupChatFrameDisplayState2() {
  6717.  
  6718. const ytdFlexyElm = es.ytdFlexy;
  6719. if (!scriptEnable || !ytdFlexyElm) return null;
  6720.  
  6721. // this is a backup solution only; should be abandoned
  6722.  
  6723. let attr_chatblock = null
  6724. let attr_chatcollapsed = null;
  6725.  
  6726. const elmChat = document.querySelector('ytd-live-chat-frame#chat')
  6727. let elmCont = null;
  6728. if (elmChat) {
  6729. elmCont = chatFrameElement('yt-live-chat-renderer #continuations')
  6730.  
  6731.  
  6732. let s = 0;
  6733. if (elmCont) {
  6734. //not found if it is collapsed.
  6735. s |= querySelectorFromAnchor.call(elmCont, 'yt-timed-continuation') ? 1 : 0;
  6736. s |= querySelectorFromAnchor.call(elmCont, 'yt-live-chat-replay-continuation, yt-player-seek-continuation') ? 2 : 0;
  6737. //s |= elmCont.querySelector('yt-live-chat-restricted-participation-renderer')?4:0;
  6738. if (s == 1) {
  6739. attr_chatblock = 'chat$live';
  6740. } else if (s == 2) attr_chatblock = 'chat$playback';
  6741.  
  6742. if (s == 1) {
  6743. let cmCountElm = document.querySelector("span#tyt-cm-count")
  6744. if (cmCountElm) cmCountElm.textContent = '';
  6745. }
  6746.  
  6747. } else if (!ytdFlexyElm.hasAttribute('tyt-chat')) {
  6748. // live chat frame but type not known
  6749.  
  6750. attr_chatblock = '';
  6751.  
  6752. }
  6753. //keep unknown as original
  6754.  
  6755.  
  6756. let isCollapsed = !!elmChat.hasAttribute('collapsed');
  6757. attr_chatcollapsed = isCollapsed;
  6758.  
  6759. } else {
  6760. attr_chatblock = false;
  6761. attr_chatcollapsed = false;
  6762.  
  6763. }
  6764.  
  6765. return { attr_chatblock, attr_chatcollapsed }
  6766.  
  6767. }
  6768.  
  6769.  
  6770. const mtf_checkFlexy_ = (ls) => {
  6771.  
  6772. const ls0 = ls;
  6773.  
  6774. ls = flexAttr_toLayoutStatus(ls, 'theater')
  6775. ls = flexAttr_toLayoutStatus(ls, 'tyt-chat')
  6776. ls = flexAttr_toLayoutStatus(ls, 'is-two-columns_')
  6777. ls = flexAttr_toLayoutStatus(ls, 'tyt-tab')
  6778. ls = flexAttr_toLayoutStatus(ls, 'fullscreen')
  6779. ls = flexAttr_toLayoutStatus(ls, 'tyt-ep-visible')
  6780. ls = flexAttr_toLayoutStatus(ls, 'tyt-donation-shelf')
  6781.  
  6782. fixLayoutStatus(ls);
  6783.  
  6784. if (ls0 !== ls) {
  6785. wls.layoutStatus = ls
  6786. }
  6787.  
  6788. }
  6789.  
  6790. const mtf_checkFlexy = () => {
  6791. // once per $$native-ytd-watch-flexy$$ {ytd-watch-flexy} detection
  6792.  
  6793. const ytdFlexyElm = es.ytdFlexy;
  6794. if (!scriptEnable || !ytdFlexyElm) return true;
  6795.  
  6796.  
  6797. wls.layoutStatus = 0;
  6798.  
  6799. let isFlexyHidden = (ytdFlexyElm.hasAttribute('hidden'));
  6800.  
  6801. if (!isFlexyHidden) {
  6802. let rChatExist = setupChatFrameDisplayState2();
  6803. if (rChatExist) {
  6804. let { attr_chatblock, attr_chatcollapsed } = rChatExist;
  6805. if (attr_chatblock === null) {
  6806. //remove attribute if it is unknown
  6807. attr_chatblock = false;
  6808. attr_chatcollapsed = false;
  6809. }
  6810. let v = attr_chatblock;
  6811. if (typeof v === 'string') {
  6812. if (attr_chatcollapsed === true) v = '-' + v;
  6813. if (attr_chatcollapsed === false) v = '+' + v;
  6814. }
  6815. wAttr(ytdFlexyElm, 'tyt-chat', v)
  6816.  
  6817. }
  6818. }
  6819.  
  6820. let rTabSelection = [...querySelectorAllFromAnchor.call(ytdFlexyElm, '.tab-btn[tyt-tab-content]')]
  6821. .map(elm => ({ elm, hidden: elm.classList.contains('tab-btn-hidden') }));
  6822.  
  6823. if (rTabSelection.length === 0) {
  6824. wAttr(ytdFlexyElm, 'tyt-tab', false);
  6825. } else {
  6826. rTabSelection = rTabSelection.filter(entry => entry.hidden !== true); // all available tabs
  6827. if (rTabSelection.length === 0) wAttr(ytdFlexyElm, 'tyt-tab', '');
  6828. }
  6829. rTabSelection = null;
  6830.  
  6831. let rEP = engagement_panels_();
  6832. if (rEP && rEP.list.length > 0) {
  6833. wAttr(ytdFlexyElm, 'tyt-ep-visible', `${rEP.value}`);
  6834. } else {
  6835. wAttr(ytdFlexyElm, 'tyt-ep-visible', false);
  6836. }
  6837.  
  6838. mtf_checkFlexy_(LAYOUT_VAILD);
  6839.  
  6840. mtoFlexyAttr.bindElement(ytdFlexyElm, {
  6841. attributes: true,
  6842. attributeFilter: [/*'tyt-ctl',*/ 'tyt-chat', 'theater', 'is-two-columns_', 'tyt-tab', 'fullscreen', 'tyt-ep-visible', 'tyt-donation-shelf', 'hidden', 'is-extra-wide-video_'],
  6843. attributeOldValue: true
  6844. })
  6845. mtoBodyAttr.bindElement(document.body, {
  6846. attributes: true,
  6847. attributeFilter: ['data-ytlstm-theater-mode'],
  6848. attributeOldValue: true
  6849. })
  6850.  
  6851. let columns = document.querySelector('ytd-page-manager#page-manager #columns.ytd-watch-flexy')
  6852. if (columns) {
  6853. wAttr(columns, 'userscript-scrollbar-render', true);
  6854. }
  6855.  
  6856. immediateCheck()
  6857.  
  6858. return false;
  6859. }
  6860.  
  6861. document.addEventListener('tabview-fix-layout', () => {
  6862.  
  6863. immediateCheck()
  6864.  
  6865. }, false)
  6866.  
  6867.  
  6868. function switchTabActivity(activeLink) {
  6869.  
  6870. //console.log(4545, activeLink)
  6871. if (!scriptEnable) return;
  6872.  
  6873. const ytdFlexyElm = es.ytdFlexy;
  6874.  
  6875. if (!ytdFlexyElm) return;
  6876.  
  6877. if (activeLink && activeLink.classList.contains('tab-btn-hidden')) return; // not allow to switch to hide tab
  6878.  
  6879. //if (isTheater() && isWideScreenWithTwoColumns()) activeLink = null;
  6880.  
  6881.  
  6882. function runAtEnd() {
  6883.  
  6884. if (activeLink) {
  6885. lstTab.lastTab = activeLink.getAttribute('tyt-tab-content')
  6886. lstTab.lastPanel = null;
  6887.  
  6888. if (!document.querySelector(`${lstTab.lastTab}.tab-content-cld tabview-view-tab-expander`)) {
  6889.  
  6890. scriptletDeferred.debounce(() => {
  6891.  
  6892. let secondary = document.querySelector('#secondary.ytd-watch-flexy');
  6893. if (secondary) {
  6894. secondary.dispatchEvent(new CustomEvent('tabview-hover-slider-restore'))
  6895. //console.log(1995)
  6896. }
  6897.  
  6898. })
  6899.  
  6900. }
  6901. }
  6902.  
  6903. const newTag = activeLink ? lstTab.lastTab : '';
  6904.  
  6905. ytdFlexyElm.setAttribute('tyt-tab', newTag)
  6906.  
  6907. if (newTag === '#tab-videos') {
  6908.  
  6909.  
  6910.  
  6911. let t = document.querySelector('#tab-videos yt-chip-cloud-renderer')
  6912. if (t) {
  6913. scriptletDeferred.debounce(() => {
  6914. t.isConnected && t.dispatchEvent(new CustomEvent('tyt-resize-chip-cloud'));
  6915. t = null;
  6916. })
  6917. }
  6918.  
  6919. }
  6920.  
  6921.  
  6922. }
  6923.  
  6924. const links = document.querySelectorAll('#material-tabs a[tyt-tab-content]');
  6925.  
  6926. //console.log(701, activeLink)
  6927.  
  6928. for (const link of links) {
  6929. let content = document.querySelector(link.getAttribute('tyt-tab-content'));
  6930. if (link && content) {
  6931. if (link !== activeLink) {
  6932. link.classList.remove("active");
  6933. content.classList.add("tab-content-hidden");
  6934. if (!content.hasAttribute("tyt-hidden")) {
  6935. content.setAttribute("tyt-hidden", ""); // for https://greasyfork.org/en/scripts/456108
  6936. }
  6937. } else {
  6938. link.classList.add("active");
  6939. if (content.hasAttribute("tyt-hidden")) {
  6940. content.removeAttribute("tyt-hidden"); // for https://greasyfork.org/en/scripts/456108
  6941. }
  6942. content.classList.remove("tab-content-hidden");
  6943. }
  6944. }
  6945. }
  6946.  
  6947. runAtEnd();
  6948.  
  6949.  
  6950. }
  6951.  
  6952.  
  6953. function getStore() {
  6954. let s = localStorage[STORE_key];
  6955. function resetStore() {
  6956. let ret = {
  6957. version: 1,
  6958. };
  6959. localStorage[STORE_key] = JSON.stringify(ret);
  6960. return ret;
  6961. }
  6962. if (!s) return resetStore();
  6963. let obj = null;
  6964. try {
  6965. obj = JSON.parse(s);
  6966. } catch (e) { }
  6967. return obj && obj.version === STORE_VERSION ? obj : resetStore();
  6968. }
  6969.  
  6970. function setStore(obj) {
  6971. if (!obj || typeof obj !== 'object') return false;
  6972. if (obj.version !== STORE_VERSION) return false;
  6973. localStorage[STORE_key] = JSON.stringify(obj);
  6974. return true;
  6975. }
  6976.  
  6977.  
  6978.  
  6979. async function handlerMaterialTabClickInner(tabBtn) {
  6980.  
  6981. await Promise.resolve(0);
  6982.  
  6983. const layoutStatusMutexUnlock = await new Promise(resolve => {
  6984. layoutStatusMutex.lockWith(unlock => {
  6985. resolve(unlock)
  6986. })
  6987. });
  6988.  
  6989. // locked
  6990. let unlock = layoutStatusMutexUnlock; // function of unlock inside layoutStatusMutex
  6991.  
  6992. //console.log(8515)
  6993. switchTabActivity_lastTab = tabBtn.getAttribute('tyt-tab-content');
  6994.  
  6995. let isActiveAndVisible = tabBtn.classList.contains('tab-btn') && tabBtn.classList.contains('active') && !tabBtn.classList.contains('tab-btn-hidden')
  6996.  
  6997. _console.log(8221, 15, isActiveAndVisible)
  6998.  
  6999. if (isFullScreen()) {
  7000.  
  7001.  
  7002. const fullScreenTabScrollIntoView = () => {
  7003. let scrollElement = document.querySelector('ytd-app[scrolling]')
  7004. if (!scrollElement) return;
  7005. // single column view; click button; scroll to tab content area 100%
  7006. let rightTabs = document.querySelector('#right-tabs');
  7007. let pTop = rightTabs.getBoundingClientRect().top - scrollElement.getBoundingClientRect().top
  7008. if (rightTabs && pTop > 0 && tabBtn.classList.contains('active')) {
  7009. rightTabs.scrollIntoView(false);
  7010. }
  7011. }
  7012.  
  7013. _console.log(8221, 16, 1)
  7014.  
  7015. if (isActiveAndVisible) {
  7016. timeline.setTimeout(unlock, 80);
  7017. switchTabActivity(null);
  7018. } else {
  7019.  
  7020. if (isChatExpand() && isWideScreenWithTwoColumns()) {
  7021. ytBtnCollapseChat();
  7022. } else if (isEngagementPanelExpanded() && isWideScreenWithTwoColumns()) {
  7023. ytBtnCloseEngagementPanels();
  7024. } else if (isDonationShelfExpanded() && isWideScreenWithTwoColumns()) {
  7025. closeDonationShelf();
  7026. }
  7027.  
  7028.  
  7029. timeline.setTimeout(fullScreenTabScrollIntoView, 60)
  7030.  
  7031. timeline.setTimeout(unlock, 80);
  7032. switchTabActivity(tabBtn)
  7033. }
  7034.  
  7035. } else if (isWideScreenWithTwoColumns() && !isTheater() && isActiveAndVisible) {
  7036.  
  7037. _console.log(8221, 16, 2)
  7038. //optional
  7039. timeline.setTimeout(unlock, 80);
  7040. switchTabActivity(null);
  7041. ytBtnSetTheater();
  7042. } else if (isActiveAndVisible) {
  7043.  
  7044. _console.log(8221, 16, 3)
  7045. timeline.setTimeout(unlock, 80);
  7046. switchTabActivity(null);
  7047. } else {
  7048.  
  7049. _console.log(8221, 16, 4)
  7050.  
  7051. if (isChatExpand() && isWideScreenWithTwoColumns()) {
  7052. ytBtnCollapseChat();
  7053. } else if (isEngagementPanelExpanded() && isWideScreenWithTwoColumns()) {
  7054. ytBtnCloseEngagementPanels();
  7055. } else if (isDonationShelfExpanded() && isWideScreenWithTwoColumns()) {
  7056. closeDonationShelf();
  7057. } else if (isWideScreenWithTwoColumns() && isTheater() && !isFullScreen()) {
  7058. ytBtnCancelTheater(); //ytd-watch-flexy attr [theater]
  7059. }
  7060.  
  7061. timeline.setTimeout(() => {
  7062. // single column view; click button; scroll to tab content area 100%
  7063. let rightTabs = document.querySelector('#right-tabs');
  7064. if (!isWideScreenWithTwoColumns() && rightTabs && rightTabs.offsetTop > 0 && tabBtn.classList.contains('active') && rightTabs.hasAttribute('tyt-stickybar')) {
  7065. let tabButtonBar = document.querySelector('#material-tabs');
  7066. let tabButtonBarHeight = tabButtonBar ? tabButtonBar.offsetHeight : 0;
  7067. window.scrollTo(0, rightTabs.offsetTop - tabButtonBarHeight); // scrollIntoView
  7068. }
  7069. }, 60)
  7070. // _console.log(8519)
  7071.  
  7072. timeline.setTimeout(unlock, 80)
  7073. switchTabActivity(tabBtn)
  7074.  
  7075. }
  7076.  
  7077.  
  7078. }
  7079.  
  7080. function handlerMaterialTabClick(/** @type {MouseEvent} */ evt) {
  7081.  
  7082. //console.log(8510)
  7083. const ytdFlexyElm = es.ytdFlexy;
  7084. if (!scriptEnable || !ytdFlexyElm) return null;
  7085.  
  7086. let tabBtn = this;
  7087.  
  7088. if (!tabBtn.hasAttribute('tyt-tab-content')) return;
  7089.  
  7090. /** @type {HTMLElement | null} */
  7091. let dom = evt.target;
  7092. if (!dom) return;
  7093.  
  7094. if (dom.classList.contains('font-size-btn')) return;
  7095.  
  7096.  
  7097. evt.preventDefault();
  7098.  
  7099. handlerMaterialTabClickInner(tabBtn);
  7100.  
  7101.  
  7102. }
  7103.  
  7104. function onVideoLeavePictureInPicuture() {
  7105. isMiniviewForStickyHeadEnabled = false;
  7106. }
  7107.  
  7108.  
  7109. let videoPlayerInsectObserver = null;
  7110. let videoInsected = false;
  7111.  
  7112.  
  7113. async function enablePIPforStickyHead() {
  7114. // use async & await to avoid handler took 60ms
  7115.  
  7116. if (!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && userActivation && typeof IntersectionObserver == 'function') {
  7117. let video = document.querySelector('#player video');
  7118. if (!video) return;
  7119.  
  7120. const vRect = video.getBoundingClientRect();
  7121. if (!( vRect.top < 0 && vRect.height > 100 && vRect.bottom < vRect.height * 0.25)) return; // avoid conflic with YouTube Mobile Mode in YouTube Live Borderless
  7122.  
  7123. await Promise.resolve(0)
  7124. const pageClientWidth = document.documentElement.clientWidth;
  7125. if (pageClientWidth + 320 < screen.width && pageClientWidth > 320 && !document.querySelector('#rCbM3')) {
  7126.  
  7127.  
  7128. await Promise.resolve(0)
  7129. // desktop or notebook can use this feature
  7130.  
  7131. // --------------------------------------------------------
  7132. // ignore user activation error
  7133. enterPIP(video, null).then(r => {
  7134. if (r === true) {
  7135.  
  7136. userActivation = false;
  7137. isMiniviewForStickyHeadEnabled = true;
  7138. }
  7139. });
  7140. // --------------------------------------------------------
  7141. video.removeEventListener('leavepictureinpicture', onVideoLeavePictureInPicuture, false);
  7142. video.addEventListener('leavepictureinpicture', onVideoLeavePictureInPicuture, false);
  7143.  
  7144. if (!video.hasAttribute('NOL4j')) {
  7145. video.setAttribute('NOL4j', "");
  7146.  
  7147.  
  7148. await Promise.resolve(0)
  7149.  
  7150. let callback = (entries) => {
  7151.  
  7152.  
  7153. let lastEntry = entries[entries.length - 1];
  7154. if (lastEntry && lastEntry.isIntersecting === true) {
  7155.  
  7156. videoInsected = true;
  7157.  
  7158. if (isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation && videoInsected) {
  7159. restorePIPforStickyHead();
  7160. }
  7161.  
  7162. } else {
  7163. videoInsected = false;
  7164. }
  7165.  
  7166. };
  7167.  
  7168. if (!videoPlayerInsectObserver) {
  7169. videoPlayerInsectObserver = new IntersectionObserver(callback, {
  7170. root: null,
  7171. rootMargin: "0px",
  7172. threshold: 0.25
  7173. });
  7174. }
  7175.  
  7176. videoPlayerInsectObserver.takeRecords();
  7177. videoPlayerInsectObserver.disconnect();
  7178.  
  7179. videoPlayerInsectObserver.observe(video);
  7180.  
  7181.  
  7182. }
  7183.  
  7184. }
  7185. }
  7186. }
  7187.  
  7188. function setStickyHeader(targetElm, bool, getWidthHeight, getLeftRight) {
  7189.  
  7190. //if(isStickyHeaderEnabled===bool) return; // no update
  7191.  
  7192. if (bool === true) {
  7193. const { width, height } = getWidthHeight();
  7194. targetElm.style.setProperty("--tyt-stickybar-w", width + 'px')
  7195. targetElm.style.setProperty("--tyt-stickybar-h", height + 'px')
  7196. const res = getLeftRight();
  7197. if (res) {
  7198.  
  7199. targetElm.style.setProperty("--tyt-stickybar-l", (res.left) + 'px')
  7200. targetElm.style.setProperty("--tyt-stickybar-r", (res.right) + 'px')
  7201.  
  7202. }
  7203. wAttr(targetElm, 'tyt-stickybar', true);
  7204. isStickyHeaderEnabled = true;
  7205.  
  7206. if (!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && userActivation && typeof IntersectionObserver == 'function') {
  7207. setTimeout(enablePIPforStickyHead, 0);
  7208. }
  7209.  
  7210. } else if (bool === false) {
  7211.  
  7212. wAttr(targetElm, 'tyt-stickybar', false);
  7213. isStickyHeaderEnabled = false;
  7214.  
  7215.  
  7216. }
  7217.  
  7218.  
  7219. }
  7220.  
  7221. const singleColumnScrolling = async function () {
  7222. //makeHeaderFloat
  7223. // required for 1) init 2) layout change 3) resizing
  7224.  
  7225. if (!scriptEnable || pageType !== 'watch') return;
  7226.  
  7227.  
  7228. let isTwoCol = (wls.layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS;
  7229. if (isTwoCol) {
  7230.  
  7231. if (isStickyHeaderEnabled) {
  7232.  
  7233. let targetElm = document.querySelector("#right-tabs");
  7234. setStickyHeader(targetElm, false, null, null);
  7235. }
  7236. return;
  7237. }
  7238.  
  7239. let pageY = scrollY;
  7240.  
  7241.  
  7242. let tdt = Date.now();
  7243. singleColumnScrolling_dt = tdt;
  7244.  
  7245.  
  7246. _console.log(7891, 'scrolling')
  7247.  
  7248. function getXYStatus(res) {
  7249.  
  7250. const [navHeight, elmY] = res;
  7251.  
  7252. let xyz = [elmY + navHeight, pageY, elmY - navHeight]
  7253.  
  7254. let xyStatus = 0
  7255. if (xyz[1] < xyz[2] && xyz[2] < xyz[0]) {
  7256. // 1
  7257. xyStatus = 1
  7258. }
  7259.  
  7260. if (xyz[0] > xyz[1] && xyz[1] > xyz[2]) {
  7261.  
  7262. //2
  7263. xyStatus = 2
  7264.  
  7265. }
  7266.  
  7267. if (xyz[2] < xyz[0] && xyz[0] < xyz[1]) {
  7268. // 3
  7269.  
  7270. xyStatus = 3
  7271.  
  7272.  
  7273. }
  7274.  
  7275. return xyStatus;
  7276. }
  7277.  
  7278. let [targetElm, header, navElm] = await Promise.all([
  7279. Promise.resolve().then(() => document.querySelector("#right-tabs")),
  7280.  
  7281. Promise.resolve().then(() => document.querySelector("#right-tabs header")),
  7282.  
  7283. Promise.resolve().then(() => document.querySelector('#masthead-container, #masthead')),
  7284.  
  7285. ]);
  7286.  
  7287. function emptyForGC() {
  7288. targetElm = null;
  7289. header = null;
  7290. navElm = null;
  7291. }
  7292.  
  7293. if (!targetElm || !header) {
  7294. return emptyForGC();
  7295. }
  7296. if (singleColumnScrolling_dt !== tdt) return emptyForGC();
  7297.  
  7298. let res2 = await Promise.all([
  7299. Promise.resolve().then(() => navElm ? navElm.offsetHeight : 0),
  7300. Promise.resolve().then(() => targetElm.offsetTop)
  7301. ])
  7302.  
  7303. if (res2 === null) return emptyForGC();
  7304.  
  7305. if (singleColumnScrolling_dt !== tdt) return emptyForGC();
  7306.  
  7307.  
  7308. const xyStatus = getXYStatus(res2);
  7309.  
  7310.  
  7311. function getLeftRight() {
  7312.  
  7313. let thp = document.querySelector('tabview-view-pos-thead');
  7314. if (thp) {
  7315.  
  7316. let rect = thp.getBoundingClientRect()
  7317. if (rect) {
  7318. return {
  7319. left: rect.left,
  7320. right: document.documentElement.clientWidth - rect.right
  7321. };
  7322. }
  7323. }
  7324. return null;
  7325. }
  7326.  
  7327. let bool = (xyStatus == 2 || xyStatus == 3) ? true : ((xyStatus == 1) ? false : null);
  7328.  
  7329. function getWidthHeight() {
  7330. return { width: targetElm.offsetWidth, height: header.offsetHeight };
  7331. }
  7332.  
  7333. setStickyHeader(targetElm, bool, getWidthHeight, getLeftRight);
  7334.  
  7335.  
  7336. emptyForGC();
  7337.  
  7338. };
  7339.  
  7340.  
  7341. const singleColumnScrolling2 = async function (xyStatus, width, xRect) {
  7342. //makeHeaderFloat
  7343.  
  7344. if (!scriptEnable || pageType !== 'watch') return;
  7345.  
  7346.  
  7347. if ((wls.layoutStatus & LAYOUT_TWO_COLUMNS) === LAYOUT_TWO_COLUMNS) {
  7348. return;
  7349. }
  7350.  
  7351. let [targetElm, header] = await Promise.all([
  7352. Promise.resolve().then(() => document.querySelector("#right-tabs")),
  7353. Promise.resolve().then(() => document.querySelector("#right-tabs header"))
  7354. ]);
  7355.  
  7356. function emptyForGC() {
  7357. targetElm = null;
  7358. header = null;
  7359. }
  7360.  
  7361.  
  7362. if (!targetElm || !header) {
  7363. return emptyForGC();
  7364. }
  7365.  
  7366. function getLeftRight() {
  7367. return xRect;
  7368. }
  7369.  
  7370. let bool = (xyStatus == 2 || xyStatus == 3) ? true : ((xyStatus == 1) ? false : null);
  7371.  
  7372. function getWidthHeight() {
  7373. return { width: (width || targetElm.offsetWidth), height: header.offsetHeight };
  7374. }
  7375.  
  7376. setStickyHeader(targetElm, bool, getWidthHeight, getLeftRight);
  7377.  
  7378. emptyForGC();
  7379.  
  7380. };
  7381.  
  7382.  
  7383. function resetBuggyLayoutForNewVideoPage() {
  7384.  
  7385. const ytdFlexyElm = es.ytdFlexy;
  7386. if (!ytdFlexyElm) return;
  7387.  
  7388. //(flexy is visible and watch video page)
  7389.  
  7390. scriptEnable = true;
  7391.  
  7392. _console.log(27056)
  7393.  
  7394. let new_layoutStatus = wls.layoutStatus
  7395.  
  7396. new_layoutStatus & (LAYOUT_CHATROOM_COLLAPSED | LAYOUT_CHATROOM)
  7397.  
  7398. const new_isExpandedChat = !(new_layoutStatus & LAYOUT_CHATROOM_COLLAPSED) && !!(new_layoutStatus & LAYOUT_CHATROOM)
  7399. const new_isCollapsedChat = !!(new_layoutStatus & LAYOUT_CHATROOM_COLLAPSED) && !!(new_layoutStatus & LAYOUT_CHATROOM)
  7400.  
  7401. const new_isTwoColumns = new_layoutStatus & LAYOUT_TWO_COLUMNS;
  7402. const new_isTheater = new_layoutStatus & LAYOUT_THEATER;
  7403. const new_isTabExpanded = new_layoutStatus & LAYOUT_TAB_EXPANDED;
  7404. const new_isFullScreen = new_layoutStatus & LAYOUT_FULLSCREEN;
  7405. const new_isExpandedEPanel = new_layoutStatus & LAYOUT_ENGAGEMENT_PANEL_EXPANDED;
  7406. const new_isExpandedDonationShelf = new_layoutStatus & LAYOUT_DONATION_SHELF_EXPANDED;
  7407.  
  7408. const nothingShown = !new_isTabExpanded && !new_isExpandedChat && !new_isExpandedEPanel && !new_isExpandedDonationShelf
  7409.  
  7410. if (ytdFlexyElm.getAttribute('tyt-tab') === '' && new_isTwoColumns && !new_isTheater && nothingShown && !new_isFullScreen) {
  7411. // e.g. engage panel removed after miniview and change video
  7412. setToActiveTab();
  7413. } 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) {
  7414. wls.layoutStatus = new_layoutStatus & (~LAYOUT_ENGAGEMENT_PANEL_EXPANDED)
  7415. } else if (new_isExpandedDonationShelf && querySelectorAllFromAnchor.call(ytdFlexyElm, 'ytd-donation-shelf-renderer.ytd-watch-flexy:not([hidden])').length === 0) {
  7416. wls.layoutStatus = new_layoutStatus & (~LAYOUT_DONATION_SHELF_EXPANDED)
  7417. }
  7418.  
  7419. }
  7420.  
  7421.  
  7422. function extractInfoFromLiveChatRenderer(liveChatRenderer) {
  7423.  
  7424. let lcr = liveChatRenderer
  7425.  
  7426. let data_shb = ((lcr || 0).showHideButton || 0).toggleButtonRenderer
  7427.  
  7428. let default_display_state = null, txt_collapse = null, txt_expand = null;
  7429.  
  7430.  
  7431. if (data_shb && data_shb.defaultText && data_shb.toggledText && data_shb.defaultText.runs && data_shb.toggledText.runs) {
  7432.  
  7433. if (data_shb.defaultText.runs.length === 1 && data_shb.toggledText.runs.length === 1) {
  7434.  
  7435. if (lcr.initialDisplayState == "LIVE_CHAT_DISPLAY_STATE_EXPANDED") {
  7436.  
  7437. default_display_state = lcr.initialDisplayState
  7438.  
  7439. txt_collapse = (data_shb.defaultText.runs[0] || 0).text // COLLAPSE the area
  7440.  
  7441. txt_expand = (data_shb.toggledText.runs[0] || 0).text // expand the area
  7442.  
  7443. } else if (lcr.initialDisplayState == "LIVE_CHAT_DISPLAY_STATE_COLLAPSED") {
  7444. default_display_state = lcr.initialDisplayState
  7445.  
  7446. txt_expand = (data_shb.defaultText.runs[0] || 0).text // expand the area
  7447.  
  7448. txt_collapse = (data_shb.toggledText.runs[0] || 0).text // COLLAPSE the area
  7449. }
  7450.  
  7451.  
  7452. if (typeof txt_expand == 'string' && typeof txt_collapse == 'string' && txt_expand.length > 0 && txt_collapse.length > 0) {
  7453.  
  7454. } else {
  7455. txt_expand = null;
  7456. txt_collapse = null;
  7457. }
  7458. }
  7459.  
  7460. }
  7461.  
  7462. return { default_display_state, txt_collapse, txt_expand }
  7463.  
  7464. }
  7465.  
  7466. const dpeChatRefreshCounter = ControllerID();
  7467. // let proceedingChatFrameVideoID = '';
  7468. let newVideoPageCACC = -1;
  7469. let mvideoState = 0;
  7470.  
  7471. function newVideoPage(evt_detail) {
  7472.  
  7473. //toggleBtnDC = 1;
  7474.  
  7475. console.debug('[tyt] newVideoPage');
  7476. // Promise.resolve().then(setupVideoTitleHover);
  7477. mvideoState = 0;
  7478. // console.debug('[tyt] debug ym-01-0')
  7479.  
  7480. const ytdFlexyElm = es.ytdFlexy;
  7481. if (!ytdFlexyElm) return;
  7482.  
  7483. timeline.reset();
  7484. layoutStatusMutex = new Mutex();
  7485.  
  7486. let liveChatRenderer = null;
  7487. let isReplay = null;
  7488.  
  7489. if (pageType !== 'watch') return; // scriptEnable -> pageType shall be always 'watch'
  7490. resetBuggyLayoutForNewVideoPage();
  7491.  
  7492. try {
  7493. liveChatRenderer = evt_detail.pageData.response.contents.twoColumnWatchNextResults.conversationBar.liveChatRenderer
  7494. } catch (e) { }
  7495. if (liveChatRenderer) {
  7496. if (liveChatRenderer.isReplay === true) isReplay = true;
  7497. }
  7498.  
  7499. pageFetchedDataVideoId = ((((evt_detail || 0).pageData || 0).playerResponse || 0).videoDetails || 0).videoId || 0;
  7500.  
  7501.  
  7502. const fvid = pageFetchedDataVideoId;
  7503. const tyid = dpeChatRefreshCounter();
  7504. // proceedingChatFrameVideoID = '';
  7505. newVideoPageCACC = chatroomAttrCollapseCount;
  7506. // console.debug('[tyt] debug ym-01-1')
  7507. const rootDom = document.documentElement;
  7508. rootDom.setAttribute('sxmq8', rootDom.getAttribute('sxmq8') === '1' ? '0' : '1');
  7509. setTimeout(() => {
  7510. const rootDom = document.documentElement;
  7511. rootDom.setAttribute('sxmq8', rootDom.getAttribute('sxmq8') === '1' ? '0' : '1');
  7512. // console.debug('[tyt] debug ym-01-2')
  7513. if (fvid !== pageFetchedDataVideoId) return;
  7514. // console.debug('[tyt] debug ym-01-3')
  7515. if (tyid !== +dpeChatRefreshCounter) return;
  7516. // console.debug('[tyt] debug ym-01-4')
  7517. dpeChatRefreshCounter();
  7518. const chat = document.querySelector('ytd-live-chat-frame#chat');
  7519. if (chat && !chat.hasAttribute('collapsed')) {
  7520. // proceedingChatFrameVideoID = fvid;
  7521. // console.debug('[tyt] debug ym-01-5')
  7522. // dpeNewUrlChat(chat); // force replace url
  7523. const iframe = querySelectorFromAnchor.call(chat, 'body iframe.style-scope.ytd-live-chat-frame#chatframe');
  7524. // console.log("iframe.xx",501,iframe)
  7525. if (iframe) iframeLoadProcess(iframe); // fix empty
  7526.  
  7527. }
  7528. }, 67);
  7529.  
  7530.  
  7531. const chatBlockR = liveChatRenderer ? (isReplay ? 3 : 1) : 0
  7532. const initialDisplayState = liveChatRenderer ? liveChatRenderer.initialDisplayState : null;
  7533.  
  7534.  
  7535. liveChatRenderer = null; // release memory for GC, just in case
  7536.  
  7537. let f = () => {
  7538.  
  7539. _console.log(932, 1, 1)
  7540. const ytdFlexyElm = es.ytdFlexy;
  7541. if (!scriptEnable || !ytdFlexyElm) return;
  7542.  
  7543. _console.log(932, 1, 2)
  7544. if (pageType !== 'watch') return;
  7545.  
  7546. _console.log(932, 1, 3)
  7547.  
  7548.  
  7549. let displayState = setupChatFrameDisplayState1(chatBlockR, initialDisplayState);
  7550.  
  7551. let { attr_chatblock, attr_chatcollapsed, chatTypeChanged } = displayState;
  7552.  
  7553.  
  7554. if (pageType === 'watch') { // reset info when hidden
  7555.  
  7556. let elm_storeLastPanel = es.storeLastPanel;
  7557.  
  7558. if (!elm_storeLastPanel) storeLastPanel = null;
  7559. else if (!isDOMVisible(elm_storeLastPanel)) {
  7560. storeLastPanel = null;
  7561. ytBtnCloseEngagementPanels();
  7562. }
  7563.  
  7564. }
  7565.  
  7566. if (chatTypeChanged) {
  7567.  
  7568. if (attr_chatblock == 'chat$live') {
  7569.  
  7570. _console.log(932, 4)
  7571.  
  7572. mtf_forceCheckLiveVideo_disable = 2;
  7573.  
  7574. //console.log(3712,1)
  7575.  
  7576. _disableComments();
  7577.  
  7578.  
  7579. } else {
  7580.  
  7581. const tabBtn = document.querySelector('[tyt-tab-content="#tab-comments"].tab-btn-hidden')
  7582. if (tabBtn) {
  7583. emptyCommentSection();
  7584. _console.log(9360, 74);
  7585. setTabBtnVisible(tabBtn, true);
  7586. } else {
  7587. setCommentSection(0);
  7588. }
  7589.  
  7590. mtf_forceCheckLiveVideo_disable = 0;
  7591.  
  7592. _console.log(7234, 'comments_section_loaded = 0')
  7593. restoreFetching();
  7594.  
  7595.  
  7596. }
  7597.  
  7598.  
  7599. } else {
  7600.  
  7601. // restore Fetching only
  7602.  
  7603. if (mtf_forceCheckLiveVideo_disable !== 2 && (attr_chatblock === false || attr_chatblock === 'chat$playback')) {
  7604.  
  7605. emptyCommentSection();
  7606. _console.log(9360, 77);
  7607. mtf_forceCheckLiveVideo_disable = 0;
  7608. _console.log(7235, 'comments_section_loaded = 0')
  7609. restoreFetching();
  7610.  
  7611. }
  7612.  
  7613. }
  7614.  
  7615.  
  7616. checkAndMakeNewCommentFetch();
  7617.  
  7618. }
  7619.  
  7620. f();
  7621.  
  7622. }
  7623.  
  7624. function setVideosTwoColumns(/** @type {number} */ flag, /** @type {boolean} */ bool) {
  7625.  
  7626. //two columns to one column
  7627.  
  7628. /*
  7629. [placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy
  7630.  
  7631. is-two-columns ="" => no is-two-columns
  7632. [placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer
  7633. no hidden => hidden =""
  7634. [placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer
  7635. hidden ="" => no hidden
  7636.  
  7637. */
  7638.  
  7639. let cssSelector1 = '[placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy'
  7640.  
  7641. let cssSelector2 = '[placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer'
  7642.  
  7643. let cssSelector3 = '[placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer'
  7644.  
  7645. let res = {}
  7646. if (flag & 1) {
  7647. res.m1 = document.querySelector(cssSelector1)
  7648. if (res.m1) wAttr(res.m1, 'is-two-columns', bool ? '' : false);
  7649. }
  7650.  
  7651. if (flag & 2) {
  7652. res.m2 = document.querySelector(cssSelector2)
  7653. if (res.m2) wAttr(res.m2, 'hidden', bool ? false : '');
  7654. }
  7655.  
  7656. if (flag & 4) {
  7657. res.m3 = document.querySelector(cssSelector3)
  7658. if (res.m3) wAttr(res.m3, 'hidden', bool ? '' : false);
  7659. }
  7660.  
  7661. return res
  7662.  
  7663.  
  7664. }
  7665.  
  7666.  
  7667. // ---------------------------------------------------------------------------------------------
  7668.  
  7669. // ---- EVENTS ----
  7670.  
  7671. let ytEventSequence = 0
  7672. let formatDates = null
  7673.  
  7674. function setupFormatDates(pageFetchedDataLocal) {
  7675.  
  7676. formatDates = {}
  7677. try {
  7678. formatDates.publishDate = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.publishDate
  7679. } catch (e) { }
  7680. // 2022-12-30
  7681.  
  7682. try {
  7683. formatDates.uploadDate = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.uploadDate
  7684. } catch (e) { }
  7685. // 2022-12-30
  7686.  
  7687. try {
  7688. formatDates.publishDate2 = pageFetchedDataLocal.pageData.response.contents.twoColumnWatchNextResults.results.results.contents[0].videoPrimaryInfoRenderer.dateText.simpleText
  7689. } catch (e) { }
  7690. // 2022/12/31
  7691.  
  7692. if (typeof formatDates.publishDate2 === 'string' && formatDates.publishDate2 !== formatDates.publishDate) {
  7693. formatDates.publishDate = formatDates.publishDate2
  7694. formatDates.uploadDate = null
  7695. }
  7696.  
  7697. try {
  7698. formatDates.broadcastBeginAt = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.liveBroadcastDetails.startTimestamp
  7699. } catch (e) { }
  7700. try {
  7701. formatDates.broadcastEndAt = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.liveBroadcastDetails.endTimestamp
  7702. } catch (e) { }
  7703. try {
  7704. formatDates.isLiveNow = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.liveBroadcastDetails.isLiveNow
  7705. } catch (e) { }
  7706.  
  7707. }
  7708.  
  7709. function pageBeingFetched(evt) {
  7710.  
  7711. let nodeName = (((evt || 0).target || 0).nodeName || '').toUpperCase()
  7712. if (nodeName !== 'YTD-APP') return;
  7713.  
  7714. const pageFetchedDataLocal = evt.detail;
  7715.  
  7716. let d_page = ((pageFetchedDataLocal || 0).pageData || 0).page;
  7717. if (!d_page) return;
  7718.  
  7719. pageType = d_page;
  7720.  
  7721. if (pageType !== 'watch') return
  7722.  
  7723. let isFirstLoad = firstLoadStatus & 8;
  7724.  
  7725. if (isFirstLoad) {
  7726. firstLoadStatus -= 8;
  7727. for (const iframe of document.querySelectorAll('body iframe.style-scope.ytd-live-chat-frame#chatframe')) {
  7728. Promise.resolve(iframe).then(iframeLoadProcess); // fix empty
  7729. }
  7730. // document.addEventListener('load', iframeLoadHookHandler, capturePassive);
  7731. ytMicroEventsInit();
  7732. }
  7733. // ytMicroEventsInit set
  7734. variableResets();
  7735.  
  7736. if (isFirstLoad && ytEventSequence >= 2) {
  7737.  
  7738. scriptletDeferred.debounce(() => {
  7739.  
  7740. let docElement = document.documentElement
  7741. if (docElement.hasAttribute('tabview-loaded')) {
  7742. throw 'Tabview Youtube Duplicated';
  7743. }
  7744. docElement.setAttribute('tabview-loaded', '')
  7745.  
  7746. Promise.resolve(docElement).then(docElement => {
  7747. if (ytEventSequence >= 2) {
  7748. docElement.dispatchEvent(new CustomEvent('tabview-ce-hack'))
  7749. docElement = null
  7750. }
  7751. });
  7752.  
  7753. });
  7754.  
  7755. }
  7756. // tabview-loaded delay set
  7757.  
  7758. setupFormatDates(pageFetchedDataLocal);
  7759. const promiseChatDetails = Promise.resolve(pageFetchedDataLocal).then((pageFetchedDataLocal) => {
  7760. if (ytEventSequence >= 2) {
  7761. let liveChatRenderer = null;
  7762. try {
  7763. liveChatRenderer = pageFetchedDataLocal.pageData.response.contents.twoColumnWatchNextResults.conversationBar.liveChatRenderer
  7764. } catch (e) { }
  7765. chatroomDetails = liveChatRenderer ? extractInfoFromLiveChatRenderer(liveChatRenderer) : null;
  7766. }
  7767. }).then();
  7768.  
  7769.  
  7770. let tmpElm = es.ytdFlexy;
  7771. if (tmpElm && tmpElm.isConnected === true && tmpElm.nodeName.toLowerCase() === 'ytd-watch-flexy') {
  7772. // currently, tmpElm is null; to be reviewed
  7773. } else {
  7774. // update global ref
  7775. ytdFlexy = mWeakRef(document.querySelector('ytd-watch-flexy:not([hidden])') || document.querySelector('ytd-watch-flexy'));
  7776. }
  7777. tmpElm = null;
  7778.  
  7779. if (!es.ytdFlexy) return;
  7780.  
  7781. Promise.resolve(0).then(() => {
  7782.  
  7783. const ytdFlexyElm = es.ytdFlexy; // shall be always non-null
  7784.  
  7785. if (ytEventSequence >= 2 && pageRendered === 0 && ytdFlexyElm && ytdFlexyElm.isConnected === true) {
  7786.  
  7787. // trigger renderDeferred.resolve();
  7788. let elmPL = document.createElement('tabview-view-ploader');
  7789. pageRendered = 1;
  7790. // ytdFlexyElm.appendChild(elmPL);
  7791. elementAppend.call(ytdFlexyElm, elmPL);
  7792. // pageRendered keeps at 1 if the video is continuously playing at the background
  7793. // pageRendered would not be resolve but will reset for each change of video
  7794.  
  7795. } else if (ytEventSequence >= 2 && pageRendered === 1 && ytdFlexyElm && ytdFlexyElm.isConnected === true) {
  7796. // 511, [3, 1, true]
  7797. } else {
  7798. console.warn(511, [ytEventSequence, pageRendered, !!ytdFlexyElm])
  7799. }
  7800.  
  7801. });
  7802.  
  7803. let _pageFetchedDataLocal = pageFetchedDataLocal;
  7804. promiseChatDetails.then(() => {
  7805.  
  7806. const ytdFlexyElm = es.ytdFlexy;
  7807. if (ytEventSequence >= 2 && ytdFlexyElm) {
  7808. ytdFlexyElm.classList.toggle('tyt-chat-toggleable', !!chatroomDetails);
  7809. }
  7810.  
  7811. if (ytEventSequence >= 2) {
  7812.  
  7813. discardableFn(() => { // assume tyt-deferred
  7814.  
  7815. const pageFetchedDataLocal = _pageFetchedDataLocal;
  7816. _pageFetchedDataLocal = null;
  7817. if (ytEventSequence >= 2 && pageFetchedDataLocal !== null) {
  7818. domInit_comments();
  7819. newVideoPage(pageFetchedDataLocal);
  7820. }
  7821.  
  7822. });
  7823.  
  7824. }
  7825.  
  7826. });
  7827.  
  7828. }
  7829.  
  7830. let pageSeqMutex = new Mutex()
  7831.  
  7832. function pageSeq1(evt) {
  7833. _navigateLoadDT = 0
  7834. if (ytEventSequence !== 1) {
  7835. ytEventSequence = 1
  7836. pageSeqMutex.lockWith(unlock => {
  7837. // regardless pageType
  7838. pageBeingInit();
  7839. unlock();
  7840. })
  7841. }
  7842. }
  7843.  
  7844. function pageSeq2(evt) {
  7845. _navigateLoadDT = 0;
  7846.  
  7847. if (ytEventSequence !== 1) {
  7848. ytEventSequence = 1;
  7849. pageSeqMutex.lockWith(unlock => {
  7850. // regardless pageType
  7851. pageBeingInit();
  7852. unlock();
  7853. })
  7854. }
  7855. if (ytEventSequence === 1) {
  7856. ytEventSequence = 2;
  7857.  
  7858. pageType = null;
  7859.  
  7860. pageSeqMutex.lockWith(unlock => {
  7861. // regardless pageType
  7862.  
  7863. pageType = null;
  7864. pageBeingFetched(evt);
  7865. // ytMicroEventsInit set + tabview-loaded delay set
  7866.  
  7867. if (pageType !== 'watch') {
  7868. ytdFlexy = null;
  7869. chatroomDetails = null;
  7870. }
  7871.  
  7872. Promise.resolve().then(() => {
  7873. const isWatch = pageType === 'watch';
  7874. const isEventSeqOK = ytEventSequence >= 2;
  7875. if (!isWatch) {
  7876. ytdFlexy = null;
  7877. chatroomDetails = null;
  7878. }
  7879. if (!isWatch && isEventSeqOK) {
  7880. variableResets();
  7881. emptyCommentSection();
  7882. tabsDeferred.reset();
  7883. _pageBeingInit();
  7884. tabsDeferred.resolve(); // for page initialization
  7885. }
  7886. if (isEventSeqOK) {
  7887. document.documentElement.classList.toggle('tabview-normal-player', isWatch);
  7888. }
  7889. });
  7890.  
  7891. if (_updateTimeAccum > 0) {
  7892. const currentVideo = document.querySelector('#movie_player video[src]')
  7893. let keep_viTime = false
  7894. if (currentVideo && currentVideo.readyState > currentVideo.HAVE_CURRENT_DATA && currentVideo.currentTime > 2.2) {
  7895. // allow miniview browsing
  7896. keep_viTime = true
  7897. }
  7898. if (!keep_viTime) {
  7899. _viTimeNum = 200;
  7900. _updateTimeAccum = 0;
  7901. delete document.head.dataset.viTime;
  7902. }
  7903. }
  7904.  
  7905. unlock();
  7906. })
  7907. }
  7908.  
  7909. }
  7910.  
  7911. function pageSeq3(evt) {
  7912. _navigateLoadDT = 0
  7913.  
  7914. if (ytEventSequence === 2) {
  7915. ytEventSequence = 3
  7916.  
  7917. pageSeqMutex.lockWith(unlock => {
  7918. if (pageType === 'watch') {
  7919. // ytMicroEventsInit set + tabview-loaded delay set
  7920. onNavigationEndAsync();
  7921. }
  7922.  
  7923.  
  7924. unlock();
  7925. })
  7926. }
  7927. }
  7928.  
  7929.  
  7930. document.addEventListener('yt-navigate-start', pageSeq1, bubblePassive)
  7931. document.addEventListener('yt-navigate-cache', pageSeq1, bubblePassive)
  7932. document.addEventListener('yt-navigate-redirect', pageSeq1, bubblePassive)
  7933. document.addEventListener('yt-page-data-fetched', pageSeq2, bubblePassive)
  7934. document.addEventListener("yt-navigate-finish", pageSeq3, bubblePassive)
  7935. //yt-navigate-redirect
  7936. //yt-page-data-fetched
  7937. //yt-navigate-error
  7938. //yt-navigate-start
  7939. //yt-page-manager-navigate-start
  7940. //yt-navigate
  7941. //yt-navigate-cache
  7942.  
  7943. globalHook('yt-page-data-fetched', generalLog901)
  7944. //globalHook('yt-rendererstamper-finished',generalLog901)
  7945. globalHook('yt-page-data-updated', generalLog901)
  7946. globalHook('yt-player-updated', generalLog901)
  7947. globalHook('yt-watch-comments-ready', generalLog901)
  7948. globalHook('yt-page-type-changed', generalLog901)
  7949. globalHook('data-changed', generalLog901)
  7950. globalHook('yt-navigate-finish', generalLog901)
  7951. globalHook('yt-navigate-redirect', generalLog901)
  7952. globalHook('yt-navigate-error', generalLog901)
  7953. globalHook('yt-navigate-start', generalLog901)
  7954. globalHook('yt-page-manager-navigate-start', generalLog901)
  7955. globalHook('yt-navigate', generalLog901)
  7956. globalHook('yt-navigate-cache', generalLog901)
  7957.  
  7958.  
  7959. // ---------------------------------------------------------------------------------------------
  7960.  
  7961.  
  7962. function manualResizeT() {
  7963.  
  7964. if (!scriptEnable) return;
  7965. if (pageType !== 'watch') return;
  7966. //lastResizeAt = Date.now();
  7967.  
  7968. if ((wls.layoutStatus & LAYOUT_FULLSCREEN) === LAYOUT_FULLSCREEN) {
  7969.  
  7970. } else if ((wls.layoutStatus & LAYOUT_TWO_COLUMNS) === 0) {
  7971. // single col
  7972.  
  7973. setTimeout3(() => {
  7974. singleColumnScrolling(true)
  7975. })
  7976.  
  7977. } else {
  7978. // two cols
  7979.  
  7980. updateFloatingSlider();
  7981.  
  7982. }
  7983.  
  7984.  
  7985. }
  7986. //let lastResizeAt = 0;
  7987. const resizeCount = ControllerID();
  7988. window.addEventListener('resize', function (evt) {
  7989.  
  7990. if (evt.isTrusted === true) {
  7991. //console.log(evt)
  7992. let tcw = resizeCount();
  7993. Promise.resolve(0).then(() => {
  7994. if (tcw !== +resizeCount) return;
  7995. setTimeout(() => {
  7996. // avoid duplicate calling during resizing
  7997. if (tcw !== +resizeCount) return;
  7998.  
  7999. resizeCount.set(0);
  8000. manualResizeT();
  8001. dispatchCommentRowResize();
  8002. }, 160);
  8003. });
  8004. }
  8005.  
  8006. }, bubblePassive)
  8007.  
  8008.  
  8009. document.addEventListener("tyt-chat-popup", (evt) => {
  8010.  
  8011. let detail = (evt || 0).detail
  8012. if (!detail) return
  8013. const { popuped } = detail
  8014. if (typeof popuped !== 'boolean') return;
  8015.  
  8016. let ytdFlexyElm = es.ytdFlexy
  8017. if (!ytdFlexyElm) return
  8018.  
  8019. ytdFlexyElm.classList.toggle('tyt-chat-popup', popuped)
  8020. if (popuped === true) {
  8021. enableLivePopupCheck = true;
  8022. ytBtnSetTheater()
  8023. } else {
  8024. enableLivePopupCheck = false;
  8025. ytBtnCancelTheater()
  8026. }
  8027.  
  8028. })
  8029.  
  8030.  
  8031.  
  8032. let doingSelectionChange = false;
  8033. document.addEventListener("keyup", (evt) => {
  8034. if (!evt || !evt.target || !evt.key) return;
  8035. if (doingSelectionChange) {
  8036. if (!evt.shiftKey || evt.key.indexOf("Shift") == 0) {
  8037. doingSelectionChange = false;
  8038. }
  8039. }
  8040. })
  8041.  
  8042. document.addEventListener("keydown", (evt) => {
  8043. if (!evt || !evt.target || !evt.key) return;
  8044. if (evt.shiftKey && evt.key.indexOf("Arrow") == 0) {
  8045. try {
  8046. if (doingSelectionChange || !window.getSelection().isCollapsed) {
  8047. evt.stopImmediatePropagation();
  8048. evt.stopPropagation();
  8049. doingSelectionChange = true;
  8050. }
  8051.  
  8052. } catch (e) {
  8053.  
  8054. }
  8055. }
  8056. }, true);
  8057.  
  8058. let userActivation = false;
  8059.  
  8060. document.addEventListener('click', function () {
  8061. userActivation = true;
  8062.  
  8063.  
  8064. if (isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation && videoInsected) {
  8065. setTimeout(delayedClickHandler, 80);
  8066. }
  8067.  
  8068. // if(isMiniviewForStickyHeadEnabled && !isStickyHeaderEnabled && userActivation){
  8069. // setTimeout(restorePIPforStickyHead, 80);
  8070. // }else if(!isMiniviewForStickyHeadEnabled && isStickyHeaderEnabled && userActivation && typeof IntersectionObserver == 'function'){
  8071. // setTimeout(enablePIPforStickyHead, 80);
  8072. // }
  8073. });
  8074.  
  8075. // new comment count fetch way
  8076. document.addEventListener('ytd-comments-data-changed', function (evt) {
  8077. const hasData = (evt.detail || 0).hasData;
  8078. if (hasData === false) {
  8079. // this is much effective to clear the counting text
  8080. emptyCommentSection();
  8081. }
  8082. innerDOMCommentsCountLoader(true);
  8083. checkAndMakeNewCommentFetch();
  8084. }, true);
  8085.  
  8086. document.addEventListener('ytd-comments-header-changed', function () {
  8087. const res = innerDOMCommentsCountLoader(true);
  8088. if (res && res.newFound === true && res.length === 1 && res[0].isLatest && res[0].isNew) {
  8089. if (renderDeferred.resolved && fetchCounts.new) {
  8090. // force refresh count dom
  8091. fetchCounts.fetched = false;
  8092. Q.comments_section_loaded = 0;
  8093. }
  8094. }
  8095. checkAndMakeNewCommentFetch();
  8096. }, true);
  8097.  
  8098. document.addEventListener("tabview-plugin-loaded", () => {
  8099.  
  8100. scriptletDeferred.resolve();
  8101.  
  8102. if (MINIVIEW_BROWSER_ENABLE) {
  8103. document.dispatchEvent(new CustomEvent("tabview-miniview-browser-enable"));
  8104. }
  8105.  
  8106.  
  8107. }, false)
  8108.  
  8109. if (isGMAvailable() && typeof GM_registerMenuCommand === 'function') {
  8110.  
  8111. let dialog = null;
  8112. function createDialog() {
  8113.  
  8114. const _themeProps_ = {
  8115. dialogBackgroundColor: '#f6f6f6',
  8116. dialogBackgroundColorDark: '#23252a',
  8117. backdropColor: '#b5b5b568',
  8118. textColor: '#111111',
  8119. textColorDark: '#f0f3f4',
  8120. zIndex: 60000,
  8121. fontSize: '10pt',
  8122. dialogMinWidth: '32px',
  8123. dialogMinHeight: '24px',
  8124. };
  8125.  
  8126. class VJSD extends VanillaJSDialog {
  8127.  
  8128. get themeProps() {
  8129. return _themeProps_
  8130. }
  8131.  
  8132. isDarkTheme() {
  8133. return document.documentElement.hasAttribute('dark');
  8134. }
  8135.  
  8136. onBeforeShow() {
  8137. const es = this.es;
  8138. if ('checkboxSelectionDisplay' in es) {
  8139. es.checkboxSelectionDisplay.textContent = '';
  8140. }
  8141. const setDefaultTabTick = (myDefaultTab) => {
  8142. for (const checkbox of document.getElementsByName('tabview-tab-default')) {
  8143. checkbox.checked = checkbox.value === myDefaultTab;
  8144. }
  8145. }
  8146. function getDefaultTabBtnSetting(store) {
  8147. if (!store) { } else {
  8148. let myDefaultTab = store[key_default_tab];
  8149. if (!myDefaultTab || typeof myDefaultTab !== 'string' || !/^\#[a-zA-Z\_\-\+]+$/.test(myDefaultTab)) {
  8150. } else {
  8151. if (document.querySelector(`.tab-btn[tyt-tab-content="${myDefaultTab}"]`)) return setDefaultTabTick(myDefaultTab);
  8152. }
  8153. }
  8154. setDefaultTabTick(null);
  8155. }
  8156. let store = getStore();
  8157. getDefaultTabBtnSetting(store);
  8158. }
  8159.  
  8160. onFirstCreation() {
  8161.  
  8162. const S = this.S; /* this is the global method */
  8163.  
  8164. /* on top of the setup function, override the icon widget on global method */
  8165. S.widgets.icon = (iconTag) => {
  8166. return S.ce('i', { className: 'vjsd-icon fa-solid fa-' + iconTag });
  8167. }
  8168.  
  8169. /* you might also overide `S.importCSS` by the use of Userscript Manager's import */
  8170. S.importCSS(
  8171. 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/fontawesome.min.css#sha512=SgaqKKxJDQ/tAUAAXzvxZz33rmn7leYDYfBP+YoMRSENhf3zJyx3SBASt/OfeQwBHA1nxMis7mM3EV/oYT6Fdw==',
  8172. // 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/brands.min.css',
  8173. 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/solid.min.css#sha512=yDUXOUWwbHH4ggxueDnC5vJv4tmfySpVdIcN1LksGZi8W8EVZv4uKGrQc0pVf66zS7LDhFJM7Zdeow1sw1/8Jw=='
  8174. );
  8175.  
  8176. /* load CSS files, etc - You might overide the `getTheme()` in VanillaJSDialog */
  8177. this.themeSetup();
  8178. }
  8179.  
  8180. /* init is called after setup function is called */
  8181. init() {
  8182. const S = this.S; /* this is the global method */
  8183.  
  8184. const es = this.es; /* this is a store for HTMLElements binded to this dialog */
  8185.  
  8186. es.dialog = S.ce('div', {
  8187. className: 'vjsd-dialog'
  8188. }, {
  8189. '__vjsd__': ''
  8190. });
  8191.  
  8192. es.dialog.append(
  8193. es.header = S.ce('div', {
  8194. className: 'vjsd-dialog-header vjsd-hflex'
  8195. }),
  8196. es.body = S.ce('div', {
  8197. className: 'vjsd-dialog-body vjsd-gap-2 vjsd-overscroll-none vjsd-vflex'
  8198. }),
  8199. es.footer = S.ce('div', {
  8200. className: 'vjsd-dialog-footer vjsd-hflex'
  8201. }),
  8202.  
  8203. );
  8204.  
  8205. es.header.append(
  8206. S.widgets.icon('circle-info', (a) => {
  8207.  
  8208. }),
  8209. S.widgets.title('Tabview Youtube - Change Default Tab', {
  8210. className: 'vjsd-flex-fill'
  8211. }),
  8212. S.widgets.buttonIcon('square-xmark', {
  8213. 'vjsd-clickable': '#dialogXmark'
  8214. })
  8215. );
  8216.  
  8217. const checkBoxChanged = () => {
  8218. let elmChoice1 = [...document.getElementsByName('tabview-tab-default')].filter(e => e.checked).map(e => e.value);
  8219. console.assert(elmChoice1.length <= 1);
  8220. es.checkboxSelectionDisplay.textContent = elmChoice1.length === 1 ? `The default tab will be set to ${elmChoice1[0]}` : `The default tab will be reset.`;
  8221. }
  8222.  
  8223. es.body.append(
  8224. S.widgets.labeledRadio('vjsd-checkbox1 vjsd-checkbox-tick', 'Info', (elmLabel, elmInput) => {
  8225. elmInput.name = 'tabview-tab-default';
  8226. elmInput.value = '#tab-info';
  8227. es.checkbox1 = elmInput;
  8228. elmInput.addEventListener('change', checkBoxChanged)
  8229. elmLabel.style.fontSize = '200%';
  8230. }),
  8231. S.widgets.labeledRadio('vjsd-checkbox1 vjsd-checkbox-tick', 'Comment', (elmLabel, elmInput) => {
  8232. elmInput.name = 'tabview-tab-default';
  8233. elmInput.value = '#tab-comments';
  8234. es.checkbox2 = elmInput;
  8235. elmInput.addEventListener('change', checkBoxChanged)
  8236. elmLabel.style.fontSize = '200%';
  8237. }),
  8238. S.widgets.labeledRadio('vjsd-checkbox1 vjsd-checkbox-tick', 'Video', (elmLabel, elmInput) => {
  8239. elmInput.name = 'tabview-tab-default';
  8240. elmInput.value = '#tab-videos';
  8241. es.checkbox3 = elmInput;
  8242. elmInput.addEventListener('change', checkBoxChanged)
  8243. elmLabel.style.fontSize = '200%';
  8244. }),
  8245. es.checkboxSelectionDisplay = S.ce('div', { className: 'vjsd-custom-widget' })
  8246. );
  8247.  
  8248. const onXMarkClicked = () => {
  8249. this.dismiss();
  8250. }
  8251.  
  8252. const onClearClicked = () => {
  8253. es.checkbox1.checked = false;
  8254. es.checkbox2.checked = false;
  8255. es.checkbox3.checked = false;
  8256. checkBoxChanged();
  8257. }
  8258.  
  8259. const onConfirmClicked = () => {
  8260. let myDefaultTab = null;
  8261. for (const checkbox of document.getElementsByName('tabview-tab-default')) {
  8262. if (checkbox.checked) myDefaultTab = checkbox.value;
  8263. }
  8264. myDefaultTab = myDefaultTab || null;
  8265. console.log(myDefaultTab)
  8266. setMyDefaultTab(myDefaultTab);
  8267. this.dismiss();
  8268. }
  8269.  
  8270. const onCancelClicked = () => {
  8271. this.dismiss();
  8272. }
  8273.  
  8274. es.footer.append(
  8275. es.clearButton = S.widgets.button('Clear', {
  8276. 'vjsd-clickable': '#clear'
  8277. }),
  8278. S.widgets.space(),
  8279. S.widgets.button('Cancel', {
  8280. 'vjsd-clickable': '#cancel'
  8281. }),
  8282. S.widgets.button('Confirm', {
  8283. 'vjsd-clickable': '#confirm'
  8284. }),
  8285. )
  8286.  
  8287. this.clickable('#cancel', onCancelClicked)
  8288. this.clickable('#clear', onClearClicked)
  8289. this.clickable('#confirm', onConfirmClicked)
  8290. this.clickable('#dialogXmark', onXMarkClicked);
  8291.  
  8292. this.backdrop = 'dismiss';
  8293. document.body.appendChild(es.dialog)
  8294. }
  8295. }
  8296.  
  8297. VJSD.setup1();
  8298. return new VJSD();
  8299. }
  8300.  
  8301. GM_registerMenuCommand("Change Default Tab", function () {
  8302. dialog = dialog || createDialog();
  8303. dialog.show();
  8304. });
  8305.  
  8306. /*
  8307. GM_registerMenuCommand("Default Tab: NULL", function () {
  8308. setMyDefaultTab(null);
  8309. });
  8310. GM_registerMenuCommand("Default Tab: Info", function () {
  8311. setMyDefaultTab("#tab-info");
  8312. });
  8313. GM_registerMenuCommand("Default Tab: Comments", function () {
  8314. setMyDefaultTab("#tab-comments");
  8315. });
  8316. GM_registerMenuCommand("Default Tab: Video", function () {
  8317. setMyDefaultTab("#tab-videos");
  8318. });
  8319. */
  8320. }
  8321.  
  8322.  
  8323. handleDOMAppear('#tabview-controller', () => { }); // dummy
  8324. document.documentElement.appendChild(document.createElement('tabview-controller')).id = 'tabview-tabs-hide-controller';
  8325. document.documentElement.appendChild(document.createElement('tabview-controller')).id = 'tabview-default-tab-controller';
  8326.  
  8327. document.documentElement.setAttribute('plugin-tabview-youtube', `${scriptVersionForExternal}`)
  8328. if (document.documentElement.getAttribute('tabview-unwrapjs')) {
  8329. document.dispatchEvent(new CustomEvent("tabview-plugin-loaded"))
  8330. }
  8331.  
  8332.  
  8333. // function nestedObjectFlatten(prefix, obj) {
  8334. // let ret = {};
  8335. // let _prefix = prefix ? `${prefix}.` : '';
  8336. // let isObject = (obj && typeof obj == 'object' && obj.constructor.name == 'Object');
  8337. // let isArray = (obj && typeof obj == 'object' && obj.constructor.name == 'Array');
  8338. // const f = (k, v) => {
  8339. // let isObject = (v && typeof v == 'object' && v.constructor.name == 'Object');
  8340. // let isArray = (v && typeof v == 'object' && v.constructor.name == 'Array');
  8341. // if (isObject || isArray) {
  8342. // let r = nestedObjectFlatten(k, v)
  8343. // for (const w in r) {
  8344. // ret[`${_prefix}${w}`] = r[w];
  8345. // }
  8346. // } else {
  8347. // ret[`${_prefix}${k}`] = v;
  8348. // }
  8349. // }
  8350. // if (isObject) {
  8351. // for (const k in obj) {
  8352. // let v = obj[k];
  8353. // f(k, v);
  8354. // }
  8355. // } else if (isArray) {
  8356. // let idx = 0;
  8357. // for (const v of obj) {
  8358. // let k = `[${idx}]`;
  8359. // f(k, v);
  8360. // idx++;
  8361. // }
  8362. // }
  8363. // return ret;
  8364. // }
  8365.  
  8366. /*
  8367.  
  8368. for(const p of document.querySelectorAll('ytd-watch-flexy *')){ let m = p.data; if(!m)continue; console.log(m)}
  8369.  
  8370. function objec
  8371.  
  8372. */
  8373.  
  8374.  
  8375. //Object.keys($0).filter(key=>!(key in $0.constructor.prototype))
  8376.  
  8377. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML'))
  8378. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML')).filter(k=>$0 instanceof window[k])
  8379.  
  8380.  
  8381. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  8382.  
  8383. /*
  8384. fix bug for comment section - version 1.8.7
  8385. This issue is the bug in browser's rendering
  8386. I guess, this is due to the lines clamp with display:-webkit-box
  8387. use stupid coding to let it re-render when its content become visible
  8388. /*
  8389.  
  8390. ytd-expander[should-use-number-of-lines][collapsed] > #content.ytd-expander {
  8391. color: var(--yt-spec-text-primary);
  8392. display: -webkit-box;
  8393. overflow: hidden;
  8394. max-height: none;
  8395. -webkit-box-orient: vertical;
  8396. -webkit-line-clamp: var(--ytd-expander-max-lines, 4);
  8397. }
  8398.  
  8399. // v1.8.36 imposed a effective solution for fixing this bug
  8400.  
  8401. */
  8402.  
  8403. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  8404.  
  8405.  
  8406. /**
  8407. *
  8408.  
  8409.  
  8410. f.initChildrenObserver=function(){var a=this;this.observer=new MutationObserver(function(){return a.childrenChanged()});
  8411. this.observer.observe(this.$.content,{subtree:!0,childList:!0,attributes:!0});this.childrenChanged()};
  8412. 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()})}))};
  8413.  
  8414.  
  8415. f.onIronResize=function(){this.recomputeOnResize&&this.childrenChanged()};
  8416.  
  8417.  
  8418. onButtonClick_:function(){this.fire("yt-close-upsell-dialog")},
  8419. 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};
  8420. n(xI,L);f=xI.prototype;f.alwaysToggleableChanged=function(){this.alwaysToggleable&&(this.canToggle=!0)};
  8421.  
  8422.  
  8423. f.calculateCanCollapse=function(){this.canToggle=this.shouldUseNumberOfLines?this.alwaysToggleable||this.$.content.offsetHeight<this.$.content.scrollHeight:this.alwaysToggleable||this.$.content.scrollHeight>this.collapsedHeight};
  8424. f.detachObserver=function(){this.observer&&this.observer.disconnect()};
  8425.  
  8426. *
  8427. *
  8428. *
  8429. */
  8430.  
  8431.  
  8432. })({
  8433. requestAnimationFrame: (typeof webkitRequestAnimationFrame === 'function' ? webkitRequestAnimationFrame : requestAnimationFrame),
  8434. cancelAnimationFrame: (typeof webkitRequestAnimationFrame === 'function' ? webkitRequestAnimationFrame : requestAnimationFrame)
  8435. });
  8436. // console.timeEnd("Tabview Youtube Init Script")
  8437.  
  8438. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  8439. }
  8440.  
  8441.  
  8442. ; !(async () => {
  8443. 'use strict';
  8444.  
  8445. const o = [{
  8446. id: 'tabview-css-content',
  8447. resTag: 'contentCSS',
  8448. }, {
  8449. id: 'tabview-css-chat',
  8450. resTag: 'chatCSS'
  8451. }, {
  8452. id: 'tabview-css-control',
  8453. resTag: 'controlCSS'
  8454. }];
  8455.  
  8456. const Promise = (async () => { })().constructor;
  8457.  
  8458. const contents = o.map(e => {
  8459. e = e.resTag;
  8460. return GM_getResourceText(e) || GM.getResourceText(e) || '';
  8461. });
  8462.  
  8463. const texts = await Promise.all(contents);
  8464.  
  8465. while (document.documentElement === null) {
  8466. await new Promise(r => window.requestAnimationFrame(r));
  8467. }
  8468.  
  8469. const target = document.head || document.documentElement;
  8470. let i = 0;
  8471. for (const e of o) {
  8472. const text = texts[i++];
  8473. if (text) {
  8474. const styleNode = document.createElement('style');
  8475. styleNode.id = e.id;
  8476. styleNode.textContent = text;
  8477. target.appendChild(styleNode);
  8478. }
  8479. }
  8480.  
  8481. main();
  8482.  
  8483. })();