Tabview Youtube

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

目前为 2023-01-24 提交的版本。查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址