Tabview Youtube

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

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

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

QingJ © 2025

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