Tabview Youtube

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

当前为 2023-05-03 提交的版本,查看 最新版本

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