Tabview Youtube

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

目前为 2023-05-09 提交的版本。查看 最新版本

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

QingJ © 2025

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