Tabview Youtube

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

当前为 2023-02-04 提交的版本,查看 最新版本

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