Tabview Youtube

把Youtube Videos中的評論及影片清單製作成Tabs

目前為 2023-01-10 提交的版本,檢視 最新版本

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

QingJ © 2025

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