Tabview Youtube

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

当前为 2023-05-07 提交的版本,查看 最新版本

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