Tabview Youtube

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

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

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