Tabview Youtube

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

当前为 2023-01-25 提交的版本,查看 最新版本

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