Tabview Youtube

Trasforma commenti e liste in schede per i Video di YouTube

Versione datata 27/05/2024. Vedi la nuova versione l'ultima versione.

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