Tabview Youtube

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

当前为 2024-05-26 提交的版本,查看 最新版本

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