Tabview Youtube

Make comments and lists into tabs for YouTube Videos

当前为 2022-07-16 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Tabview Youtube
  3. // @name:en Tabview Youtube
  4. // @name:jp Tabview Youtube
  5. // @name:zh-tw Tabview Youtube
  6. // @name:zh-cn Tabview Youtube
  7. // @namespace http://tampermonkey.net/
  8. // @version 2.4.7
  9. // @license MIT https://github.com/cyfung1031/Tabview-Youtube/blob/main/LICENSE
  10. // @description Make comments and lists into tabs for YouTube Videos
  11. // @description:en Make comments and lists into tabs for YouTube Videos
  12. // @description:jp YouTube動画のコメントやリストなどをタブに作成します
  13. // @description:zh-tw 把Youtube Videos中的評論及影片清單製作成Tabs
  14. // @description:zh-cn 把Youtube Videos中的评论及视频列表制作成Tabs
  15. // @author CY Fung
  16. // @include https://www.youtube.com/*
  17. // @icon https://github.com/cyfung1031/Tabview-Youtube/raw/main/images/icon128p.png
  18. // @run-at document-start
  19. // @grant GM_getResourceText
  20. // @resource contentCSS https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/06a843f4f5d4d3ab76227cbd35a8adf59615e77d/css/style_content.css
  21. // @resource injectionJS1 https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/7282343d6a6535d4dc79535e39c28b76ab2f33cf/js/injection_script_1.js
  22. // @resource injectionFixAutoComplete https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/06a843f4f5d4d3ab76227cbd35a8adf59615e77d/js/injectionScript_fixAutoComplete.js
  23. // @require https://cdnjs.cloudflare.com/ajax/libs/cash/8.1.0/cash.min.js
  24. // @noframes
  25. // ==/UserScript==
  26.  
  27. /* jshint esversion:6 */
  28.  
  29. function main($){
  30. // MIT License
  31. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51. -(function() {
  52.  
  53. function inIframe() {
  54. try {
  55. return window.self !== window.top;
  56. } catch (e) {
  57. return true;
  58. }
  59. }
  60.  
  61. if (inIframe()) return;
  62.  
  63. if (!$) return;
  64.  
  65. /**
  66. * SVG resources:
  67. * <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>
  68. */
  69.  
  70. const scriptVersionForExternal = '2022/05/07';
  71.  
  72. const isMyScriptInChromeRuntime = () => typeof((((window || 0).chrome || 0).runtime || 0).getURL) == 'function'
  73.  
  74. const svgComments = `<path d="M40.068 13.465l-34.138.07A5.94 5.94 0 0 0 0 19.465v21.141a5.94 5.94 0 0 0 5.93 5.929H12v10a1
  75. 1 0 0 0 1.74.673l9.704-10.675 16.626-.068A5.94 5.94 0 0 0 46 40.536V19.395a5.94 5.94 0 0 0-5.932-5.93zM10 23.465h13a1
  76. 1 0 1 1 0 2H10a1 1 0 1 1 0-2zm26 14H10a1 1 0 1 1 0-2h26a1 1 0 1 1 0 2zm0-6H10a1 1 0 1 1 0-2h26a1 1 0 1 1 0
  77. 2zm18.072-28.93l-34.142-.07A5.94 5.94 0 0 0 14 8.395v3.124l26.064-.054c4.377 0 7.936 3.557 7.936 7.93v21.07.071
  78. 2.087l3.26 3.586a1 1 0 0 0 1.74-.673v-10h1.07A5.94 5.94 0 0 0 60 29.607V8.465a5.94 5.94 0 0 0-5.928-5.93z"/>`.trim();
  79.  
  80. const svgVideos = `<path d="M298 33c0-13.255-10.745-24-24-24H24C10.745 9 0 19.745 0 33v232c0 13.255 10.745 24 24
  81. 24h250c13.255 0 24-10.745 24-24V33zM91 39h43v34H91V39zM61 259H30v-34h31v34zm0-186H30V39h31v34zm73
  82. 186H91v-34h43v34zm-11-82.292v-55.417c0-8.25 5.868-11.302 12.77-6.783l40.237 26.272c6.902 4.519 6.958 11.914.056
  83. 16.434l-40.321 26.277c-6.902 4.52-12.742 1.467-12.742-6.783zM207 259h-43v-34h43v34zm0-186h-43V39h43v34zm61
  84. 186h-31v-34h31v34zm0-186h-31V39h31v34z"/>`.trim();
  85.  
  86. const svgInfo = `<path d="M11.812 0C5.289 0 0 5.289 0 11.812s5.289 11.813 11.812 11.813 11.813-5.29 11.813-11.813S18.335
  87. 0 11.812 0zm2.459 18.307c-.608.24-1.092.422-1.455.548s-.783.189-1.262.189c-.736
  88. 0-1.309-.18-1.717-.539s-.611-.814-.611-1.367c0-.215.015-.435.045-.659a8.23 8.23 0 0 1
  89. .147-.759l.761-2.688c.067-.258.125-.503.171-.731a3.24 3.24 0 0 0
  90. .068-.633c0-.342-.071-.582-.212-.717s-.412-.201-.813-.201c-.196
  91. 0-.398.029-.605.09s-.383.12-.529.176l.201-.828c.498-.203.975-.377 1.43-.521s.885-.218 1.29-.218c.731 0 1.295.178
  92. 1.692.53s.594.812.594 1.376c0 .117-.014.323-.041.617a4.13 4.13 0 0 1-.152.811l-.757
  93. 2.68c-.062.215-.117.461-.167.736s-.073.485-.073.626c0 .356.079.599.239.728s.435.194.827.194a2.4 2.4 0 0 0 .626-.097
  94. 3.56 3.56 0 0 0 .506-.17l-.203.827zm-.134-10.878c-.353.328-.778.492-1.275.492s-.924-.164-1.28-.492a1.57 1.57 0
  95. 0 1-.533-1.193c0-.465.18-.865.533-1.196a1.81 1.81 0 0 1 1.28-.497 1.79 1.79 0 0 1 1.275.497c.353.331.53.731.53
  96. 1.196s-.177.865-.53 1.193z"/>`.trim();
  97.  
  98. const svgPlayList = `<path d="M0 64h256v42.667H0zm0 85.333h256V192H0zm0 85.334h170.667v42.667H0zm341.333
  99. 0v-85.334h-42.666v85.334h-85.334v42.666h85.334v85.334h42.666v-85.334h85.334v-42.666z"/>`.trim();
  100.  
  101. // --- Youtube Video Testing :
  102. // Square Video: https://www.youtube.com/watch?v=L0RXVnRbFg8
  103. // Square Video: https://www.youtube.com/watch?v=bK_rKhMIotU
  104. // ---
  105.  
  106.  
  107. const LAYOUT_TWO_COLUMNS = 1;
  108. const LAYOUT_THEATER = 2;
  109. const LAYOUT_FULLSCREEN = 4;
  110. const LAYOUT_CHATROOM = 8;
  111. const LAYOUT_CHATROOM_COLLASPED = 16;
  112. const LAYOUT_TAB_EXPANDED = 32;
  113. const LAYOUT_ENGAGEMENT_PANEL_EXPAND = 64;
  114.  
  115. const mtoInterval1 = 40;
  116. const mtoInterval2 = 150;
  117.  
  118. let lastVideoURL = null; // for less attribute set only
  119.  
  120.  
  121.  
  122. const querySelectorFromAnchor = HTMLElement.prototype.querySelector;
  123. const querySelectorAllFromAnchor = HTMLElement.prototype.querySelectorAll;
  124.  
  125.  
  126.  
  127. function scriptInjector(script_id, url_chrome, response_id){
  128.  
  129. let res={
  130. script_id: script_id,
  131. inject: function(){
  132.  
  133. let res = this, script_id = this.script_id;
  134.  
  135. if(!document.querySelector(`script#${script_id}`)){
  136. if (res.runtime_url){
  137. addScriptByURL(res.runtime_url).id = script_id;
  138. } else {
  139. addScript(`${res.injection_script}`).id = script_id;
  140. }
  141. }
  142.  
  143. }
  144. }
  145. res.script_id = script_id;
  146. if (isMyScriptInChromeRuntime()){
  147. res.runtime_url = window.chrome.runtime.getURL(url_chrome)
  148. } else {
  149. res.injection_script = GM_getResourceText(response_id);
  150. }
  151.  
  152. return res;
  153.  
  154.  
  155.  
  156. }
  157.  
  158. const script_inject_facp = scriptInjector(
  159. 'userscript-tabview-injection-facp',
  160. 'js/injectionScript_fixAutoComplete.js',
  161. "injectionFixAutoComplete");
  162. const script_inject_js1 = scriptInjector(
  163. 'userscript-tabview-injection-1',
  164. 'js/injection_script_1.js',
  165. "injectionJS1");
  166.  
  167.  
  168.  
  169. /** @type {WeakRef | null} */
  170. const WeakRef = window.WeakRef;
  171. const mWeakRef = WeakRef ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  172. /** @type {(wr: Object | null) => Object | null} */
  173. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  174.  
  175.  
  176.  
  177. const nonCryptoRandStr_base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  178. function nonCryptoRandStr(/** @type {number} */ n){
  179. const result = new Array(n);
  180. const baseStr = nonCryptoRandStr_base;
  181. const bLen = baseStr.length;
  182. for ( let i = 0; i < n; i++ ) {
  183. let t = null
  184. do {
  185. t = baseStr.charAt(Math.floor(Math.random() * bLen));
  186. }while(i===0 && 10-t>0)
  187. result[i]=t;
  188. }
  189. return result.join('');
  190. }
  191.  
  192. /**
  193. * Class definition
  194. * @property {string} propName - propriety description
  195. * ...
  196. */
  197. class ObserverRegister{
  198. constructor(/** @type {()=>MutationObserver | IntersectionObserver} */ observerCreator){
  199. let uid = null;
  200. const uidStore = ObserverRegister.uidStore;
  201. do{
  202. uid = nonCryptoRandStr(5);
  203. }while(uidStore[uid])
  204. uidStore[uid] = true;
  205. /**
  206. * uid is the unique string for each observer
  207. * @type {string}
  208. * @public
  209. */
  210. this.uid = uid;
  211. /**
  212. * observerCreator is a function to create the observer
  213. * @type {Function}
  214. * @public
  215. */
  216. this.observerCreator = observerCreator
  217. /**
  218. * observer is the actual observer object
  219. * @type {MutationObserver | IntersectionObserver}
  220. * @public
  221. */
  222. this.observer = null;
  223. }
  224. bindElement(/** @type {HTMLElement} */ elm, ...args){
  225. if(elm.hasAttribute(`o3r-${this.uid}`))return false;
  226. elm.setAttribute(`o3r-${this.uid}`,'')
  227. if(this.observer===null){
  228. this.observer=this.observerCreator();
  229. }
  230. this.observer.observe(elm, ...args)
  231. return true
  232. }
  233. clear(/** @type {boolean} */ flag){
  234. if(this.observer !== null){
  235. //const uidStore = ObserverRegister.uidStore;
  236. if(flag === true){
  237. this.observer.takeRecords();
  238. this.observer.disconnect();
  239. }
  240. this.observer = null;
  241. for(const s of document.querySelectorAll(`[o3r-${this.uid}]`)) s.removeAttribute(`o3r-${this.uid}`)
  242. //uidStore[this.uid]=false;
  243. //this.uid = null;
  244. }
  245. }
  246. }
  247.  
  248. /**
  249. * 'uidStore' is the static store of strings used.
  250. * @static
  251. */
  252. ObserverRegister.uidStore = {}; //backward compatible with FireFox 55.
  253.  
  254. const mtoMutation_watchFlexy = new ObserverRegister(()=>{
  255. return new MutationObserver(FP.mtoNavF)
  256. });
  257. const sa_wflexy = mtoMutation_watchFlexy.uid;
  258.  
  259. const mtoMutation_body = new ObserverRegister(()=>{
  260. return new MutationObserver(FP.mtoBodyF)
  261. });
  262. const sa_body = mtoMutation_body.uid;
  263.  
  264. const mtoFlexyAttr = new ObserverRegister(()=>{
  265. return new MutationObserver(mtf_attrFlexy)
  266. });
  267. const sa_flexyAttr = mtoFlexyAttr.uid;
  268.  
  269. const mtoVisibility_EngagementPanel = new ObserverRegister(()=>{
  270. return new MutationObserver(FP.mtf_attrEngagementPanel)
  271. });
  272. const sa_epanel = mtoVisibility_EngagementPanel.uid;
  273.  
  274. const mtoVisibility_Playlist = new ObserverRegister(()=>{
  275. return new AttributeMutationObserver({
  276. "hidden": FP.mtf_attrPlaylist
  277. })
  278. })
  279. const sa_playlist = mtoVisibility_Playlist.uid;
  280.  
  281. const mtoVisibility_Comments = new ObserverRegister(()=>{
  282. return new AttributeMutationObserver({
  283. "hidden": FP.mtf_attrComments
  284. })
  285. })
  286. const sa_comments = mtoVisibility_Comments.uid;
  287.  
  288.  
  289. const mtoVisibility_Chatroom = new ObserverRegister(()=>{
  290. return new AttributeMutationObserver({
  291. "collapsed": FP.mtf_attrChatroom
  292. })
  293. })
  294. const sa_chatroom = mtoVisibility_Chatroom.uid;
  295.  
  296.  
  297.  
  298.  
  299.  
  300. function tracer(key, cmp) {
  301. if (cmp > 0) return tracer[key] === cmp;
  302. return (tracer[key] = Date.now());
  303. }
  304.  
  305. function racer(key, f) {
  306. let now = Date.now();
  307. const kTime = `${key}$$1`
  308. let t = racer[kTime] || 0;
  309.  
  310. if (now < t) {
  311. const kCount = `${key}$$2`;
  312. racer[kCount] = (racer[kCount] || 0) + 1;
  313. if (racer[kCount] === 1) {
  314. let g = f;
  315. requestAnimationFrame(() => {
  316. racer[kCount] = 0;
  317. g();
  318. g = null;
  319. })
  320. }
  321. } else {
  322. racer[kTime] = now + 16;
  323. f();
  324. }
  325. }
  326.  
  327. class ScriptEF {
  328. constructor() {
  329. this._id = scriptEC;
  330. }
  331. isValid() {
  332. return this._id === scriptEC;
  333. }
  334. }
  335.  
  336. class Timeout {
  337.  
  338. set(f, d, repeatCount) {
  339. if (this.cid > 0) return;
  340. let sEF = new ScriptEF();
  341. if (repeatCount > 0) {
  342.  
  343. let rc = repeatCount;
  344. const g = () => {
  345. this.cid = 0;
  346. if (!sEF.isValid()) return;
  347. let res = f();
  348. if (--rc <= 0) return;
  349. if (res === true) this.cid = timeline.setTimeout(g, d);
  350. }
  351. g();
  352.  
  353. } else {
  354.  
  355. const g = () => {
  356. this.cid = 0;
  357. if (!sEF.isValid()) return;
  358. if (f() === true) this.cid = timeline.setTimeout(g, d);
  359. }
  360. this.cid = timeline.setTimeout(g, d);
  361. }
  362. }
  363.  
  364. clear() {
  365. if (this.cid > 0) timeline.clearTimeout(this.cid);
  366. }
  367.  
  368. isEmpty() {
  369. return !this.cid
  370. }
  371.  
  372.  
  373. }
  374.  
  375. class Mutex {
  376.  
  377. constructor() {
  378. this.p = Promise.resolve()
  379. }
  380.  
  381. lockWith(f) {
  382.  
  383. this.p = this.p.then(() => {
  384. return new Promise(f)
  385. }).catch(console.warn)
  386. }
  387.  
  388. }
  389.  
  390.  
  391.  
  392. function prettyElm(/** @type {Element} */ elm) {
  393. if (!elm || !elm.nodeName) return null;
  394. const eId = elm.id || null;
  395. const eClsName = elm.className || null;
  396. return [elm.nodeName.toLowerCase(), typeof eId == 'string' ? "#" + eId : '', typeof eClsName == 'string' ? '.' + eClsName.replace(/\s+/g, '.') : ''].join('').trim();
  397. }
  398.  
  399. function extractTextContent(/** @type {Node} */ elm) {
  400. 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, '')
  401. }
  402.  
  403. function addScript(/** @type {string} */ scriptText) {
  404. const scriptNode = document.createElement('script');
  405. scriptNode.type = 'text/javascript';
  406. scriptNode.textContent = scriptText;
  407. try {
  408. document.documentElement.appendChild(scriptNode);
  409. } catch (e) {
  410. console.log('addScript Error', e)
  411. }
  412. return scriptNode;
  413. }
  414.  
  415. function addScriptByURL(/** @type {string} */ scriptURL) {
  416. const scriptNode = document.createElement('script');
  417. scriptNode.type = 'text/javascript';
  418. scriptNode.src = scriptURL;
  419. try {
  420. document.documentElement.appendChild(scriptNode);
  421. } catch (e) {
  422. console.log('addScriptByURL Error', e)
  423. }
  424. return scriptNode;
  425. }
  426.  
  427. function addStyle(/** @type {string} */ styleText, /** @type {HTMLElement | Document} */ container) {
  428. const styleNode = document.createElement('style');
  429. //styleNode.type = 'text/css';
  430. styleNode.textContent = styleText;
  431. (container || document.documentElement).appendChild(styleNode);
  432. return styleNode;
  433. }
  434.  
  435.  
  436. const stopIframePropagation = function(/** @type {Event} */ evt){
  437. if(scriptEnable && evt && evt.target && evt.target.nodeName=='IFRAME'){
  438. evt.stopImmediatePropagation();
  439. evt.stopPropagation();
  440. }
  441. }
  442. document.addEventListener('mouseover', stopIframePropagation, true)
  443. document.addEventListener('mouseout', stopIframePropagation, true)
  444. document.addEventListener('mousedown', stopIframePropagation, true)
  445. document.addEventListener('mouseup', stopIframePropagation, true)
  446. document.addEventListener('keydown', stopIframePropagation, true)
  447. document.addEventListener('keyup', stopIframePropagation, true)
  448. document.addEventListener('mouseenter', stopIframePropagation, true)
  449. document.addEventListener('mouseleave', stopIframePropagation, true)
  450.  
  451.  
  452.  
  453. function isDOMVisible(/** @type {HTMLElement} */ elem) {
  454. // jQuery version : https://github.com/jquery/jquery/blob/a684e6ba836f7c553968d7d026ed7941e1a612d8/src/css/hiddenVisibleSelectors.js
  455. return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
  456. }
  457.  
  458. function isNonEmptyString(s) {
  459. return typeof s == 'string' && s.length > 0;
  460. }
  461.  
  462.  
  463. async function nativeFunc(/** @type {EventTarget} */ dom, /** @type {string} */ property, /** @type {any} */ args) {
  464. dom.dispatchEvent(new CustomEvent("userscript-call-dom-func", { detail: { property, args } }))
  465. }
  466.  
  467. // async function nativeValue(dom, property, args) {
  468. // dom.dispatchEvent(new CustomEvent("userscript-call-dom-value", { detail: { property, args } }))
  469. // }
  470. // async function nativeFuncStacked(/** @type {string} */ selector, /** @type {string} */ property, /** @type {any} */ args){
  471. // document.dispatchEvent(new CustomEvent("userscript-call-dom-func-stacked", { detail: { selector, property, args } }))
  472. // }
  473. // async function nativeValueStacked(selector, property, args){
  474. // document.dispatchEvent(new CustomEvent("userscript-call-dom-value-stacked", { detail: { selector, property, args } }))
  475. // }
  476. // async function nativeConstStacked(selector, property, args){
  477. // document.dispatchEvent(new CustomEvent("userscript-call-dom-const-stacked", { detail: { selector, property, args } }))
  478. // }
  479.  
  480.  
  481. function akAttr(/** @type {HTMLElement} */ cssElm, /** @type {String} */ attrName, /** @type {boolean} */ isNegative, /** @type {string | any} */ flag) {
  482. // isNegative => incomplete loading
  483.  
  484. let u = parseInt(cssElm.getAttribute(attrName) || 0) || 0;
  485. let ak = Math.abs(u);
  486.  
  487. if (ak > 100 && isNegative && u < 0) {
  488.  
  489. } else if (ak > 100 && !isNegative && u > 0) {
  490.  
  491. } else {
  492. if (ak <= 100) {
  493. ak = 101;
  494. } else {
  495. ak++;
  496. if (ak >= 800) ak = 101;
  497. }
  498. // 101, 102, ... 799, 101
  499. }
  500.  
  501. cssElm.setAttribute(attrName, `${ isNegative ? -ak : ak }${ flag || '' }`)
  502. }
  503.  
  504.  
  505.  
  506. let timeout_resize_for_layout_change = new Timeout();
  507.  
  508. function dispatchWindowResize(){
  509. // for youtube to detect layout resize for adjusting Player tools
  510. return window.dispatchEvent(new Event('resize'));
  511. }
  512.  
  513.  
  514.  
  515. function layoutStatusChanged(/** @type {number} */ old_layoutStatus, /** @type {number} */ new_layoutStatus) {
  516.  
  517.  
  518. if (old_layoutStatus === new_layoutStatus) return;
  519.  
  520. const cssElm = kRef(ytdFlexy);
  521.  
  522. if (!cssElm) return;
  523.  
  524.  
  525. const new_isExpandedChat = !(new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  526. const new_isCollaspedChat = (new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  527.  
  528. const new_isTwoColumns = !!(new_layoutStatus & LAYOUT_TWO_COLUMNS);
  529. const new_isTheater = !!(new_layoutStatus & LAYOUT_THEATER);
  530. const new_isTabExpanded = !!(new_layoutStatus & LAYOUT_TAB_EXPANDED);
  531. const new_isFullScreen = !!(new_layoutStatus & LAYOUT_FULLSCREEN);
  532. const new_isExpandEPanel = !!(new_layoutStatus & LAYOUT_ENGAGEMENT_PANEL_EXPAND);
  533.  
  534.  
  535.  
  536. function showTabOrChat() {
  537.  
  538. layoutStatusMutex.lockWith(unlock => {
  539.  
  540. if (lastShowTab == '#chatroom') {
  541.  
  542. if (new_isTabExpanded) switchTabActivity(null)
  543. if (!new_isExpandedChat) ytBtnExpandChat();
  544.  
  545. } else if (lastShowTab && lastShowTab.indexOf('#engagement-panel-') == 0) {
  546.  
  547. if (new_isTabExpanded) switchTabActivity(null)
  548. if (!new_isExpandEPanel) ytBtnOpenEngagementPanel(lastShowTab);
  549.  
  550. } else {
  551.  
  552. if (new_isExpandedChat) ytBtnCollapseChat()
  553. if (!new_isTabExpanded) {setToActiveTab();}
  554.  
  555. }
  556.  
  557. timeline.setTimeout(unlock, 40);
  558.  
  559. })
  560. }
  561.  
  562. function hideTabAndChat() {
  563.  
  564. layoutStatusMutex.lockWith(unlock => {
  565.  
  566. if (new_isTabExpanded) switchTabActivity(null)
  567. if (new_isExpandedChat) ytBtnCollapseChat()
  568. if (new_isExpandEPanel) ytBtnCloseEngagementPanels();
  569.  
  570.  
  571. timeline.setTimeout(unlock, 40);
  572.  
  573. })
  574.  
  575. }
  576.  
  577.  
  578. if (new_isExpandedChat || new_isTabExpanded || new_isExpandEPanel) {
  579. if (statusCollasped !== 1) statusCollasped = 1;
  580. } else {
  581. if (statusCollasped === 1) statusCollasped = 2;
  582. }
  583.  
  584. let changes = 0;
  585.  
  586. if (old_layoutStatus !== null) changes = old_layoutStatus ^ new_layoutStatus;
  587.  
  588. let chat_collasped_changed = !!(changes & LAYOUT_CHATROOM_COLLASPED)
  589. let tab_expanded_changed = !!(changes & LAYOUT_TAB_EXPANDED)
  590. let theater_mode_changed = !!(changes & LAYOUT_THEATER)
  591. let column_mode_changed = !!(changes & LAYOUT_TWO_COLUMNS)
  592. let fullscreen_mode_changed = !!(changes & LAYOUT_FULLSCREEN)
  593. let epanel_expanded_changed = !!(changes & LAYOUT_ENGAGEMENT_PANEL_EXPAND)
  594.  
  595. let tab_change = (tab_expanded_changed ? 1 : 0) | (chat_collasped_changed ? 2 : 0) | (epanel_expanded_changed ? 4 : 0);
  596.  
  597. let isChatOrTabExpandTriggering = tab_change == 0 ? false : (
  598. (tab_expanded_changed && new_isTabExpanded) ||
  599. (chat_collasped_changed && new_isExpandedChat) ||
  600. (epanel_expanded_changed && new_isExpandEPanel)
  601. );
  602.  
  603. let isChatOrTabCollaspeTriggering = tab_change == 0 ? false : (
  604. (tab_expanded_changed && !new_isTabExpanded) ||
  605. (chat_collasped_changed && new_isCollaspedChat) ||
  606. (epanel_expanded_changed && !new_isExpandEPanel)
  607. );
  608.  
  609.  
  610.  
  611. let moreThanOneShown = (new_isTabExpanded + new_isExpandedChat + new_isExpandEPanel) > 1
  612.  
  613. let requestVideoResize = false;
  614.  
  615. if (fullscreen_mode_changed || new_isFullScreen) {
  616.  
  617. } else if(new_isTwoColumns && !new_isTheater && !column_mode_changed && (tab_change==2 || tab_change==4) && !new_isTabExpanded && new_isExpandedChat && new_isExpandEPanel){
  618.  
  619. if(epanel_expanded_changed){
  620. layoutStatusMutex.lockWith(unlock => {
  621. ytBtnCollapseChat();
  622. setTimeout(unlock,13)
  623. })
  624. }else if(chat_collasped_changed){
  625. layoutStatusMutex.lockWith(unlock => {
  626. ytBtnCloseEngagementPanels();
  627. setTimeout(unlock,13)
  628. })
  629.  
  630. }
  631.  
  632. } else if (tab_change == 0 && column_mode_changed && new_isTwoColumns && !new_isTheater && statusCollasped === 1 && moreThanOneShown) {
  633.  
  634. showTabOrChat();
  635. requestVideoResize = true;
  636.  
  637. } else if (tab_change == 2 && new_isExpandedChat && new_isTwoColumns && !new_isTheater && statusCollasped === 1 && new_isTabExpanded && !column_mode_changed) {
  638.  
  639. switchTabActivity(null);
  640. requestVideoResize = true;
  641.  
  642. } else if (isChatOrTabExpandTriggering && new_isTwoColumns && new_isTheater && statusCollasped === 1 && !theater_mode_changed && !column_mode_changed) {
  643.  
  644. ytBtnCancelTheater();
  645. requestVideoResize = true;
  646.  
  647. } else if (new_isTwoColumns && new_isTheater && statusCollasped === 1) {
  648.  
  649. hideTabAndChat();
  650. requestVideoResize = true;
  651.  
  652. } else if (isChatOrTabCollaspeTriggering && new_isTwoColumns && !new_isTheater && statusCollasped === 2 && !column_mode_changed) {
  653.  
  654. ytBtnSetTheater();
  655. requestVideoResize = true;
  656.  
  657. } else if (tab_change == 0 && (column_mode_changed || theater_mode_changed) && new_isTwoColumns && !new_isTheater && statusCollasped !== 1) {
  658.  
  659. showTabOrChat();
  660. requestVideoResize = true;
  661.  
  662. } else if (!new_isFullScreen && new_isTwoColumns && !new_isTheater && !new_isTabExpanded &&
  663. (new_isCollaspedChat || !new_isExpandedChat) &&
  664. !new_isExpandEPanel
  665. ) {
  666. // bug fix for restoring from mini player
  667.  
  668. layoutStatusMutex.lockWith(unlock => {
  669. setToActiveTab();
  670. timeline.setTimeout(unlock, 40);
  671. })
  672.  
  673. requestVideoResize = true;
  674.  
  675. } else if (tab_expanded_changed) {
  676.  
  677. requestVideoResize = true;
  678.  
  679. }
  680.  
  681.  
  682. if (column_mode_changed && !chat_collasped_changed && new_isExpandedChat) {
  683.  
  684. runAfterExpandChat();
  685.  
  686. }
  687.  
  688.  
  689.  
  690. if (requestVideoResize) {
  691.  
  692. timeout_resize_for_layout_change.clear();
  693. timeout_resize_for_layout_change.set(() => {
  694. dispatchWindowResize();
  695. }, 92)
  696.  
  697. } else if (timeout_resize_for_layout_change.isEmpty() && (Date.now()) - lastResizeAt > 600) {
  698. timeout_resize_for_layout_change.set(() => {
  699. if ((Date.now()) - lastResizeAt > 600) dispatchWindowResize();
  700. }, 62)
  701. }
  702.  
  703.  
  704.  
  705.  
  706. }
  707.  
  708.  
  709.  
  710. const wls = new Proxy({
  711. /** @type {number | null} */
  712. layoutStatus:undefined
  713. }, {
  714. get: function(target, prop) {
  715. return target[prop];
  716. },
  717. set: function(target, prop, value) {
  718. if(prop=='layoutStatus'){
  719. if (value === null) {
  720. statusCollasped = 0;
  721. target[prop] = value;
  722. return;
  723. }else if(target[prop]===value){
  724. return;
  725. }else{
  726. if (!target.layoutStatus_pending) {
  727. target.layoutStatus_pending = true;
  728. const old_layoutStatus = target[prop];
  729. target[prop] = value;
  730. layoutStatusMutex.lockWith(unlock => {
  731. target.layoutStatus_pending = false;
  732. layoutStatusChanged(old_layoutStatus, target[prop]);
  733. timeline.setTimeout(unlock, 40)
  734. })
  735. return;
  736. }
  737. }
  738. }
  739. target[prop] = value;
  740. },
  741. has: function(target, prop) {
  742. return (prop in target);
  743. }
  744. });
  745.  
  746.  
  747.  
  748.  
  749.  
  750.  
  751. const svgElm = (w, h, vw, vh, p) => `<svg width="${w}" height="${h}" viewBox="0 0 ${vw} ${vh}" preserveAspectRatio="xMidYMid meet">${p}</svg>`
  752.  
  753. let settings = {
  754. defaultTab: "#tab-videos"
  755. };
  756.  
  757.  
  758. let mtoInterval = mtoInterval1;
  759.  
  760. function isVideoPlaying(video) {
  761. return video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  762. }
  763.  
  764. function wAttr(elm, attr, kv) {
  765. if (!elm || kv === null) {} else if (kv === true) { elm.setAttribute(attr, '') } else if (kv === false) { elm.removeAttribute(attr) } else if (typeof kv == 'string') { elm.setAttribute(attr, kv) }
  766. }
  767.  
  768. function hideTabBtn(tabBtn) {
  769. let isActiveBefore = tabBtn.classList.contains('active');
  770. tabBtn.classList.add("tab-btn-hidden");
  771. if (isActiveBefore) {
  772. setToActiveTab();
  773. }
  774. }
  775.  
  776. function hasAttribute(obj, key) {
  777. return obj && obj.hasAttribute(key);
  778. }
  779.  
  780. function isTheater() {
  781. const cssElm = kRef(ytdFlexy);
  782. return (cssElm && cssElm.hasAttribute('theater'))
  783. }
  784.  
  785. function isFullScreen() {
  786. const cssElm = kRef(ytdFlexy);
  787. return (cssElm && cssElm.hasAttribute('fullscreen'))
  788. }
  789.  
  790. function isChatExpand() {
  791. const cssElm = kRef(ytdFlexy);
  792. return cssElm && cssElm.hasAttribute('userscript-chatblock') && !cssElm.hasAttribute('userscript-chat-collapsed')
  793. }
  794.  
  795. function isWideScreenWithTwoColumns() {
  796. const cssElm = kRef(ytdFlexy);
  797. return (cssElm && cssElm.hasAttribute('is-two-columns_'))
  798. }
  799.  
  800. function isAnyActiveTab() {
  801. return $('#right-tabs .tab-btn.active').length > 0
  802. }
  803.  
  804. function isEngagementPanelExpanded() { //note: not checking the visual elements
  805. const cssElm = kRef(ytdFlexy);
  806. return (cssElm && +cssElm.getAttribute('userscript-engagement-panel') > 0)
  807. }
  808.  
  809. function engagement_panels_() {
  810.  
  811. let res = [];
  812. let shownRes = [];
  813.  
  814. let v = 0,
  815. k = 1,
  816. count = 0;
  817. for (const ePanel of document.querySelectorAll(
  818. `ytd-watch-flexy ytd-engagement-panel-section-list-renderer[o3r-${sa_epanel}]`
  819. )) {
  820.  
  821. let visibility = ePanel.getAttribute('visibility') //ENGAGEMENT_PANEL_VISIBILITY_EXPANDED //ENGAGEMENT_PANEL_VISIBILITY_HIDDEN
  822.  
  823. switch (visibility) {
  824. case 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED':
  825. v |= k;
  826. count++;
  827. shownRes.push(ePanel)
  828. res.push({ ePanel, k, visible: true });
  829. break;
  830. case 'ENGAGEMENT_PANEL_VISIBILITY_HIDDEN':
  831. res.push({ ePanel, k, visible: false });
  832. break;
  833. default:
  834. res.push({ ePanel, k, visible: false });
  835. }
  836.  
  837. k = k << 1;
  838.  
  839. }
  840. return { list: res, value: v, count: count, shownRes };
  841. }
  842.  
  843.  
  844. function ytBtnOpenEngagementPanel(/** @type {number | string} */ panel_id) {
  845.  
  846. if (typeof panel_id == 'string') {
  847. panel_id = panel_id.replace('#engagement-panel-', '');
  848. panel_id = parseInt(panel_id);
  849. }
  850. if (panel_id >= 0) {} else return false;
  851.  
  852. let panels = engagement_panels_();
  853.  
  854. for (const { ePanel, k, visible } of panels.list) {
  855. if ((panel_id & k) === k) {
  856. if (!visible) ePanel.setAttribute('visibility', "ENGAGEMENT_PANEL_VISIBILITY_EXPANDED");
  857. } else {
  858. if (visible) ytBtnCloseEngagementPanel(ePanel);
  859. }
  860. }
  861.  
  862. }
  863.  
  864. function ytBtnCloseEngagementPanel(/** @type {HTMLElement} */ s) {
  865. //ePanel.setAttribute('visibility',"ENGAGEMENT_PANEL_VISIBILITY_HIDDEN");
  866. let btn = querySelectorFromAnchor.call(s,'ytd-watch-flexy ytd-engagement-panel-title-header-renderer #header > #visibility-button > ytd-button-renderer');
  867. if (btn) {
  868. btn.click();
  869. }
  870. }
  871.  
  872. function ytBtnCloseEngagementPanels() {
  873. if (isEngagementPanelExpanded()) {
  874. for (const s of document.querySelectorAll(
  875. `ytd-watch-flexy ytd-engagement-panel-section-list-renderer[o3r-${sa_epanel}]`
  876. )) {
  877. if (s.getAttribute('visibility') == "ENGAGEMENT_PANEL_VISIBILITY_EXPANDED") ytBtnCloseEngagementPanel(s);
  878. }
  879. }
  880. }
  881.  
  882. function ytBtnSetTheater() {
  883. if (!isTheater()) {
  884. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  885. if (sizeBtn) sizeBtn.click();
  886. }
  887. }
  888.  
  889. function ytBtnCancelTheater() {
  890. if (isTheater()) {
  891. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  892. if (sizeBtn) sizeBtn.click();
  893. }
  894. }
  895.  
  896. function ytBtnExpandChat() {
  897. let button = document.querySelector('ytd-live-chat-frame#chat[collapsed] > .ytd-live-chat-frame#show-hide-button')
  898. if (button) querySelectorFromAnchor.call(button,'ytd-toggle-button-renderer').click();
  899. }
  900.  
  901. function ytBtnCollapseChat() {
  902. let button = document.querySelector('ytd-live-chat-frame#chat:not([collapsed]) > .ytd-live-chat-frame#show-hide-button')
  903. if (button) button.querySelector('ytd-toggle-button-renderer').click();
  904. }
  905.  
  906. /*
  907. function hackImgShadow(imgShadow) {
  908. // add to #columns and add back after loaded
  909. let img = imgShadow.querySelector('img')
  910. if (!img) return;
  911.  
  912. let p = imgShadow.parentNode
  913. let z = $(imgShadow).clone()[0]; //to occupy the space
  914. p.replaceChild(z, imgShadow)
  915. $(imgShadow).prependTo('#columns'); // refer to css hack
  916.  
  917. function onload(evt) {
  918. if (evt) this.removeEventListener('load', onload, false)
  919. p.replaceChild(imgShadow, z)
  920. p = null;
  921. z = null;
  922. imgShadow = null;
  923. }
  924.  
  925. if (img.complete) onload();
  926. else img.addEventListener('load', onload, false)
  927. }
  928. */
  929.  
  930.  
  931. const Q = {}
  932.  
  933.  
  934.  
  935. function chatFrameContentDocument() {
  936. // non-null if iframe exist && contentDocument && readyState = complete
  937. /** @type {HTMLIFrameElement | null} */
  938. let iframe = document.querySelector('ytd-live-chat-frame iframe#chatframe');
  939. if (!iframe) return null; //iframe must be there
  940. /** @type {Document | null} */
  941. let cDoc = null;
  942. try {
  943. cDoc = iframe.contentDocument;
  944. } catch (e) {}
  945. if (!cDoc) return null;
  946. if (cDoc.readyState != 'complete') return null; //we must wait for its completion
  947.  
  948. return cDoc;
  949.  
  950. }
  951.  
  952. function chatFrameElement(/** @type {string} */ cssSelector) {
  953. let cDoc = chatFrameContentDocument();
  954. if (!cDoc) return null;
  955. /** @type {HTMLElement | null} */
  956. let elm = null;
  957. try {
  958. elm = cDoc.querySelector(cssSelector)
  959. } catch (e) {
  960. console.log('iframe error', e)
  961. }
  962. return elm;
  963. }
  964.  
  965.  
  966.  
  967.  
  968. function fixTabs() {
  969.  
  970.  
  971. if (!scriptEnable) return;
  972.  
  973.  
  974. let queryElement = document.querySelector('*:not(#tab-videos) > #related:not([non-placeholder-videos]) > ytd-watch-next-secondary-results-renderer')
  975.  
  976. let isRelocated = !!queryElement;
  977.  
  978.  
  979.  
  980. if (isRelocated) {
  981.  
  982. let relocatedRelated = queryElement.parentNode; // NOT NULL
  983.  
  984. let right_tabs = document.querySelector('#right-tabs');
  985. let tab_videos = querySelectorFromAnchor.call(right_tabs,"#tab-videos");
  986.  
  987. if (!right_tabs || !tab_videos) return;
  988.  
  989. for (const s of querySelectorAllFromAnchor.call(relocatedRelated,'#related')) {
  990. s.setAttribute('non-placeholder-videos', '')
  991. }
  992.  
  993. let target_container = document.querySelector('ytd-watch-flexy:not([is-two-columns_]) #primary-inner, ytd-watch-flexy[is-two-columns_] #secondary-inner')
  994.  
  995. if (target_container) target_container.append(right_tabs) // last-child
  996.  
  997.  
  998. let videos_related = relocatedRelated; // NOT NULL
  999. $('[placeholder-videos]').removeAttr('placeholder-videos');
  1000. $('[placeholder-for-youtube-play-next-queue]').removeAttr('placeholder-for-youtube-play-next-queue');
  1001.  
  1002. tab_videos.appendChild(videos_related);
  1003. let videos_results_renderer = relocatedRelated.querySelector("ytd-watch-next-secondary-results-renderer");
  1004. if (videos_results_renderer) videos_results_renderer.setAttribute('data-dom-changed-by-tabview-youtube', scriptVersionForExternal);
  1005. videos_related.setAttribute('placeholder-for-youtube-play-next-queue', '')
  1006. videos_related.setAttribute('placeholder-videos', '')
  1007.  
  1008. $('[placeholder-videos]').on("scroll", makeBodyScrollByEvt);
  1009.  
  1010.  
  1011.  
  1012.  
  1013. }
  1014.  
  1015.  
  1016.  
  1017. /** @type {HTMLElement | null} */
  1018. let chatroom = null;
  1019. if (chatroom = document.querySelector('*:not([data-positioner="before|#chat"]) + ytd-live-chat-frame#chat, ytd-live-chat-frame#chat:first-child')) {
  1020.  
  1021. let positioner = document.querySelector('tabview-youtube-positioner[data-positioner="before|#chat"]');
  1022. if (positioner) positioner.remove();
  1023.  
  1024.  
  1025. if (document.querySelector('.YouTubeLiveFilledUpView')) {
  1026. // no relocation
  1027. } else {
  1028.  
  1029. $(chatroom).insertBefore('#right-tabs')
  1030.  
  1031. }
  1032.  
  1033.  
  1034. $(positioner ? positioner : document.createElement('tabview-youtube-positioner')).attr('data-positioner', 'before|#chat').insertBefore(chatroom)
  1035.  
  1036.  
  1037.  
  1038. }
  1039.  
  1040.  
  1041. }
  1042.  
  1043. function handlerAutoCompleteExist() {
  1044.  
  1045.  
  1046. /** @type {HTMLElement} */
  1047. let autoComplete = this;
  1048.  
  1049. autoComplete.removeEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false)
  1050.  
  1051. let domId = autoComplete.getAttribute('data-autocomplete-input-id')
  1052. let searchBox = autoComplete.ownerDocument.querySelector(`[data-autocomplete-results-id="${domId}"]`)
  1053.  
  1054. if (!domId || !searchBox) return;
  1055.  
  1056. let positioner = searchBox.nextSibling;
  1057. if (positioner && positioner.nodeName.toLowerCase() == "autocomplete-positioner") {} else if (positioner && positioner.nodeName.toLowerCase() != "autocomplete-positioner") {
  1058. $(positioner = document.createElement("autocomplete-positioner")).insertAfter(searchBox);
  1059. } else {
  1060. $(positioner = document.createElement("autocomplete-positioner")).prependTo(searchBox.parentNode);
  1061. }
  1062. $(autoComplete).prependTo(positioner);
  1063.  
  1064. positioner.style.setProperty('--sb-margin-bottom', getComputedStyle(searchBox).marginBottom)
  1065. positioner.style.setProperty('--height', searchBox.offsetHeight + 'px')
  1066.  
  1067. }
  1068.  
  1069. function mtf_fixAutoCompletePosition(/** @type {HTMLElement} */ elmAutoComplete) {
  1070.  
  1071.  
  1072. elmAutoComplete.setAttribute('autocomplete-disable-updatesc', '')
  1073. elmAutoComplete.addEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false)
  1074.  
  1075. script_inject_facp.inject();
  1076.  
  1077. }
  1078.  
  1079. function mtf_AfterFixTabs() {
  1080.  
  1081.  
  1082. /** @type {HTMLElement | null} */
  1083. let ytdFlexyElm = kRef(ytdFlexy);
  1084. if (!scriptEnable || !ytdFlexyElm) return;
  1085.  
  1086. /** @type {HTMLElement | null} */
  1087. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1088.  
  1089.  
  1090.  
  1091. const autocomplete = querySelectorFromAnchor.call(rootElement,'[placeholder-for-youtube-play-next-queue] input#suggestions-search + autocomplete-positioner > .autocomplete-suggestions[data-autocomplete-input-id]:not([position-fixed-by-tabview-youtube])')
  1092.  
  1093. if (autocomplete) {
  1094.  
  1095. const searchBox = document.querySelector('[placeholder-for-youtube-play-next-queue] input#suggestions-search')
  1096.  
  1097.  
  1098. if (searchBox) {
  1099.  
  1100.  
  1101. autocomplete.parentNode.setAttribute('position-fixed-by-tabview-youtube', '');
  1102. autocomplete.setAttribute('position-fixed-by-tabview-youtube', '');
  1103. autocomplete.setAttribute('userscript-scrollbar-render', '')
  1104.  
  1105. if (!searchBox.hasAttribute('is-set-click-to-toggle')) {
  1106. searchBox.setAttribute('is-set-click-to-toggle', '')
  1107. searchBox.addEventListener('click', function() {
  1108.  
  1109.  
  1110. setTimeout(() => {
  1111. const autocomplete = document.querySelector(`.autocomplete-suggestions[data-autocomplete-input-id="${ this.getAttribute('data-autocomplete-results-id') }"]`)
  1112.  
  1113. if (!autocomplete) return;
  1114.  
  1115. const isNotEmpty = (autocomplete.textContent || '').length > 0 && (this.value || '').length > 0;
  1116.  
  1117. if (isNotEmpty) {
  1118.  
  1119. let elmVisible = isDOMVisible(autocomplete)
  1120.  
  1121. if (elmVisible) $(autocomplete).hide();
  1122. else $(autocomplete).show();
  1123.  
  1124. }
  1125.  
  1126. }, 20);
  1127.  
  1128. })
  1129.  
  1130. let timeoutOnce_searchbox_keyup = new Timeout();
  1131. searchBox.addEventListener('keyup', function() {
  1132.  
  1133. timeoutOnce_searchbox_keyup.set(() => {
  1134.  
  1135. const autocomplete = document.querySelector(`.autocomplete-suggestions[data-autocomplete-input-id="${ this.getAttribute('data-autocomplete-results-id') }"]`)
  1136.  
  1137. if (!autocomplete) return;
  1138.  
  1139.  
  1140. const isNotEmpty = (autocomplete.textContent || '').length > 0 && (this.value || '').length > 0
  1141.  
  1142. if (isNotEmpty) {
  1143.  
  1144. let elmVisible = isDOMVisible(autocomplete)
  1145.  
  1146. if (!elmVisible) $(autocomplete).show();
  1147.  
  1148. }
  1149.  
  1150. }, 20);
  1151.  
  1152. })
  1153.  
  1154. }
  1155.  
  1156.  
  1157.  
  1158. }
  1159.  
  1160. }
  1161.  
  1162.  
  1163.  
  1164.  
  1165. let currentLastVideo = querySelectorFromAnchor.call(rootElement,'[placeholder-videos] #items ytd-compact-video-renderer:last-of-type')
  1166. let prevLastVideo = kRef(_cachedLastVideo);
  1167.  
  1168. if (prevLastVideo !== currentLastVideo && currentLastVideo) {
  1169. _cachedLastVideo = mWeakRef(currentLastVideo);
  1170. }
  1171.  
  1172. if (prevLastVideo !== currentLastVideo && currentLastVideo && prevLastVideo) {
  1173.  
  1174. let isPrevRemoved = !prevLastVideo.parentNode
  1175.  
  1176.  
  1177. function getVideoListHash() {
  1178.  
  1179. let res = [...document.querySelectorAll('[placeholder-videos] #items ytd-compact-video-renderer')].map(renderer => {
  1180. return renderer.querySelector('a[href*="watch"][href*="v="]').getAttribute('href')
  1181.  
  1182. }).join('|')
  1183. // /watch?v=XXXXX|/watch?v=XXXXXX|/watch?v=XXXXXX
  1184.  
  1185. // alternative - DOM.data.videoId
  1186. // let elms = document.querySelectorAll('[placeholder-videos] #items ytd-compact-video-renderer')
  1187. // let res = [...elms].map(elm=>elm.data.videoId||'').join('|') ;
  1188.  
  1189. if (res.indexOf('||') >= 0) {
  1190. res = '';
  1191. }
  1192.  
  1193. return res ? res : null;
  1194. }
  1195.  
  1196. if (isPrevRemoved) {
  1197.  
  1198. // this is the replacement of videos instead of addition
  1199.  
  1200. const searchBox = document.querySelector('[placeholder-for-youtube-play-next-queue] input#suggestions-search')
  1201.  
  1202. let currentPlayListHash = getVideoListHash() || null;
  1203.  
  1204. if (!currentPlayListHash) {
  1205.  
  1206. } else if (!videoListBeforeSearch && searchBox) {
  1207.  
  1208. videoListBeforeSearch = currentPlayListHash;
  1209. if (videoListBeforeSearch) {
  1210. //console.log('fromSearch', videoListBeforeSearch)
  1211.  
  1212. requestAnimationFrame(function() {
  1213.  
  1214. let renderer = document.querySelector('[placeholder-videos] ytd-watch-next-secondary-results-renderer');
  1215. if (searchBox && searchBox.parentNode) searchBox.blur();
  1216.  
  1217. if (renderer) {
  1218. let scrollParent = renderer.parentNode;
  1219. if (scrollParent.scrollHeight > scrollParent.offsetHeight) {
  1220. let targetTop = renderer.offsetTop;
  1221. if (searchBox && searchBox.parentNode == scrollParent) targetTop -= searchBox.offsetHeight
  1222. scrollParent.scrollTop = targetTop - scrollParent.firstChild.offsetTop;
  1223. }
  1224. }
  1225.  
  1226. });
  1227.  
  1228. }
  1229.  
  1230. } else if (videoListBeforeSearch) {
  1231.  
  1232. if (currentPlayListHash != videoListBeforeSearch) {
  1233.  
  1234. videoListBeforeSearch = null;
  1235. //console.log('fromSearch', videoListBeforeSearch)
  1236.  
  1237.  
  1238. }
  1239.  
  1240. }
  1241.  
  1242.  
  1243. }
  1244.  
  1245.  
  1246. }
  1247.  
  1248.  
  1249.  
  1250.  
  1251. }
  1252.  
  1253. function base_ChatExist() {
  1254.  
  1255. let ytdFlexyElm = kRef(ytdFlexy);
  1256. if (!scriptEnable || !ytdFlexyElm) return null;
  1257.  
  1258. // no mutation triggering if the changes are inside the iframe
  1259.  
  1260. // 1) Detection of #continuations inside iframe
  1261. // iframe ownerDocument is accessible due to same origin
  1262. // if the chatroom is collasped, no determination of live chat or replay (as no #continuations and somehow a blank iframe doc)
  1263.  
  1264. // 2) Detection of meta tag
  1265. // This is fastest but not reliable. It is somehow a bug that the navigation might not update the meta tag content
  1266.  
  1267. // 3) Detection of HTMLElement inside video player for live video
  1268.  
  1269. // (1)+(3) = solution
  1270.  
  1271. let attr_chatblock = null
  1272. let attr_chatcollapsed = null;
  1273.  
  1274. const elmChat = document.querySelector('ytd-live-chat-frame#chat')
  1275. let elmCont = null;
  1276. if (elmChat) {
  1277. elmCont = chatFrameElement('yt-live-chat-renderer #continuations')
  1278.  
  1279.  
  1280. let s = 0;
  1281. if (elmCont) {
  1282. //not found if it is collasped.
  1283. s |= querySelectorFromAnchor.call(elmCont,'yt-timed-continuation') ? 1 : 0;
  1284. s |= querySelectorFromAnchor.call(elmCont,'yt-live-chat-replay-continuation, yt-player-seek-continuation') ? 2 : 0;
  1285. //s |= elmCont.querySelector('yt-live-chat-restricted-participation-renderer')?4:0;
  1286. if (s == 1) {
  1287. attr_chatblock = 'chat-live';
  1288. }else if (s == 2) attr_chatblock = 'chat-playback';
  1289.  
  1290. if (s == 1) $("span#tab3-txt-loader").text('');
  1291.  
  1292. } else if (!ytdFlexyElm.hasAttribute('userscript-chatblock')) {
  1293. // live chat frame but type not known
  1294. attr_chatblock = '';
  1295.  
  1296. }
  1297. //keep unknown as original
  1298. let isCollapsed = !!elmChat.hasAttribute('collapsed');
  1299. attr_chatcollapsed = isCollapsed;
  1300.  
  1301. } else {
  1302. attr_chatblock = false;
  1303. attr_chatcollapsed = false;
  1304.  
  1305. }
  1306.  
  1307. return { attr_chatblock, attr_chatcollapsed }
  1308.  
  1309. }
  1310.  
  1311.  
  1312. function mtf_ChatExist() {
  1313.  
  1314. let ytdFlexyElm = kRef(ytdFlexy);
  1315. if (!scriptEnable || !ytdFlexyElm) return;
  1316.  
  1317. if (deferredVarYTDHidden) return;
  1318.  
  1319. const elmChat = document.querySelector('ytd-live-chat-frame#chat')
  1320. let elmCont = null;
  1321. if (elmChat) {
  1322. elmCont = chatFrameElement('yt-live-chat-renderer #continuations')
  1323. }
  1324.  
  1325. const chatBlockR = (elmChat ? 1 : 0) + (elmCont ? 2 : 0)
  1326. if (Q.mtf_chatBlockQ !== chatBlockR) {
  1327. Q.mtf_chatBlockQ = chatBlockR
  1328. let rChatExist = base_ChatExist();
  1329. //console.log(2446, rChatExist)
  1330. if (rChatExist) {
  1331. let { attr_chatblock, attr_chatcollapsed } = rChatExist;
  1332. wAttr(ytdFlexyElm, 'userscript-chatblock', attr_chatblock)
  1333. wAttr(ytdFlexyElm, 'userscript-chat-collapsed', attr_chatcollapsed)
  1334. if(attr_chatblock=='chat-live') _disableComments();
  1335. }
  1336. }
  1337.  
  1338. }
  1339.  
  1340.  
  1341.  
  1342.  
  1343. let lastScrollAt1 = 0;
  1344.  
  1345. function makeBodyScrollByEvt() {
  1346. let ct = Date.now();
  1347. if (ct - lastScrollAt1 < 6) return; // avoid duplicate calling
  1348. lastScrollAt1 = ct;
  1349. window.dispatchEvent(new Event("scroll")); // dispatch Scroll Event to Window for content display
  1350. }
  1351.  
  1352. let lastScrollAt2 = 0;
  1353.  
  1354. function makeBodyScroll() {
  1355. let ct = Date.now();
  1356. if (ct - lastScrollAt2 < 30) return; // avoid over triggering
  1357. lastScrollAt2 = ct;
  1358. requestAnimationFrame(() => {
  1359. window.dispatchEvent(new Event("scroll")); // ask youtube to display content
  1360. })
  1361. }
  1362.  
  1363. //let requestingComments = null
  1364. //let scrollForComments_lastStart = 0;
  1365. /*
  1366. function scrollForComments_TF() {
  1367. let comments = requestingComments;
  1368. if (!comments) return;
  1369. if (comments.hasAttribute('hidden')) {
  1370. window.dispatchEvent(new Event("scroll"));
  1371. } else requestingComments = null;
  1372.  
  1373. }
  1374. function scrollForComments() {
  1375. scrollForComments_TF();
  1376. if (!requestingComments) return;
  1377. requestAnimationFrame(scrollForComments_TF);
  1378. let ct = Date.now();
  1379. if (ct - scrollForComments_lastStart < 60) return;
  1380. scrollForComments_lastStart = ct;
  1381. timeline.setTimeout(scrollForComments_TF, 80);
  1382. timeline.setTimeout(scrollForComments_TF, 240);
  1383. timeline.setTimeout(scrollForComments_TF, 870);
  1384. }
  1385. */
  1386.  
  1387.  
  1388.  
  1389. const mtoCs = { mtoNav: null, mtoBody: null };
  1390.  
  1391.  
  1392. const mtoVs = {}
  1393.  
  1394. const mutation_target_id_list = ['ytp-caption-window-container', 'items', 'button', 'movie_player', 'player-ads', 'hover-overlays', 'replies'];
  1395. const mutation_target_class_list = ['ytp-panel-menu', 'ytp-endscreen-content'];
  1396.  
  1397. function isMtoOverallSkip(dTarget) {
  1398.  
  1399. if (!dTarget || dTarget.nodeType !== 1) return true;
  1400.  
  1401. if (mutation_target_id_list.includes(dTarget.id)) return true;
  1402.  
  1403. for (const c of dTarget.classList) {
  1404. if (mutation_target_class_list.includes(c)) return true;
  1405. }
  1406.  
  1407. return false;
  1408. }
  1409.  
  1410.  
  1411. const mutation_div_id_ignorelist = [
  1412. 'metadata-line',
  1413. 'ytp-caption-window-container',
  1414. 'top-level-buttons-computed',
  1415. 'microformat',
  1416. 'visibility-button',
  1417. 'info-strings',
  1418. 'action-menu',
  1419. 'reply-button-end'
  1420. ];
  1421.  
  1422. const mutation_div_class_ignorelist = [
  1423. 'badge', 'tp-yt-paper-tooltip', 'ytp-autonav-endscreen-upnext-header',
  1424. 'ytp-bound-time-left', 'ytp-bound-time-right', 'ytp-share-icon',
  1425. 'ytp-tooltip-title', 'annotation', 'ytp-copylink-icon', 'ytd-thumbnail',
  1426. 'paper-ripple',
  1427. //caption
  1428. 'captions-text', 'caption-visual-line', 'ytp-caption-segment', 'ytp-caption-window-container',
  1429. //menu
  1430. 'ytp-playlist-menu-button-text',
  1431.  
  1432. 'ytp-bezel-icon', 'ytp-bezel-text',
  1433. 'dropdown-content',
  1434. 'tp-yt-paper-menu-button', 'tp-yt-iron-dropdown',
  1435.  
  1436. 'ytd-metadata-row-renderer', // #content.ytd-metadata-row-renderer inside each of ytd-metadata-row-renderer (ytd-expander)
  1437. 'ytd-engagement-panel-section-list-renderer', // {div#content.style-scope.ytd-engagement-panel-section-list-renderer} inside each of ytd-engagement-panel-section-list-renderer
  1438.  
  1439. 'autocomplete-suggestions' // autocomplete-suggestions
  1440. ];
  1441.  
  1442. const mutation_target_tag_ignorelist = [
  1443. 'ytd-channel-name', 'tp-yt-iron-dropdown', 'tp-yt-paper-tooltip',
  1444. 'tp-yt-paper-listbox', 'yt-img-shadow', 'ytd-thumbnail', 'ytd-video-meta-block',
  1445.  
  1446. 'yt-icon-button', 'tp-yt-paper-button', 'yt-formatted-string', 'yt-icon', 'button', 'paper-ripple',
  1447.  
  1448. 'ytd-player-microformat-renderer',
  1449. 'ytd-engagement-panel-section-list-renderer', 'ytd-engagement-panel-title-header-renderer',
  1450. 'ytd-comment-renderer', 'ytd-menu-renderer', 'ytd-badge-supported-renderer',
  1451. 'ytd-subscribe-button-renderer', 'ytd-subscription-notification-toggle-button-renderer',
  1452. 'ytd-button-renderer', 'ytd-toggle-button-renderer',
  1453. 'yt-pdg-comment-chip-renderer', 'ytd-comment-action-buttons-renderer', 'ytd-comment-thread-renderer',
  1454. 'ytd-compact-radio-renderer', 'ytd-compact-video-renderer',
  1455. 'ytd-video-owner-renderer',
  1456. 'ytd-metadata-row-renderer', //ytd-metadata-row-renderer is part of the #collapsible inside ytd-expander
  1457.  
  1458. 'ytd-moving-thumbnail-renderer',
  1459. 'ytd-thumbnail-overlay-toggle-button-renderer',
  1460. 'ytd-thumbnail-overlay-bottom-panel-renderer', 'ytd-thumbnail-overlay-equalizer',
  1461. 'ytd-thumbnail-overlay-now-playing-renderer', 'ytd-thumbnail-overlay-resume-playback-renderer',
  1462. 'ytd-thumbnail-overlay-side-panel-renderer', 'ytd-thumbnail-overlay-time-status-renderer',
  1463. 'ytd-thumbnail-overlay-hover-text-renderer',
  1464.  
  1465. 'yt-interaction',
  1466. 'tp-yt-paper-spinner-lite', 'tp-yt-paper-spinner',
  1467.  
  1468. 'h1', 'h2', 'h3', 'h4', 'h5', 'span', 'a',
  1469.  
  1470. 'meta', 'br', 'script', 'style', 'link', 'dom-module', 'template'
  1471. ];
  1472.  
  1473. function isMtoTargetSkip(mutation) {
  1474. //skip not important mutation tartget
  1475.  
  1476. if (!mutation) return true;
  1477. let { type, target } = mutation
  1478.  
  1479. if (!target || target.nodeType !== 1 || type != 'childList') return true;
  1480.  
  1481. let tagName = target.nodeName.toLowerCase();
  1482.  
  1483. if (mutation_target_tag_ignorelist.includes(tagName)) return true;
  1484.  
  1485. switch (tagName) {
  1486.  
  1487.  
  1488. case 'ytd-expander':
  1489. if (target.id == 'expander' && Q.comments_section_loaded == 1 && target.classList.contains('ytd-comment-renderer')) return true; // load comments
  1490. return false;
  1491.  
  1492. case 'div':
  1493.  
  1494. if (target.id == 'contents') {
  1495. return false;
  1496. }
  1497. if (mutation_div_id_ignorelist.includes(target.id)) return true;
  1498.  
  1499. for (const c of target.classList) {
  1500. if (mutation_div_class_ignorelist.includes(c)) return true;
  1501. }
  1502.  
  1503. return false;
  1504.  
  1505. }
  1506.  
  1507. return false;
  1508.  
  1509. }
  1510.  
  1511.  
  1512. function mtf_forceCheckLiveVideo() {
  1513. // once per $$player-playback-timestamp$$ {#ytd-player .ytp-time-display} && $$chat-frame$$ {ytd-live-chat-frame#chat} detection
  1514. // reset after popstatechange / videochange
  1515.  
  1516. if(mtf_forceCheckLiveVideo_disable) return ;
  1517.  
  1518. let ytdFlexyElm = kRef(ytdFlexy);
  1519. if (!scriptEnable || !ytdFlexyElm) return ;
  1520.  
  1521. const playerLabel = document.querySelector('ytd-watch-flexy:not([hidden]) #ytd-player .ytp-time-display') && document.querySelector('ytd-watch-flexy:not([hidden]) ytd-live-chat-frame#chat')
  1522. if (!playerLabel) return ;
  1523. mtf_forceCheckLiveVideo_disable = 1;
  1524. timeline.setTimeout(FP.fireOnce_forceCheckLiveVideo_tf, 170)
  1525. return ;
  1526. }
  1527.  
  1528. // continuous check for element relocation
  1529. function mtf_append_comments() {
  1530. /** @type {HTMLElement | null} */
  1531. let ytdFlexyElm = kRef(ytdFlexy);
  1532. if (!scriptEnable || !ytdFlexyElm) return;
  1533.  
  1534. /** @type {HTMLElement | null} */
  1535. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1536.  
  1537. let comments = querySelectorFromAnchor.call(rootElement,'#primary ytd-watch-metadata ~ ytd-comments#comments');
  1538. if (comments) $(comments).appendTo('#tab-comments').attr('data-dom-changed-by-tabview-youtube', scriptVersionForExternal)
  1539. }
  1540.  
  1541. // continuous check for element relocation
  1542. function mtf_liveChatBtnF() {
  1543. /** @type {HTMLElement | null} */
  1544. let ytdFlexyElm = kRef(ytdFlexy);
  1545. if (!scriptEnable || !ytdFlexyElm) return;
  1546.  
  1547. /** @type {HTMLElement | null} */
  1548. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1549.  
  1550. let button = querySelectorFromAnchor.call(rootElement,'ytd-live-chat-frame#chat > .ytd-live-chat-frame#show-hide-button:nth-child(n+2)');
  1551. if (button) button.parentNode.insertBefore(button, button.parentNode.firstChild)
  1552. }
  1553.  
  1554.  
  1555.  
  1556. // continuous check for element relocation
  1557. // fired at begining & window resize, etc
  1558. function mtf_append_playlist() {
  1559.  
  1560. /** @type {HTMLElement | null} */
  1561. let ytdFlexyElm = kRef(ytdFlexy);
  1562. if (!scriptEnable || !ytdFlexyElm) return;
  1563.  
  1564. /** @type {HTMLElement | null} */
  1565. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1566.  
  1567. let ple1 = querySelectorFromAnchor.call(rootElement,"*:not(#ytd-userscript-playlist) > ytd-playlist-panel-renderer#playlist");
  1568. if (ple1) {
  1569. let ct = Date.now();
  1570. let truePlaylist = null;
  1571. let truePlaylist_items = document.querySelector('ytd-playlist-panel-renderer#playlist #items:not(:empty)');
  1572. if (truePlaylist_items) {
  1573.  
  1574. let pElm = truePlaylist_items.parentNode;
  1575. while (pElm && pElm.nodeType === 1) {
  1576. if (pElm.id == 'playlist') {
  1577. pElm.setAttribute('tabview-true-playlist', ct)
  1578. truePlaylist = pElm;
  1579. break;
  1580. }
  1581. pElm = pElm.parentNode;
  1582. }
  1583.  
  1584. }
  1585.  
  1586. if (!truePlaylist) truePlaylist = ple1; // NOT NULL
  1587.  
  1588. for (const s of document.querySelectorAll(`*:not(#ytd-userscript-playlist) > ytd-playlist-panel-renderer#playlist:not([tabview-true-playlist="${ct}"])`))
  1589. s.parentNode.removeChild(s);
  1590.  
  1591. let $wrapper = getWrapper('ytd-userscript-playlist')
  1592. $wrapper.append(truePlaylist).appendTo(document.querySelector("#tab-list"));
  1593. truePlaylist.setAttribute('data-dom-changed-by-tabview-youtube', scriptVersionForExternal)
  1594. setDisplayedPlaylist(); // relocation after re-layout
  1595.  
  1596. requestAnimationFrame(() => {
  1597. let ytdFlexyElm = kRef(ytdFlexy);
  1598. if (!scriptEnable || !ytdFlexyElm) return;
  1599. if (!switchTabActivity_lastTab && (ytdFlexyElm.getAttribute('tabview-selection') + '').indexOf('#tab-') === 0 && /https\:\/\/www\.youtube\.com\/watch.*[\?\&]list=[\w\-\_]+/.test(location.href)) {
  1600. if (setToActiveTab('#tab-list')) switchTabActivity_lastTab = '#tab-list';
  1601. }
  1602. })
  1603.  
  1604. }
  1605. }
  1606.  
  1607.  
  1608. // content fix - info & playlist
  1609. // fired at begining, and keep for in case any change
  1610. function mtf_fix_details() {
  1611.  
  1612. if (!scriptEnable) return;
  1613.  
  1614. if (no_fix_contents_until < Date.now()) {
  1615. if (document.querySelector('#tab-info ytd-expander > #content')) {
  1616. no_fix_contents_until = Date.now() + 3000;
  1617. timeline.setTimeout(function() {
  1618. const expander = document.querySelector('ytd-watch-flexy #tab-info ytd-expander');
  1619. if(!expander || expander.nodeType!==1) return;
  1620. if(expander.style.getPropertyValue('--ytd-expander-collapsed-height')){
  1621. expander.style.setProperty('--ytd-expander-collapsed-height','')
  1622. }else{
  1623.  
  1624. if (expander.hasAttribute('collapsed')) wAttr(expander, 'collapsed', false);
  1625. expander.style.setProperty('--ytd-expander-collapsed-height', '');
  1626.  
  1627. let btn1 = querySelectorFromAnchor.call(expander,'tp-yt-paper-button#less:not([hidden])');
  1628. let btn2 = querySelectorFromAnchor.call(expander,'tp-yt-paper-button#more:not([hidden])');
  1629.  
  1630. if (btn1) wAttr(btn1, 'hidden', true);
  1631. if (btn2) wAttr(btn2, 'hidden', true);
  1632. }
  1633. }, 40);
  1634.  
  1635. }
  1636. }
  1637.  
  1638. if (no_fix_playlist_until < Date.now()) {
  1639. // just in case the playlist is collapsed
  1640. const playlist = document.querySelector('#tab-list ytd-playlist-panel-renderer#playlist')
  1641. if (playlist) {
  1642. no_fix_playlist_until = Date.now() + 3000;
  1643. timeline.setTimeout(function() {
  1644. if (playlist.hasAttribute('collapsed')) wAttr(playlist, 'collapsed', false);
  1645. if (playlist.hasAttribute('collapsible')) wAttr(playlist, 'collapsible', false);
  1646. }, 40)
  1647. }
  1648. }
  1649.  
  1650.  
  1651. }
  1652.  
  1653.  
  1654.  
  1655. function isNullComments() {
  1656.  
  1657. let comments = document.querySelector('ytd-comments#comments')
  1658. if (!comments || comments.hasAttribute('hidden')) return true;
  1659.  
  1660. }
  1661.  
  1662. function _innerCommentsLoader( /** @type {HTMLElement} */ rootElement) {
  1663.  
  1664. /** @type {HTMLElement | null} */
  1665. let ytdFlexyElm = kRef(ytdFlexy);
  1666. if (!scriptEnable || !ytdFlexyElm) return;
  1667. if (deferredVarYTDHidden) return;
  1668.  
  1669.  
  1670. let messageElm, messageStr, commentRenderer;
  1671. let diffCSS = `[tabview-cache-time="${sect_hTime}"]`
  1672.  
  1673. if (commentRenderer = querySelectorFromAnchor.call(rootElement,`ytd-comments#comments #count.ytd-comments-header-renderer:not(${diffCSS})`)) {
  1674.  
  1675. scheduledCommentRefresh=false;
  1676. let eTime = Date.now();
  1677.  
  1678. sect_holder = mWeakRef(commentRenderer);
  1679. sect_hText = commentRenderer.textContent;
  1680. sect_hTime = eTime;
  1681. commentRenderer.setAttribute('tabview-cache-time', eTime);
  1682.  
  1683. return {
  1684. status: 1,
  1685. f: () => {
  1686.  
  1687. let span = document.querySelector("span#tab3-txt-loader")
  1688. let r = '0';
  1689. let txt = commentRenderer.textContent
  1690. if (typeof txt == 'string') {
  1691. let m = txt.match(/[\d\,\s]+/)
  1692. if (m) {
  1693. r = m[0].trim()
  1694.  
  1695.  
  1696. }
  1697. }
  1698. if (span){
  1699.  
  1700. let tab_btn = span.closest('.tab-btn[userscript-tab-content="#tab-comments"]')
  1701. if(tab_btn)tab_btn.setAttribute('loaded-comment','normal')
  1702. span.textContent = r;
  1703. }
  1704. //console.log(754)
  1705. mtoInterval = mtoInterval2;
  1706. scheduledCommentRefresh=false;
  1707. setCommentSection(1);
  1708. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents'))
  1709. }
  1710. }
  1711.  
  1712. } else if ((messageElm = querySelectorFromAnchor.call(rootElement,`ytd-item-section-renderer#sections #header ~ #contents > ytd-message-renderer:not(${diffCSS})`)) && (messageStr = (messageElm.textContent || '').trim())) { //ytd-message-renderer
  1713. // it is possible to get the message before the header generation.
  1714. // sample link - https://www.youtube.com/watch?v=PVUZ8Nvr1ic
  1715. // sample link - https://www.youtube.com/watch?v=yz8AiQc1Bk8
  1716.  
  1717. scheduledCommentRefresh=false;
  1718. let eTime = Date.now();
  1719.  
  1720. sect_holder = mWeakRef(messageElm);
  1721. sect_hText = messageElm.textContent;
  1722. sect_hTime = eTime;
  1723. messageElm.setAttribute('tabview-cache-time', eTime);
  1724.  
  1725. return {
  1726. status: 2,
  1727. f: () => {
  1728. timeline.setTimeout(function() {
  1729. let span = document.querySelector("span#tab3-txt-loader")
  1730. const mainMsg = querySelectorFromAnchor.call(messageElm,'#message, #submessage')
  1731. if (mainMsg && mainMsg.textContent) {
  1732. for (const msg of querySelectorAllFromAnchor.call(mainMsg,'*:not(:empty)')) {
  1733. if (msg.childElementCount === 0 && msg.textContent) {
  1734. messageStr = msg.textContent.trim()
  1735. break
  1736. }
  1737. }
  1738. }
  1739. if (span){
  1740. let tab_btn = span.closest('.tab-btn[userscript-tab-content="#tab-comments"]')
  1741. if(tab_btn)tab_btn.setAttribute('loaded-comment','message')
  1742. span.textContent ='\u200B';
  1743. }
  1744. mtoInterval = mtoInterval2;
  1745. scheduledCommentRefresh=false;
  1746. setCommentSection(1);
  1747. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents'))
  1748. }, 40);
  1749. }
  1750. }
  1751.  
  1752. }
  1753.  
  1754. }
  1755.  
  1756. const atChange = async ()=>{
  1757.  
  1758. // call when video change / popstate change / switch back from mini-view
  1759.  
  1760. let ytdFlexyElm = kRef(ytdFlexy);
  1761. if(!ytdFlexyElm) return;
  1762.  
  1763. mtf_forceCheckLiveVideo_disable = 0;
  1764. mtf_forceCheckLiveVideo();
  1765.  
  1766. if(Q.comments_section_loaded===0){
  1767.  
  1768. const tabBtn = document.querySelector('[userscript-tab-content="#tab-comments"].tab-btn-hidden')
  1769. if(tabBtn) {
  1770. tabBtn.classList.remove("tab-btn-hidden") //if contains
  1771. }
  1772.  
  1773. }
  1774. }
  1775.  
  1776.  
  1777.  
  1778. function hookSection(){
  1779.  
  1780.  
  1781. //console.log(3300)
  1782.  
  1783. let ytdFlexyElm = kRef(ytdFlexy);
  1784. if (!scriptEnable || !ytdFlexyElm) return ;
  1785.  
  1786. const comments = querySelectorFromAnchor.call(ytdFlexyElm,'ytd-comments#comments')
  1787. if (!comments) return ;
  1788.  
  1789. if(deferredVarYTDHidden) return;
  1790.  
  1791. //console.log(3310)
  1792.  
  1793. //new MutationObserver(function(){console.log(comments.querySelectorAll('*').length)}).observe(comments,{ attributes: true, childList: true, subtree: true })
  1794.  
  1795. function foundSection(sections){
  1796.  
  1797. //console.log(3320)
  1798.  
  1799. function ulfx() {
  1800. //console.log(1220)
  1801.  
  1802.  
  1803. const rootElement = comments.parentNode
  1804.  
  1805.  
  1806. if (pendingOne && querySelectorAllFromAnchor.call(comments,'[tabview-cache-time]').length > 1) return;
  1807. pendingOne = false;
  1808. if(!rootElement) return; //prevent unknown condition
  1809.  
  1810.  
  1811. let innerCommentsLoaderRet = _innerCommentsLoader(rootElement);
  1812.  
  1813. //console.log(1222,_innerCommentsLoader)
  1814.  
  1815. if (!innerCommentsLoaderRet) {
  1816.  
  1817.  
  1818. let holder = kRef(sect_holder);
  1819. if (holder && comments.contains(holder)) {
  1820.  
  1821. if (sect_lastUpdate) return;
  1822. sect_lastUpdate = 1;
  1823.  
  1824. timeline.setTimeout(function() {
  1825. //console.log(2633)
  1826. if (holder.textContent !== sect_hText && sect_hTime > 0) {
  1827.  
  1828. if (querySelectorAllFromAnchor.call(comments,'[tabview-cache-time]').length === 1) {
  1829.  
  1830. sect_hTime--;
  1831.  
  1832. let innerCommentsLoaderRet = _innerCommentsLoader(rootElement);
  1833.  
  1834. if (innerCommentsLoaderRet) {
  1835. //console.log(9442)
  1836. innerCommentsLoaderRet.f();
  1837. fetchCommentsFinished();
  1838. }
  1839.  
  1840. pendingOne = false;
  1841.  
  1842. }
  1843.  
  1844.  
  1845. }
  1846. sect_lastUpdate = 0
  1847. }, 400)
  1848.  
  1849. } else if (sect_holder) {
  1850. sect_holder = null
  1851. sect_hTime = 0;
  1852. sect_lastUpdate = 0;
  1853. pendingOne = false;
  1854. timeline.setTimeout(()=>{
  1855. if(!deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0 && comments.hasAttribute('hidden')){
  1856.  
  1857. scheduledCommentRefresh=false; // logic tbc
  1858. resetCommentSection();
  1859. }
  1860. },142);
  1861. Q.mutationTarget=null;
  1862. FP.mtf_attrComments(); // in case for popstate
  1863. }
  1864.  
  1865.  
  1866. } else {
  1867.  
  1868. //console.log(9443)
  1869. innerCommentsLoaderRet.f();
  1870. fetchCommentsFinished();
  1871.  
  1872. pendingOne = true;
  1873.  
  1874. }
  1875.  
  1876.  
  1877.  
  1878. }
  1879.  
  1880. function observerHook(mutationsList, observer){
  1881.  
  1882. let valid = false
  1883. for (const mutation of mutationsList) {
  1884.  
  1885. let target = mutation.target;
  1886. if (!target) break;
  1887. if (!target.id) break;
  1888. let classList = target.classList;
  1889.  
  1890.  
  1891. if (
  1892. classList.contains('ytd-item-section-renderer') ||
  1893. classList.contains('ytd-comments-header-renderer') ||
  1894. classList.contains('ytd-message-renderer')) {
  1895. valid = true
  1896. break;
  1897. }
  1898.  
  1899. break; // only outest mutation
  1900.  
  1901.  
  1902. }
  1903. if (valid) ulfx();
  1904. }
  1905.  
  1906. if(sections.hasAttribute('tabview-comment-section-checked')){
  1907.  
  1908. //console.log(3612)
  1909. ulfx();
  1910.  
  1911. }else{
  1912.  
  1913. pendingOne = false;
  1914. //console.log(3611)
  1915. const observer = new MutationObserver(observerHook)
  1916. sections.setAttribute('tabview-comment-section-checked','')
  1917. const config = { childList: true, subtree: true };
  1918. observer.observe(sections, config);
  1919. ulfx();
  1920.  
  1921.  
  1922. }
  1923.  
  1924.  
  1925.  
  1926. }
  1927. //console.log(3241, location.href)
  1928. let cid_render_section = timeline.setInterval(function() {
  1929.  
  1930. // console.log(3244, location.href)
  1931.  
  1932.  
  1933. const rootElement = comments.parentNode
  1934.  
  1935. let sections = querySelectorFromAnchor.call(rootElement,'ytd-comments#comments > ytd-item-section-renderer#sections');
  1936.  
  1937.  
  1938. if (sections) {
  1939.  
  1940. timeline.clearInterval(cid_render_section);
  1941. foundSection(sections);
  1942.  
  1943. }
  1944.  
  1945. }, 30)
  1946.  
  1947.  
  1948.  
  1949. }
  1950.  
  1951.  
  1952. let mtc_store=0;
  1953. let mtc_cid = 0;
  1954. const cssOnceFunc = {
  1955. [`ytd-comments#comments:not([o3r-${sa_comments}])`]:(comments)=>{
  1956. // once per {ytd-comments#comments} detection
  1957.  
  1958. let ytdFlexyElm = kRef(ytdFlexy);
  1959. if (!scriptEnable || !ytdFlexyElm) return;
  1960.  
  1961. if (!comments) return;
  1962.  
  1963.  
  1964.  
  1965.  
  1966. if(mtoVisibility_Comments.bindElement(comments)){
  1967. mtoVisibility_Comments.observer.check(9);
  1968. }
  1969. pageInit_attrComments = true
  1970. hookSection();
  1971.  
  1972. //let dComments = comments
  1973. //timeline.setTimeout(() => nativeFunc(dComments, "loadComments"), 20)
  1974. //comments = null;
  1975.  
  1976. },
  1977. [`ytd-playlist-panel-renderer#playlist:not([o3r-${sa_playlist}])`]:(playlist)=>{
  1978.  
  1979. // once per {ytd-playlist-panel-renderer#playlist} detection
  1980.  
  1981. let ytdFlexyElm = kRef(ytdFlexy);
  1982. if (!scriptEnable || !ytdFlexyElm) return;
  1983.  
  1984. if (!playlist) return;
  1985.  
  1986. if(mtoVisibility_Playlist.bindElement(playlist)){
  1987. mtoVisibility_Playlist.observer.check(9) //delay check required for browser bug - hidden changed not triggered
  1988. }
  1989. playlist = null;
  1990.  
  1991. return;
  1992.  
  1993. },
  1994. '#meta-contents ytd-expander:not([tabview-info-expander])':(expander)=>{
  1995.  
  1996. // once per $$native-info-description$$ {#meta-contents ytd-expander} detection
  1997.  
  1998. let ytdFlexyElm = kRef(ytdFlexy);
  1999. if (!scriptEnable || !ytdFlexyElm) return ;
  2000.  
  2001. if (!expander) return ;
  2002. expander.setAttribute('tabview-info-expander','')
  2003. $(expander).appendTo("#tab-info").attr('data-dom-changed-by-tabview-youtube', scriptVersionForExternal)
  2004.  
  2005. },
  2006. '#description-and-actions.style-scope.ytd-watch-metadata > #description ytd-text-inline-expander:not([tabview-removed-duplicate])': (teaserInfo)=>{
  2007.  
  2008.  
  2009. // for Teaser UI
  2010. // once per {#description-and-actions.style-scope.ytd-watch-metadata > #description > ytd-text-inline-expander} detection
  2011.  
  2012. let ytdFlexyElm = kRef(ytdFlexy);
  2013. if (!scriptEnable || !ytdFlexyElm) return ;
  2014. let addedInfo = document.querySelector('#tab-info ytd-expander[tabview-info-expander]');
  2015.  
  2016. if(!addedInfo) return;
  2017.  
  2018. if(!document.documentElement.hasAttribute('tabview-injection-js-1-ready')) return;
  2019.  
  2020. teaserInfo.setAttribute('tabview-removed-duplicate','')
  2021.  
  2022.  
  2023. teaserInfo.dispatchEvent(new CustomEvent('tabview-no-duplicate-info'))
  2024. //console.log(56)
  2025.  
  2026. }
  2027. }
  2028. const cssOnce = Object.keys(cssOnceFunc).join(', ')
  2029.  
  2030. const regularCheck = (addP, removeP, mutationTarget)=>{
  2031.  
  2032.  
  2033. let isInvalidAdding = mutationTarget && !mutationTarget.parentNode
  2034.  
  2035. let promisesForAddition = !scriptEnable ? [] : addP > 0 && !isInvalidAdding ? [
  2036.  
  2037. (async () => {
  2038.  
  2039. //$callOnce('mtf_checkFlexy');
  2040.  
  2041. const rootElement = Q.mutationTarget || kRef(ytdFlexy);
  2042.  
  2043. if(rootElement){
  2044.  
  2045. let fElms = querySelectorAllFromAnchor.call(rootElement,cssOnce)
  2046. if(fElms.length>0){
  2047.  
  2048. for(const fElm of fElms){
  2049. for(let cssSelctor in cssOnceFunc){
  2050. if(fElm.matches(cssSelctor)){
  2051. let f= cssOnceFunc[cssSelctor]
  2052. if(typeof f=='function') f(fElm);
  2053. break;
  2054. }
  2055.  
  2056. }
  2057. }
  2058.  
  2059. //$callOnce('mtf_initalAttr_comments');
  2060. //$callOnce('mtf_initalAttr_playlist');
  2061. // $callOnce('mtf_checkDescriptionLoaded');
  2062. }
  2063.  
  2064. }
  2065.  
  2066. })(),
  2067. (async () => {
  2068.  
  2069.  
  2070. FP.mtf_initalAttr_chatroom();
  2071. FP.mtf_initalAttr_engagement_panel();
  2072. //$callOnce('mtf_initalAttr_chatroom');
  2073. // $callOnce('mtf_initalAttr_engagement_panel');
  2074.  
  2075. mtf_forceCheckLiveVideo();
  2076. mtf_append_comments();
  2077. mtf_liveChatBtnF();
  2078. fixTabs();
  2079. mtf_AfterFixTabs();
  2080. mtf_append_playlist();
  2081.  
  2082. })()
  2083.  
  2084. ] : [];
  2085. let promisesForEveryMutation = !scriptEnable ? [] : [
  2086. (async () => {
  2087. mtf_fix_details();
  2088. mtf_ChatExist();
  2089. })()
  2090. ];
  2091.  
  2092. return [...promisesForAddition, ...promisesForEveryMutation]
  2093.  
  2094.  
  2095. }
  2096.  
  2097. function setOnlyOneEPanel(ePanel){
  2098.  
  2099. layoutStatusMutex.lockWith(unlock => {
  2100.  
  2101. let cPanels = engagement_panels_();
  2102. for (const entry of cPanels.list) {
  2103. if (entry.ePanel != ePanel && entry.visible) ytBtnCloseEngagementPanel(entry.ePanel);
  2104. }
  2105. setTimeout(unlock, 30)
  2106.  
  2107. })
  2108.  
  2109. }
  2110.  
  2111. const FP = {
  2112.  
  2113. mtoNav_delayedF: () => {
  2114.  
  2115. let { addP, removeP, mutationTarget } = Q;
  2116.  
  2117. Q.addP = 0;
  2118. Q.removeP = 0;
  2119. mtc_store=Date.now()+1870
  2120.  
  2121.  
  2122. let regularChecks = regularCheck(addP, removeP, mutationTarget);
  2123.  
  2124. Promise.all(regularChecks).then(() => {
  2125. regularChecks = null;
  2126. mtc_store= Date.now() + 3870 // pending Comments start to load
  2127. Q.mutationTarget = null;
  2128.  
  2129. Q.mtoNav_requestNo--;
  2130. //console.log('motnav reduced to', mtoNav_requestNo)
  2131. if (Q.mtoNav_requestNo > 0) {
  2132. Q.mtoNav_requestNo = 1;
  2133. setTimeout(FP.mtoNav_delayedF, mtoInterval);
  2134. }
  2135. })
  2136.  
  2137.  
  2138. },
  2139.  
  2140. mtoNavF: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  2141. //subtree DOM mutation checker - {ytd-watch-flexy} \single \subtree
  2142.  
  2143. newVideoPageCheck()
  2144.  
  2145. if (!scriptEnable) return;
  2146. if (deferredVarYTDHidden) return;
  2147.  
  2148. let ch = false;
  2149.  
  2150. let reg = [];
  2151. let dTarget = null;
  2152.  
  2153. let wAddP = 0,
  2154. wRemoveP = 0;
  2155.  
  2156. let _last_mto_target = null;
  2157. let _last_mto_target_valid = null;
  2158.  
  2159. for (const mutation of mutations) {
  2160. if (!mutation || !mutation.target || !mutation.target.parentNode) continue;
  2161.  
  2162. let elementalMutation = false;
  2163. let tAddP = 0,
  2164. tRemoveP = 0;
  2165.  
  2166. for (const addedNode of mutation.addedNodes) { //theoretically faster: only reading of states
  2167. if (addedNode.nodeType === 1) {
  2168. tAddP++;
  2169. elementalMutation = true;
  2170. }
  2171. }
  2172.  
  2173. for (const removedNode of mutation.removedNodes) { //theoretically faster: only reading of states
  2174. if (removedNode.nodeType === 1) {
  2175. tRemoveP++;
  2176. elementalMutation = true;
  2177. }
  2178. }
  2179.  
  2180. if (elementalMutation) { //skip all addition and removal operations without elemental changes (e.g. textNode modification)
  2181.  
  2182. if (_last_mto_target === mutation.target) {
  2183. // due to addition and removal operations to the same DOM
  2184. if (_last_mto_target_valid) {
  2185. // AddP & RemoveP is still valid
  2186. wAddP += tAddP;
  2187. wRemoveP += tRemoveP;
  2188. }
  2189. continue;
  2190. }
  2191. _last_mto_target = mutation.target;
  2192.  
  2193. if (isMtoTargetSkip(mutation)) {
  2194. _last_mto_target_valid = false;
  2195. continue; //theoretically slower: creation of string variables
  2196. } else {
  2197. _last_mto_target_valid = true;
  2198. wAddP += tAddP;
  2199. wRemoveP += tRemoveP;
  2200. }
  2201.  
  2202.  
  2203.  
  2204. ch = true;
  2205.  
  2206. reg.push(mutation);
  2207.  
  2208. if (dTarget === null) dTarget = mutation.target; //first
  2209. else if (dTarget === true) {} //ytdFlexy
  2210. else if (dTarget.contains(mutation.target)) {} //first node is the container to all subsequential targets
  2211. else { dTarget = true; } //the target is not the child of first node
  2212.  
  2213. }
  2214.  
  2215. }
  2216.  
  2217. if (!ch) return; // dTarget must be true OR HTMLElement
  2218.  
  2219. if (dTarget === true) dTarget = kRef(ytdFlexy); // major mutation occurance
  2220. else if (dTarget === kRef(comments_section_loaded_elm) && wAddP > wRemoveP) return true; // ignore if comments are loaded (adding comments)
  2221. else if (isMtoOverallSkip(dTarget)) return; // allow for multiple mutations at the same time - determinated after looping
  2222.  
  2223.  
  2224.  
  2225. // 4 ~ 16 times per full page loading
  2226.  
  2227. Q.addP += wAddP;
  2228. Q.removeP += wRemoveP;
  2229.  
  2230. if (Q.mutationTarget === null) Q.mutationTarget = dTarget;
  2231. else if (Q.mutationTarget != dTarget) Q.mutationTarget = kRef(ytdFlexy);
  2232.  
  2233. //console.log(prettyElm(dTarget), wAddP , wRemoveP, mtoInterval)
  2234. //console.log(prettyElm(dTarget), reg.map(m=>prettyElm(m.target)))
  2235. //console.log(7015, performance.now())
  2236.  
  2237.  
  2238.  
  2239. Q.mtoNav_requestNo++;
  2240. if (Q.mtoNav_requestNo == 1) setTimeout(FP.mtoNav_delayedF, mtoInterval);
  2241.  
  2242. },
  2243.  
  2244.  
  2245. mtoBodyF: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  2246. //subtree DOM mutation checker - {body} \single \subtree
  2247.  
  2248. if (!scriptEnable) return;
  2249. if (deferredVarYTDHidden) return;
  2250.  
  2251. for (const mutation of mutations) {
  2252. for (const addedNode of mutation.addedNodes)
  2253. if (addedNode.nodeType === 1) {
  2254. if (addedNode.nodeName == "DIV" && addedNode.matches('.autocomplete-suggestion:not([autocomplete-disable-updatesc])') ) {
  2255. mtf_fixAutoCompletePosition(addedNode)
  2256. }else if(addedNode.nodeName == "DIV" && (addedNode.id==='lyricscontainer' || addedNode.id==='showlyricsbutton')){
  2257.  
  2258. goYoutubeGeniusLyrics();
  2259.  
  2260. }
  2261. }
  2262. }
  2263.  
  2264. },
  2265.  
  2266. mtf_attrPlaylist: (attrName, newValue) => {
  2267. //attr mutation checker - {ytd-playlist-panel-renderer#playlist} \single
  2268. //::attr ~ hidden
  2269. //console.log(1210)
  2270.  
  2271. if (!scriptEnable) return;
  2272. if (deferredVarYTDHidden) return;
  2273. let cssElm = kRef(ytdFlexy);
  2274. if (!cssElm) return;
  2275.  
  2276. let playlist = document.querySelector('ytd-playlist-panel-renderer#playlist')
  2277. const tabBtn = document.querySelector('[userscript-tab-content="#tab-list"]');
  2278. let isPlaylistHidden = playlist.hasAttribute('hidden')
  2279. //console.log(1212.2, isPlaylistHidden, playlist.getAttribute('hidden'))
  2280. if (tabBtn) {
  2281. //console.log('attr playlist changed')
  2282. if (tabBtn.classList.contains('tab-btn-hidden') && !isPlaylistHidden) {
  2283. //console.log('attr playlist changed - no hide')
  2284. tabBtn.classList.remove("tab-btn-hidden");
  2285. } else if (!tabBtn.classList.contains('tab-btn-hidden') && isPlaylistHidden) {
  2286. //console.log('attr playlist changed - add hide')
  2287. hideTabBtn(tabBtn);
  2288. }
  2289. }
  2290. /* visible layout for triggering hidden removal */
  2291. akAttr(cssElm, 'tabview-youtube-playlist', isPlaylistHidden);
  2292. },
  2293. mtf_attrComments: (attrName, newValue) => {
  2294. //attr mutation checker - {ytd-comments#comments} \single
  2295. //::attr ~ hidden
  2296.  
  2297. let ytdFlexyElm = kRef(ytdFlexy);
  2298. if (!scriptEnable || !ytdFlexyElm) return;
  2299. if (deferredVarYTDHidden) return;
  2300.  
  2301. let comments = document.querySelector('ytd-comments#comments')
  2302. const tabBtn = document.querySelector('[userscript-tab-content="#tab-comments"]');
  2303. if (!comments || !tabBtn) return;
  2304. let isCommentHidden = comments.hasAttribute('hidden')
  2305. //console.log('attr comments changed')
  2306.  
  2307. mtoInterval = mtoInterval1;
  2308. mtc_store=Date.now()+2870
  2309.  
  2310. if( mtf_forceCheckLiveVideo_disable === 2 ){
  2311.  
  2312. }else if (!isCommentHidden) {
  2313.  
  2314. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'K');
  2315.  
  2316.  
  2317.  
  2318. //console.log('attr comments changed - no hide')
  2319. tabBtn.classList.remove("tab-btn-hidden") //if contains
  2320.  
  2321. //console.log(703)
  2322.  
  2323. mtc_cid&&timeline.clearInterval(mtc_cid);
  2324.  
  2325. } else if (isCommentHidden) {
  2326.  
  2327. akAttr(ytdFlexyElm, 'tabview-youtube-comments', true, 'K');
  2328. timeline.setTimeout(function(){
  2329. if(!deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0 && comments.hasAttribute('hidden')){
  2330. //console.log(3434)
  2331. scheduledCommentRefresh=false; //logic tbc
  2332. resetCommentSection();
  2333. //console.log(8022)
  2334. }
  2335. },142)
  2336.  
  2337. if(!mtc_cid) mtc_cid=timeline.setInterval(()=>{
  2338. if(mtc_store>Date.now()) return;
  2339. timeline.clearInterval(mtc_cid)
  2340. mtc_cid=0;
  2341. if(mtf_forceCheckLiveVideo_disable===2)return;
  2342. if(isNullComments()) _disableComments();
  2343.  
  2344. },80)
  2345.  
  2346. }
  2347.  
  2348.  
  2349. },
  2350.  
  2351.  
  2352. mtf_attrChatroom: (attrName, newValue) => {
  2353. //attr mutation checker - {ytd-live-chat-frame#chat} \single
  2354. //::attr ~ collapsed
  2355.  
  2356. let ytdFlexyElm = kRef(ytdFlexy);
  2357. if (!scriptEnable || !ytdFlexyElm) return;
  2358. if (deferredVarYTDHidden) return;
  2359.  
  2360. layoutStatusMutex.lockWith(unlock => {
  2361.  
  2362. const chatBlock = document.querySelector('ytd-live-chat-frame#chat')
  2363. const cssElm = kRef(ytdFlexy)
  2364.  
  2365. if (!chatBlock || !cssElm) {
  2366. unlock();
  2367. return;
  2368. }
  2369.  
  2370. if (deferredVarYTDHidden) {
  2371. unlock();
  2372. return;
  2373. }
  2374.  
  2375. if (!cssElm.hasAttribute('userscript-chatblock')) wAttr(cssElm, 'userscript-chatblock', true);
  2376. let isCollapsed = !!chatBlock.hasAttribute('collapsed');
  2377. wAttr(cssElm, 'userscript-chat-collapsed', isCollapsed);
  2378.  
  2379. if (cssElm.hasAttribute('userscript-chatblock') && !isCollapsed) lastShowTab = '#chatroom';
  2380.  
  2381. if (!isCollapsed && document.querySelector('#right-tabs .tab-btn.active') && isWideScreenWithTwoColumns() && !isTheater()) {
  2382. switchTabActivity(null);
  2383. timeline.setTimeout(unlock, 40);
  2384. } else {
  2385. unlock();
  2386. }
  2387.  
  2388. if (!isCollapsed) {
  2389. runAfterExpandChat();
  2390. } else {
  2391. chatBlock.removeAttribute('yt-userscript-iframe-loaded');
  2392. }
  2393.  
  2394. })
  2395.  
  2396.  
  2397.  
  2398.  
  2399. },
  2400.  
  2401. mtf_attrEngagementPanel: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  2402. //attr mutation checker - {ytd-engagement-panel-section-list-renderer} \mutiple
  2403. //::attr ~ visibility
  2404.  
  2405. let ytdFlexyElm = kRef(ytdFlexy);
  2406. if (!scriptEnable || !ytdFlexyElm) return;
  2407.  
  2408. //multiple instance
  2409. if (mutations) {
  2410. for (const mutation of mutations) {
  2411. let ePanel = mutation.target;
  2412. if (ePanel.getAttribute('visibility') == 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED') {
  2413. setOnlyOneEPanel(ePanel);
  2414. break;
  2415. }
  2416. }
  2417. }
  2418. if (deferredVarYTDHidden) return;
  2419.  
  2420. layoutStatusMutex.lockWith(unlock => {
  2421.  
  2422. const ePanel = document.querySelector('ytd-watch-flexy ytd-engagement-panel-section-list-renderer')
  2423. const cssElm = kRef(ytdFlexy)
  2424.  
  2425. if (!ePanel || !cssElm) {
  2426. unlock();
  2427. return;
  2428. }
  2429. let previousValue = +cssElm.getAttribute('userscript-engagement-panel') || 0;
  2430.  
  2431. let { shownRes, value, count } = engagement_panels_();
  2432. let nextValue = value;
  2433. let nextCount = count;
  2434.  
  2435.  
  2436. if (nextCount == 0 && cssElm.hasAttribute('userscript-engagement-panel')) {
  2437. storeLastPanel=null;
  2438. wAttr(cssElm, 'userscript-engagement-panel', false);
  2439. unlock();
  2440. } else {
  2441.  
  2442. if ((nextCount > 1) || (cssElm.hasAttribute('userscript-engagement-panel') && previousValue === nextValue)) {
  2443. unlock();
  2444. return;
  2445. }
  2446.  
  2447. cssElm.setAttribute('userscript-engagement-panel', nextValue);
  2448.  
  2449. let b = false;
  2450. if (previousValue != nextValue && nextValue > 0) {
  2451. lastShowTab = `#engagement-panel-${nextValue}`;
  2452. b = true;
  2453. storeLastPanel = mWeakRef( shownRes[0])
  2454. //console.log(9999, shownRes[0])
  2455. }
  2456.  
  2457. if (b && document.querySelector('#right-tabs .tab-btn.active') && isWideScreenWithTwoColumns() && !isTheater()) {
  2458. switchTabActivity(null);
  2459. timeline.setTimeout(unlock, 40);
  2460. } else {
  2461. unlock();
  2462. }
  2463. }
  2464.  
  2465. })
  2466.  
  2467.  
  2468.  
  2469.  
  2470. },
  2471.  
  2472. mtf_initalAttr_playlist: () => {
  2473. },
  2474.  
  2475. mtf_initalAttr_comments: () => {
  2476. },
  2477.  
  2478. mtf_initalAttr_chatroom: () => {
  2479. // every per [new] {ytd-live-chat-frame#chat} detection - reset after mini-playview
  2480. let ytdFlexyElm = kRef(ytdFlexy);
  2481. if (!scriptEnable || !ytdFlexyElm) return true;
  2482.  
  2483. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2484.  
  2485.  
  2486. if (!mgChatFrame.inPage()) {
  2487.  
  2488. mtoVisibility_Chatroom.clear(true);
  2489.  
  2490. let chatroom = querySelectorFromAnchor.call(rootElement,`ytd-live-chat-frame#chat:not([${sa_chatroom}]`)
  2491. if (chatroom) {
  2492. mgChatFrame.setVar(chatroom);
  2493.  
  2494. if(mtoVisibility_Chatroom.bindElement(chatroom)){
  2495. mtoVisibility_Chatroom.observer.check(9)
  2496. }
  2497.  
  2498. chatroom = null
  2499. }
  2500. }
  2501. return true;
  2502.  
  2503. },
  2504.  
  2505. mtf_initalAttr_engagement_panel: () => {
  2506. // every per $$non-checked-section-list$$ {ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([o3r-XXXXX])} detection
  2507. let ytdFlexyElm = kRef(ytdFlexy);
  2508. if (!scriptEnable || !ytdFlexyElm) return true;
  2509.  
  2510. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2511.  
  2512. let toCheck = false;
  2513. for (const engagement_panel of querySelectorAllFromAnchor.call(rootElement,
  2514. `ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([o3r-${sa_epanel}])`
  2515. )) {
  2516.  
  2517.  
  2518.  
  2519. let bindRes = mtoVisibility_EngagementPanel.bindElement(engagement_panel, {
  2520. attributes: true,
  2521. attributeFilter: ['visibility'],
  2522. attributeOldValue: true
  2523. })
  2524.  
  2525. if(bindRes) toCheck = true;
  2526. }
  2527.  
  2528. if (toCheck) FP.mtf_attrEngagementPanel()
  2529.  
  2530. return true;
  2531. },
  2532.  
  2533.  
  2534.  
  2535. //live-chat / chat-replay
  2536.  
  2537. fireOnce_forceCheckLiveVideo_tf: () => {
  2538. // once per $$player-playback-timestamp$$ {#ytd-player .ytp-time-display} && $$chat-frame$$ {ytd-live-chat-frame#chat} detection
  2539.  
  2540. let ytdFlexyElm = kRef(ytdFlexy);
  2541. if (!scriptEnable || !ytdFlexyElm) return;
  2542.  
  2543. let elm = document.querySelector('#ytd-player .ytp-time-display');
  2544. if (elm && elm.classList.contains('ytp-live')) {
  2545. //console.log(7006)
  2546. ytdFlexyElm.setAttribute('userscript-chatblock', 'chat-live')
  2547. //console.log(2441)
  2548. mtf_forceCheckLiveVideo_disable = 2;
  2549. _disableComments();
  2550. //console.log(701)
  2551. //disableComments_LiveChat();
  2552. }
  2553. },
  2554.  
  2555.  
  2556. //comments
  2557. /*
  2558. mtf_advancedComments: () => {
  2559. // once per {ytd-comments#comments #continuations} detection
  2560.  
  2561. //let ytdFlexyElm = kRef(ytdFlexy);
  2562. //if (!scriptEnable || !ytdFlexyElm) return true;
  2563.  
  2564. //const rootElement = Q.mutationTarget || ytdFlexyElm;
  2565. //const continuations = document.querySelector("ytd-comments#comments #continuations");
  2566. //if (!continuations) return true;
  2567. //requestingComments = document.querySelector('ytd-comments#comments');
  2568. //scrollForComments();
  2569. return false;
  2570. }
  2571. */
  2572.  
  2573.  
  2574. }
  2575.  
  2576.  
  2577.  
  2578.  
  2579.  
  2580. /** @type {WeakRef | null} */
  2581. let displayedPlaylist = null;
  2582. /** @type {WeakRef | null} */
  2583. let scrollingVideosList = null;
  2584.  
  2585. let scriptEnable = false;
  2586. let scriptEC = 0;
  2587. let lastShowTab = null;
  2588.  
  2589. let _cachedLastVideo = null;
  2590. let videoListBeforeSearch = null;
  2591. let no_fix_contents_until = 0;
  2592. let no_fix_playlist_until = 0;
  2593. let statusCollasped = 0;
  2594.  
  2595. /** @type {WeakRef | null} */
  2596. let ytdFlexy = null;
  2597.  
  2598. function pluginUnhook() {
  2599. _pluginUnhook();
  2600. resetCommentSection();
  2601. }
  2602.  
  2603. function _pluginUnhook() {
  2604.  
  2605. sect_lastUpdate = 0;
  2606. sect_holder = null;
  2607. sect_hTime = 0;
  2608.  
  2609. //console.log(8001)
  2610.  
  2611. videoListBeforeSearch = null;
  2612. statusCollasped = 0;
  2613. _cachedLastVideo = null;
  2614. lastShowTab = null;
  2615. displayedPlaylist = null;
  2616. scrollingVideosList = null;
  2617. scriptEnable = false;
  2618. scriptEC++;
  2619. if (scriptEC > 788888888) scriptEC = 188888888;
  2620. ytdFlexy = null;
  2621. wls.layoutStatus = null;
  2622.  
  2623. //console.log('unc01')
  2624.  
  2625. mtoVisibility_EngagementPanel.clear(true)
  2626. mtoVisibility_Playlist.clear(true)
  2627. mtoVisibility_Comments.clear(true)
  2628.  
  2629. mgChatFrame.kVar = null;
  2630. mtoVisibility_Chatroom.clear(true)
  2631. mtoFlexyAttr.clear(true)
  2632.  
  2633.  
  2634. for (const elem of document.querySelectorAll(
  2635. ['ytd-expander[tabview-info-expander]'].join(', ')
  2636. )) {
  2637. elem.removeAttribute('tabview-info-expander');
  2638. }
  2639.  
  2640. mtoMutation_body.clear(true)
  2641. mtoMutation_watchFlexy.clear(true)
  2642. //FOnce.mtf_checkFlexy = null;
  2643. //FOnce.mtf_initalAttr_comments = null;
  2644. //FOnce.mtf_initalAttr_playlist = null;
  2645. //FOnce.mtf_initalAttr_chatroom = null;
  2646. //FOnce.mtf_initalAttr_engagement_panel = null;
  2647. //FOnce.mtf_advancedComments = null;
  2648. //FOnce.mtf_checkDescriptionLoaded = null;
  2649. //FOnce.mtf_forceCheckLiveVideo = null;
  2650. Q.mtf_chatBlockQ = null;
  2651.  
  2652.  
  2653. mtoInterval = mtoInterval1;
  2654.  
  2655. }
  2656.  
  2657. let comments_section_loaded_elm = null;
  2658.  
  2659.  
  2660.  
  2661. function getTabsHTML() {
  2662.  
  2663. const sTabBtnVideos = `${svgElm(16,16,298,298,svgVideos)}<span>Videos</span>`
  2664. const sTabBtnInfo = `${svgElm(16,16,23.625,23.625,svgInfo)}<span>Info</span>`
  2665. const sTabBtnPlayList = `${svgElm(16,16,426.667,426.667,svgPlayList)}<span>Playlist</span>`
  2666.  
  2667. let str1 = `
  2668. <paper-ripple class="style-scope yt-icon-button">
  2669. <div id="background" class="style-scope paper-ripple" style="opacity:0;"></div>
  2670. <div id="waves" class="style-scope paper-ripple"></div>
  2671. </paper-ripple>
  2672. `;
  2673.  
  2674. let str_fbtns = `
  2675. <div class="font-size-right">
  2676. <div class="font-size-btn font-size-plus">
  2677. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  2678. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  2679. <path d="M12 25h26"/><path d="M25 12v26"/>
  2680. </svg>
  2681. </div><div class="font-size-btn font-size-minus">
  2682. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  2683. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  2684. <path d="M12 25h26"/>
  2685. </svg>
  2686. </div>
  2687. </div>
  2688. `.replace(/[\r\n]+/g,'')
  2689.  
  2690. const str_tabs = [
  2691. `<a id="tab-btn1" data-name="info" userscript-tab-content="#tab-info" class="tab-btn">${sTabBtnInfo}${str1}${str_fbtns}</a>`,
  2692. `<a id="tab-btn3" userscript-tab-content="#tab-comments" data-name="comments" class="tab-btn">${svgElm(16,16,60,60,svgComments)}<span id="tab3-txt-loader"></span>${str1}${str_fbtns}</a>`,
  2693. `<a id="tab-btn4" userscript-tab-content="#tab-videos" data-name="videos" class="tab-btn">${sTabBtnVideos}${str1}${str_fbtns}</a>`,
  2694. `<a id="tab-btn5" userscript-tab-content="#tab-list" class="tab-btn">${sTabBtnPlayList}${str1}${str_fbtns}</a>`
  2695. ].join('')
  2696.  
  2697. let addHTML = `
  2698. <div id="right-tabs">
  2699. <header>
  2700. <div id="material-tabs">
  2701. ${str_tabs}
  2702. </div>
  2703. </header>
  2704. <div class="tab-content">
  2705. <div id="tab-info" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2706. <div id="tab-comments" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2707. <div id="tab-videos" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2708. <div id="tab-list" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2709. </div>
  2710. </div>
  2711. `;
  2712.  
  2713. return addHTML
  2714.  
  2715. }
  2716.  
  2717.  
  2718. function onVideoChange() {
  2719. // for popstate & next video
  2720.  
  2721. newVideoPageCheck();
  2722.  
  2723. scheduledCommentRefresh=true;
  2724. let comments = document.querySelector('ytd-comments#comments')
  2725. if(!deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0 && comments.hasAttribute('hidden')){
  2726.  
  2727. scheduledCommentRefresh=false;
  2728. // comment tab btn - hide by timer in attribute change
  2729. resetCommentSection();
  2730. }
  2731.  
  2732. mtf_forceCheckLiveVideo_disable = 0
  2733. mtc_store= Date.now()+3870
  2734.  
  2735. if (deferredVarYTDHidden) { // reset info when hidden
  2736. resetCommentSection();
  2737. }else{
  2738. checkVisibleEngagementPanel();
  2739. atChange(); // in case no mutation occurance
  2740. }
  2741.  
  2742.  
  2743.  
  2744. }
  2745.  
  2746. function onNavigationEnd(evt) {
  2747. console.log('yt-navigate-finish')
  2748. document.documentElement.setAttribute('youtube-ready','')
  2749. script_inject_js1.inject();
  2750. document.documentElement.dispatchEvent(new CustomEvent('tabview-ce-hack'))
  2751.  
  2752. forceConfig();
  2753. /*
  2754. console.log(window.ytcfg)
  2755. try{
  2756. window.ytcfg.set({
  2757. "EXPERIMENT_FLAGS": {"kevlar_watch_metadata_refresh":false}})
  2758. }catch(e){}
  2759. */
  2760.  
  2761. newVideoPageCheck(); // required for init
  2762.  
  2763. let mRet =
  2764. (/^https?\:\/\/(\w+\.)*youtube\.com\/watch\?(\w+\=[^\/\?\&]+\&|\w+\=?\&)*v=[\w\-\_]+/.test(window.location.href) ? 1 : 0) +
  2765. (document.querySelector('ytd-watch-flexy[tabview-selection]') ? 2 : 0);
  2766.  
  2767. if (mRet === 1) {
  2768.  
  2769. document.addEventListener('loadedmetadata', function(evt) {
  2770. if (evt.target.matches('video[tabview-mainvideo]')) {
  2771. setTimeout(onVideoChange, 30)
  2772. }
  2773. }, true)
  2774.  
  2775. pluginUnhook(); // in case not triggered by popstate - say mini playing
  2776.  
  2777. let timeout = 4; // max. 4 animation frames
  2778.  
  2779. let tf = () => {
  2780.  
  2781. if (--timeout > 0 && !document.querySelector('#player video')) return requestAnimationFrame(tf);
  2782.  
  2783. let ytdFlexyElm = document.querySelector('ytd-watch-flexy')
  2784.  
  2785. if(!ytdFlexyElm) return;
  2786.  
  2787.  
  2788. scriptEnable = true;
  2789. scriptEC++;
  2790.  
  2791. no_fix_contents_until = 0;
  2792. no_fix_playlist_until = 0;
  2793.  
  2794. ytdFlexy = mWeakRef(ytdFlexyElm)
  2795.  
  2796. let timeoutR_findRelated = new Timeout();
  2797. timeoutR_findRelated.set(function() {
  2798. let ytdFlexyElm = kRef(ytdFlexy);
  2799. if(!ytdFlexyElm) return true;
  2800. let related = querySelectorFromAnchor.call(ytdFlexyElm,"#related");
  2801. if (!related) return true;
  2802. foundRelated(related);
  2803. }, 100, 10)
  2804.  
  2805. function foundRelated(related) {
  2806. let promise = Promise.resolve();
  2807. if (!document.querySelector("#right-tabs")) {
  2808. promise = promise.then(() => {
  2809. $(getTabsHTML()).insertBefore(related).attr('data-dom-created-by-tabview-youtube', scriptVersionForExternal);
  2810. })
  2811. }
  2812. promise.then(runAfterTabAppended)
  2813. }
  2814.  
  2815. /*
  2816. setTimeout(() => {
  2817. for (const s of document.querySelectorAll('#right-tabs [userscript-scrollbar-render]')) {
  2818. Promise.resolve(s).then(s => {
  2819. if (s && s.scrollTop > 0) s.scrollTop = 0;
  2820. let child = s.firstElementChild;
  2821. if (child && child.scrollTop > 0) child.scrollTop = 0;
  2822. });
  2823. }
  2824. }, 90)
  2825. */
  2826.  
  2827.  
  2828. }
  2829.  
  2830. tf();
  2831.  
  2832. } else if (mRet === 3) {
  2833.  
  2834. if(!scriptEnable) return;
  2835.  
  2836. let elmComments = document.querySelector('ytd-comments#comments')
  2837.  
  2838. if (elmComments) {
  2839. nativeFunc(elmComments, "loadComments")
  2840. }
  2841.  
  2842. } else if (mRet === 0) {
  2843.  
  2844. pluginUnhook(); // in case not triggered by popstate - say mini playing
  2845.  
  2846. }
  2847.  
  2848. if(mRet & 1){
  2849. setTimeout(()=>{
  2850. Q.mutationTarget=null;
  2851. atChange(); // in case no mutation occurance
  2852. FP.mtf_attrComments()
  2853. },160);
  2854. }
  2855.  
  2856. }
  2857.  
  2858.  
  2859. function setToActiveTab(defaultTab) {
  2860. if (isTheater() && isWideScreenWithTwoColumns()) return;
  2861. const jElm = document.querySelector(`a[userscript-tab-content="${switchTabActivity_lastTab}"]:not(.tab-btn-hidden)`) ||
  2862. document.querySelector(`a[userscript-tab-content="${(defaultTab||settings.defaultTab)}"]:not(.tab-btn-hidden)`) ||
  2863. document.querySelector("a[userscript-tab-content]:not(.tab-btn-hidden)") ||
  2864. null;
  2865. switchTabActivity(jElm);
  2866. return !!jElm;
  2867. }
  2868.  
  2869. function getWrapper(wrapperId) {
  2870. let $wrapper = $(`#${wrapperId}`);
  2871. if (!$wrapper[0]) $wrapper = $(`<div id="${wrapperId}"></div>`)
  2872. return $wrapper.first();
  2873. }
  2874.  
  2875. function runAfterTabAppended() {
  2876.  
  2877. document.documentElement.setAttribute('plugin-tabview-youtube', '')
  2878.  
  2879. const ytdFlexyElm = kRef(ytdFlexy)
  2880. if(!ytdFlexyElm) return;
  2881. if (!ytdFlexyElm.hasAttribute('tabview-selection')) ytdFlexyElm.setAttribute('tabview-selection', '')
  2882.  
  2883.  
  2884. //console.log('unc02')
  2885.  
  2886. // append the next videos
  2887. // it exists as "related" is already here
  2888. fixTabs();
  2889.  
  2890. // just switch to the default tab
  2891. setToActiveTab();
  2892.  
  2893.  
  2894. prepareTabBtn();
  2895.  
  2896.  
  2897. // append the detailed meta contents to the tab-info
  2898. // ** FOnce.mtf_checkDescriptionLoaded = FP.mtf_checkDescriptionLoaded;
  2899. // ** if (Q.mutationTarget === null) $callOnceAsync('mtf_checkDescriptionLoaded');
  2900.  
  2901. // force window scroll when #continuations is first detected and #comments still [hidden]
  2902. //FOnce.mtf_advancedComments = FP.mtf_advancedComments;
  2903. //if (Q.mutationTarget === null) $callOnceAsync('mtf_advancedComments');
  2904.  
  2905. // use video player's element to detect the live-chat situation (no commenting section)
  2906. // this would be very useful if the live chat is collapsed, i.e. iframe has no indication on the where it is live or replay
  2907. //FOnce.mtf_forceCheckLiveVideo = FP.mtf_forceCheckLiveVideo;
  2908. //if (Q.mutationTarget === null) $callOnceAsync('mtf_forceCheckLiveVideo');
  2909. //mtf_forceCheckLiveVideo();
  2910.  
  2911.  
  2912. // Attr Mutation Observer - #playlist - hidden
  2913. //clearMutationObserver(mtoVs, 'mtoVisibility_Playlist')
  2914. // Attr Mutation Observer callback - #playlist - hidden
  2915.  
  2916. // pending for #playlist and set Attribute Observer
  2917. // ** FOnce.mtf_initalAttr_playlist = FP.mtf_initalAttr_playlist
  2918. // ** if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_playlist');
  2919.  
  2920. // Attr Mutation Observer - ytd-comments#comments - hidden
  2921. //clearMutationObserver(mtoVs, 'mtoVisibility_Comments')
  2922. // Attr Mutation Observer callback - ytd-comments#comments - hidden
  2923.  
  2924. // pending for #comments and set Attribute Observer
  2925. // ** FOnce.mtf_initalAttr_comments = FP.mtf_initalAttr_comments;
  2926. // ** if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_comments');
  2927.  
  2928.  
  2929. //clearMutationObserver(mtoVs, 'mtoVisibility_Chatroom');
  2930. //FOnce.mtf_initalAttr_chatroom = FP.mtf_initalAttr_chatroom
  2931. //if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_chatroom');
  2932.  
  2933. // clearMutationObserver(mtoVs, 'mtoVisibility_EngagementPanel');
  2934. // for (const engagement_panel of document.querySelectorAll('ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([tabview-attr-checked])')) {
  2935. // engagement_panel.removeAttribute('tabview-attr-checked');
  2936. // }
  2937. //FOnce.mtf_initalAttr_engagement_panel = FP.mtf_initalAttr_engagement_panel
  2938. //if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_engagement_panel');
  2939.  
  2940.  
  2941. mtoFlexyAttr.clear(true)
  2942. mtf_checkFlexy()
  2943.  
  2944.  
  2945. document.querySelector("#right-tabs .tab-content").addEventListener('scroll', makeBodyScrollByEvt, true);
  2946.  
  2947.  
  2948. Q.addP = 0;
  2949. Q.removeP = 0;
  2950. Q.mutationTarget = null;
  2951.  
  2952. Q.mtoNav_requestNo = 0;
  2953.  
  2954.  
  2955. mtoMutation_watchFlexy.bindElement(ytdFlexyElm, {
  2956. childList: true,
  2957. subtree: true,
  2958. attributes: false
  2959. })
  2960.  
  2961. // for automcomplete plugin or other userscript plugins
  2962. // document.body for Firefox >= 60
  2963. mtoMutation_body.bindElement(document.querySelector('body'), {
  2964. childList: true,
  2965. subtree: false,
  2966. attributes: false
  2967. })
  2968.  
  2969.  
  2970. regularCheck(1, 0, null);
  2971.  
  2972.  
  2973.  
  2974.  
  2975. }
  2976.  
  2977.  
  2978. function fetchCommentsFinished() {
  2979. let ytdFlexyElm = kRef(ytdFlexy);
  2980. if (!scriptEnable || !ytdFlexyElm) return;
  2981. if(mtf_forceCheckLiveVideo_disable===2) return;
  2982. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'LS')
  2983. }
  2984.  
  2985. function setCommentSection( /** @type {number} */ value) {
  2986.  
  2987. Q.comments_section_loaded = value;
  2988.  
  2989. if (value === 0) {
  2990. sect_lastUpdate = 0;
  2991. comments_section_loaded_elm = null;
  2992. }
  2993.  
  2994. }
  2995.  
  2996. function resetCommentSection(){
  2997.  
  2998. let tab_btn = document.querySelector('.tab-btn[userscript-tab-content="#tab-comments"]')
  2999.  
  3000.  
  3001. if(tab_btn){
  3002.  
  3003. let span = querySelectorFromAnchor.call(tab_btn,'span#tab3-txt-loader');
  3004.  
  3005. tab_btn.removeAttribute('loaded-comment')
  3006. tab_btn.classList.remove('tab-btn-hidden')
  3007. if(span){
  3008. span.textContent='';
  3009. }
  3010. }
  3011.  
  3012.  
  3013. setCommentSection(0);
  3014.  
  3015.  
  3016. }
  3017.  
  3018. function _disableComments() {
  3019. //requestingComments = null;
  3020. mtc_cid && timeline.clearInterval(mtc_cid)
  3021. mtc_cid=0;
  3022.  
  3023. if (!scriptEnable) return;
  3024. let cssElm = kRef(ytdFlexy);
  3025. if (!cssElm) return;
  3026.  
  3027. mtoInterval = mtoInterval2;
  3028.  
  3029. if(Q.comments_section_loaded>0) return; //already displayed / disabled
  3030.  
  3031. scheduledCommentRefresh=false;
  3032. setCommentSection(2);
  3033.  
  3034. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents') || null)
  3035.  
  3036. let tabBtn = document.querySelector('.tab-btn[userscript-tab-content="#tab-comments"]');
  3037. if(tabBtn) {
  3038. tabBtn.removeAttribute('loaded-comment')
  3039. if (!tabBtn.classList.contains('tab-btn-hidden')) {
  3040. hideTabBtn(tabBtn)
  3041. }
  3042. }
  3043.  
  3044. akAttr(cssElm, 'tabview-youtube-comments', true, 'D');
  3045.  
  3046.  
  3047. }
  3048.  
  3049.  
  3050.  
  3051.  
  3052. let layoutStatusMutex = new Mutex();
  3053.  
  3054. function forceDisplayChatReplay() {
  3055. let items = chatFrameElement('yt-live-chat-item-list-renderer #items');
  3056. if (items && items.childElementCount !== 0) return;
  3057.  
  3058. let ytd_player = document.querySelector('ytd-player#ytd-player');
  3059. if (!ytd_player) return;
  3060. let videoElm = querySelectorFromAnchor.call(ytd_player,'video');
  3061. if (!videoElm) return;
  3062.  
  3063. let video = videoElm;
  3064. if (videoElm && video.currentTime > 0 && !video.ended && video.readyState > video.HAVE_CURRENT_DATA) {
  3065. let chat = document.querySelector('ytd-live-chat-frame#chat');
  3066. if (chat) {
  3067. nativeFunc(chat, "postToContentWindow", [{ "yt-player-video-progress": videoElm.currentTime }])
  3068. }
  3069. }
  3070.  
  3071. }
  3072.  
  3073.  
  3074.  
  3075. function runAfterExpandChat() {
  3076.  
  3077.  
  3078. if(runAfterExpandChat.cid_chatFrameCheck1) timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3079. if(runAfterExpandChat.cid_chatFrameCheck2) timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3080. runAfterExpandChat.cid_chatFrameCheck1=0;
  3081. runAfterExpandChat.cid_chatFrameCheck2=0;
  3082.  
  3083. new Promise(resolve => {
  3084.  
  3085. let chatFrame_st = Date.now();
  3086. runAfterExpandChat.cid_chatFrameCheck1 = 0;
  3087.  
  3088. let sEF = new ScriptEF();
  3089. runAfterExpandChat.cid_chatFrameCheck1 = timeline.setInterval(() => {
  3090. if (!sEF.isValid()) return runAfterExpandChat.cid_chatFrameCheck1 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3091. let cDoc = chatFrameContentDocument();
  3092. if (cDoc) {
  3093. runAfterExpandChat.cid_chatFrameCheck1 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3094. resolve();
  3095. } else if (!scriptEnable || !isChatExpand() || Date.now() - chatFrame_st > 6750) {
  3096. runAfterExpandChat.cid_chatFrameCheck1 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3097. }
  3098. }, 60);
  3099.  
  3100.  
  3101. }).then(() => new Promise(resolve => {
  3102.  
  3103.  
  3104. let chatFrame_st = Date.now();
  3105. runAfterExpandChat.cid_chatFrameCheck2 = 0;
  3106.  
  3107. let sEF = new ScriptEF();
  3108. runAfterExpandChat.cid_chatFrameCheck2 = timeline.setInterval(() => {
  3109. if (!sEF.isValid()) return runAfterExpandChat.cid_chatFrameCheck2 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3110. let app = chatFrameElement('yt-live-chat-app');
  3111. if (app) {
  3112. runAfterExpandChat.cid_chatFrameCheck2 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3113. resolve(app);
  3114. } else if (!scriptEnable || !isChatExpand() || Date.now() - chatFrame_st > 6750*3) {
  3115. runAfterExpandChat.cid_chatFrameCheck2 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3116. }
  3117. }, 60);
  3118.  
  3119.  
  3120. })).then(app => {
  3121.  
  3122.  
  3123. let cDoc = app.ownerDocument;
  3124.  
  3125. if (!scriptEnable || !isChatExpand()) return;
  3126. if(cDoc.querySelector('#userscript-tabview-chatroom-css')) return;
  3127. addStyle(`
  3128. body #input-panel.yt-live-chat-renderer::after {
  3129. background: transparent;
  3130. }
  3131. #items.yt-live-chat-item-list-renderer{
  3132. contain: content;
  3133. }
  3134. yt-live-chat-text-message-renderer{
  3135. contain: content;
  3136. }
  3137. #item-offset.yt-live-chat-item-list-renderer{
  3138. contain: content;
  3139. }
  3140. #item-scroller.yt-live-chat-item-list-renderer{
  3141. contain: strict;
  3142. }
  3143. img[width][height]{
  3144. contain: strict;
  3145. }
  3146. #item-list > yt-live-chat-item-list-renderer, #item-list > yt-live-chat-item-list-renderer > #contents{
  3147. contain: strict;
  3148. }
  3149.  
  3150.  
  3151. #chat.style-scope.yt-live-chat-renderer,
  3152. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer,
  3153. #item-scroller,
  3154. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer .style-scope.yt-live-chat-text-message-renderer,
  3155. yt-live-chat-ticker-paid-message-item-renderer
  3156. {
  3157. contain: layout paint style;
  3158. }
  3159. yt-img-shadow#author-photo.style-scope{
  3160. contain: layout paint style;
  3161. content-visibility: auto;
  3162. contain-intrinsic-size: 24px 24px;
  3163. }
  3164. #item-offset.style-scope.yt-live-chat-item-list-renderer,
  3165. #items.style-scope.yt-live-chat-item-list-renderer {
  3166. contain: layout paint;
  3167. }
  3168. .style-scope.yt-live-chat-text-message-renderer {
  3169. cursor: default;
  3170. }
  3171. #author-photo.style-scope.yt-live-chat-text-message-renderer,
  3172. yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer,
  3173. yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer ~ span#message.style-scope.yt-live-chat-text-message-renderer
  3174. {
  3175. pointer-events: none;
  3176. }
  3177. span#message.style-scope.yt-live-chat-text-message-renderer > img.emoji.yt-formatted-string.style-scope.yt-live-chat-text-message-renderer{
  3178. contain: layout paint style;
  3179. cursor: default;
  3180. pointer-events: none;
  3181. }
  3182. body yt-live-chat-app{
  3183. contain: size layout paint style;
  3184. content-visibility: auto;
  3185. transform: translate3d(0,0,0);
  3186. overflow: hidden;
  3187. }
  3188.  
  3189.  
  3190. /*
  3191. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer:nth-last-of-type(n+20){
  3192. content-visibility: auto;
  3193. }
  3194. */
  3195.  
  3196. /*
  3197. @supports (contain-intrinsic-size: auto 1px){
  3198.  
  3199. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer{
  3200. content-visibility: auto;
  3201. contain-intrinsic-size: auto 24px;
  3202. }
  3203.  
  3204. }
  3205. */
  3206. .style-scope.yt-live-chat-item-list-renderer{
  3207. box-sizing: border-box;
  3208. }
  3209.  
  3210. /*
  3211. .style-scope.yt-live-chat-item-list-renderer[style*="--tabview-crm-height"]{
  3212. content-visibility: auto;
  3213. contain-intrinsic-size: 1px var(--tabview-crm-height, 24px);
  3214. }
  3215.  
  3216. #item-offset.style-scope.yt-live-chat-item-list-renderer{
  3217. height: auto !important;
  3218. }
  3219. #item-offset.style-scope.yt-live-chat-item-list-renderer > #items:only-child{
  3220. position: relative !important;
  3221. }*/
  3222.  
  3223. #item-offset.style-scope.yt-live-chat-item-list-renderer{
  3224. contain: size layout paint style;
  3225. }
  3226. #item-offset.style-scope.yt-live-chat-item-list-renderer > #items:only-child{
  3227. contain: layout paint style;
  3228. }
  3229.  
  3230. `, cDoc.documentElement).id='userscript-tabview-chatroom-css'
  3231.  
  3232. let frc= 0;
  3233. let fullReady = ()=>{
  3234.  
  3235.  
  3236. if(!cDoc.documentElement.hasAttribute('style') && ++frc<900) return timeline.setTimeout(fullReady,10);
  3237.  
  3238. if (cDoc.querySelector('yt-live-chat-renderer #continuations')) {
  3239. timeline.setTimeout(() => mtf_ChatExist(), 40);
  3240. $(document.querySelector('ytd-live-chat-frame#chat')).attr('yt-userscript-iframe-loaded', '')
  3241. }
  3242.  
  3243. forceDisplayChatReplay();
  3244.  
  3245. let iframe = document.querySelector('ytd-live-chat-frame iframe#chatframe');
  3246.  
  3247.  
  3248. iframe.dispatchEvent(new CustomEvent("tabview-chatroom-ready"))
  3249.  
  3250.  
  3251.  
  3252. }
  3253. fullReady();
  3254.  
  3255.  
  3256.  
  3257. })
  3258.  
  3259. }
  3260.  
  3261. function flexyAttr_toggleFlag(mFlag, b, flag) {
  3262. if (b) mFlag = mFlag | flag;
  3263. else mFlag = mFlag & ~flag;
  3264. return mFlag;
  3265. }
  3266.  
  3267. function flexAttr_toLayoutStatus(nls, attributeName) {
  3268.  
  3269. let attrElm, b, v;
  3270. switch (attributeName) {
  3271. case 'theater':
  3272. nls = flexyAttr_toggleFlag(nls, isTheater(), LAYOUT_THEATER);
  3273. break;
  3274. case 'userscript-chat-collapsed':
  3275. case 'userscript-chatblock':
  3276. attrElm = kRef(ytdFlexy);
  3277. if (hasAttribute(attrElm, 'userscript-chat-collapsed')) {
  3278. nls = flexyAttr_toggleFlag(nls, true, LAYOUT_CHATROOM | LAYOUT_CHATROOM_COLLASPED);
  3279. } else {
  3280. nls = flexyAttr_toggleFlag(nls, hasAttribute(attrElm, 'userscript-chatblock'), LAYOUT_CHATROOM);
  3281. nls = flexyAttr_toggleFlag(nls, false, LAYOUT_CHATROOM_COLLASPED);
  3282. }
  3283. break;
  3284. case 'is-two-columns_':
  3285. nls = flexyAttr_toggleFlag(nls, isWideScreenWithTwoColumns(), LAYOUT_TWO_COLUMNS);
  3286. break;
  3287.  
  3288. case 'tabview-selection':
  3289. b = isNonEmptyString(kRef(ytdFlexy).getAttribute('tabview-selection'));
  3290. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_TAB_EXPANDED);
  3291. break;
  3292.  
  3293. case 'fullscreen':
  3294. b = isNonEmptyString(kRef(ytdFlexy).getAttribute('fullscreen'));
  3295. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_FULLSCREEN);
  3296. break;
  3297.  
  3298. case 'userscript-engagement-panel':
  3299. v = kRef(ytdFlexy).getAttribute('userscript-engagement-panel');
  3300. b = (+v > 0)
  3301. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_ENGAGEMENT_PANEL_EXPAND);
  3302. break;
  3303.  
  3304. }
  3305.  
  3306. return nls;
  3307.  
  3308.  
  3309. }
  3310.  
  3311. let mtf_attrFlexy = (mutations, observer) => {
  3312.  
  3313. //attr mutation checker - $$ytdFlexyElm$$ {ytd-watch-flexy} \single
  3314. //::attr
  3315. // ~ 'userscript-chat-collapsed', 'userscript-chatblock', 'theater', 'is-two-columns_',
  3316. // ~ 'tabview-selection', 'fullscreen', 'userscript-engagement-panel',
  3317. // ~ 'hidden'
  3318.  
  3319. //console.log(15330, scriptEnable, kRef(ytdFlexy), mutations)
  3320.  
  3321. if (!scriptEnable) return;
  3322.  
  3323. const cssElm = kRef(ytdFlexy)
  3324. if (!cssElm) return;
  3325.  
  3326. if (!mutations) return;
  3327.  
  3328. //console.log(15340)
  3329. ytdFlexyHiddenCheck(mutations);
  3330.  
  3331. const old_layoutStatus = wls.layoutStatus
  3332. if (old_layoutStatus === null) return;
  3333. let new_layoutStatus = old_layoutStatus;
  3334.  
  3335. let checkedChat = false;
  3336.  
  3337. for (const mutation of mutations) {
  3338. new_layoutStatus = flexAttr_toLayoutStatus(new_layoutStatus, mutation.attributeName);
  3339. if (mutation.attributeName == 'userscript-chat-collapsed' || mutation.attributeName == 'userscript-chatblock') {
  3340.  
  3341. if(!checkedChat){
  3342. checkedChat = true; // avoid double call
  3343.  
  3344. if (cssElm.getAttribute('userscript-chatblock') === 'chat-live') {
  3345. // assigned new attribute - "chat-live" => disable comments section
  3346. _disableComments();
  3347. }
  3348.  
  3349. if (!cssElm.hasAttribute('userscript-chatblock')) {
  3350. // might or might not collapsed before
  3351. timeline.setTimeout(() => {
  3352. if (!scriptEnable) return;
  3353. //delayed call => check with the "no active focus" condition with chatroom status
  3354. if (!isAnyActiveTab() && !isChatExpand() && !isTheater() && isWideScreenWithTwoColumns() && !isFullScreen()) {
  3355. setToActiveTab();
  3356. }
  3357. }, 240);
  3358. }
  3359. }
  3360.  
  3361. }else if(mutation.attributeName == 'userscript-engagement-panel'){
  3362. // assume any other active component such as tab content and chatroom
  3363. if (+(cssElm.getAttribute('userscript-engagement-panel')||0)===0 && +mutation.oldValue>0) {
  3364. timeline.setTimeout(() => {
  3365. if (!scriptEnable) return;
  3366. //delayed call => check with the "no active focus" condition with engagement panel status
  3367. if (!isAnyActiveTab() && !isEngagementPanelExpanded() && !isTheater() && isWideScreenWithTwoColumns() && !isFullScreen() && !isChatExpand()) {
  3368. setToActiveTab();
  3369. }
  3370. }, 240);
  3371. }
  3372. }
  3373. }
  3374.  
  3375. if (new_layoutStatus !== old_layoutStatus) wls.layoutStatus = new_layoutStatus
  3376.  
  3377. }
  3378.  
  3379. const mtf_checkFlexy = () => {
  3380. // once per $$native-ytd-watch-flexy$$ {ytd-watch-flexy} detection
  3381.  
  3382. let ytdFlexyElm = kRef(ytdFlexy);
  3383. if (!scriptEnable || !ytdFlexyElm) return true;
  3384.  
  3385.  
  3386. wls.layoutStatus = null;
  3387.  
  3388. let isFlexyHidden = (deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden'));
  3389.  
  3390. if (!isFlexyHidden) {
  3391. let rChatExist = base_ChatExist();
  3392. if (rChatExist) {
  3393. let { attr_chatblock, attr_chatcollapsed } = rChatExist;
  3394. if (attr_chatblock === null) {
  3395. //remove attribute if it is unknown
  3396. attr_chatblock = false;
  3397. attr_chatcollapsed = false;
  3398. }
  3399. wAttr(ytdFlexyElm, 'userscript-chatblock', attr_chatblock)
  3400. wAttr(ytdFlexyElm, 'userscript-chat-collapsed', attr_chatcollapsed)
  3401. }
  3402. }
  3403.  
  3404. let rTabSelection = [...querySelectorAllFromAnchor.call(ytdFlexyElm,'.tab-btn[userscript-tab-content]')]
  3405. .map(elm => ({ elm, hidden: elm.classList.contains('tab-btn-hidden') }));
  3406.  
  3407. if(rTabSelection.length === 0){
  3408. wAttr(ytdFlexyElm, 'tabview-selection', false);
  3409. }else{
  3410. rTabSelection=rTabSelection.filter(entry => entry.hidden !== true); // all available tabs
  3411. if (rTabSelection.length === 0) wAttr(ytdFlexyElm, 'tabview-selection', '');
  3412. }
  3413. rTabSelection = null;
  3414. let rEP = engagement_panels_();
  3415. if (rEP && rEP.count > 0) wAttr(ytdFlexyElm, 'userscript-engagement-panel', false);
  3416. //else wAttr(ytdFlexyElm, 'userscript-engagement-panel', rEP.value + ""); // can be 0
  3417. else if(rEP.value>0) wAttr(ytdFlexyElm, 'userscript-engagement-panel', rEP.value + ""); // can be 0
  3418.  
  3419. let ls = 0;
  3420. ls = flexAttr_toLayoutStatus(ls, 'theater')
  3421. ls = flexAttr_toLayoutStatus(ls, 'userscript-chat-collapsed')
  3422. ls = flexAttr_toLayoutStatus(ls, 'userscript-chatblock')
  3423. ls = flexAttr_toLayoutStatus(ls, 'is-two-columns_')
  3424. ls = flexAttr_toLayoutStatus(ls, 'tabview-selection')
  3425. ls = flexAttr_toLayoutStatus(ls, 'fullscreen')
  3426. ls = flexAttr_toLayoutStatus(ls, 'userscript-engagement-panel')
  3427.  
  3428. wls.layoutStatus = ls
  3429.  
  3430. mtoFlexyAttr.bindElement(ytdFlexyElm,{
  3431. attributes: true,
  3432. attributeFilter: ['userscript-chat-collapsed', 'userscript-chatblock', 'theater', 'is-two-columns_', 'tabview-selection', 'fullscreen', 'userscript-engagement-panel', 'hidden'],
  3433. attributeOldValue: true
  3434. })
  3435.  
  3436. ytdFlexyHiddenCheckBasic(ytdFlexyElm);
  3437.  
  3438.  
  3439. let columns = document.querySelector('ytd-page-manager#page-manager #columns')
  3440. if (columns) {
  3441. wAttr(columns, 'userscript-scrollbar-render', true);
  3442. }
  3443.  
  3444. return false;
  3445. }
  3446.  
  3447. function ytdFlexyHiddenCheckBasic(ytdFlexyElm){
  3448. // for both hidden and non-hidden ytd-watch-flexy
  3449.  
  3450. deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden');
  3451.  
  3452. // console.log(15403)
  3453. document.documentElement.classList.toggle('tabview-normal-player',!deferredVarYTDHidden)
  3454.  
  3455. }
  3456.  
  3457. function checkVisibleEngagementPanel(){
  3458. if(storeLastPanel){
  3459.  
  3460. let elm_storeLastPanel = kRef(storeLastPanel);
  3461.  
  3462. if(elm_storeLastPanel && !isDOMVisible(elm_storeLastPanel) ){
  3463. storeLastPanel=null;
  3464. ytBtnCloseEngagementPanels();
  3465. }
  3466.  
  3467. }
  3468.  
  3469. }
  3470.  
  3471. function ytdFlexyHiddenCheck(mutations) {
  3472.  
  3473. //console.log(15350)
  3474.  
  3475. const ytdFlexyElm = kRef(ytdFlexy)
  3476. if (!ytdFlexyElm) return;
  3477. let muHidden = false
  3478.  
  3479. for (const mutation of mutations) {
  3480. if (mutation.attributeName === 'hidden') {
  3481. //console.log(343)
  3482. muHidden = true;
  3483. break;
  3484. }
  3485. }
  3486.  
  3487. if (!muHidden) return;
  3488.  
  3489. mtc_store= Date.now()+2870
  3490. //console.log(7004)
  3491. deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden');
  3492.  
  3493. if(deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0){
  3494. scheduledCommentRefresh=false;
  3495. }
  3496.  
  3497. //console.log(15400)
  3498. if(!deferredVarYTDHidden){
  3499. mtf_forceCheckLiveVideo_disable = 0
  3500. timeline.setTimeout(function() {
  3501. mtf_ChatExist();
  3502. layoutStatusMutex.lockWith(unlock=>{
  3503. atChange(); // in case no mutation occurance
  3504. ytdFlexyHiddenCheckBasic(ytdFlexyElm);
  3505. dispatchWindowResize(); // player control positioning
  3506. timeline.setTimeout(unlock, 40);
  3507. })
  3508. }, 40);
  3509. }else{
  3510. //console.log(15401)
  3511. timeline.setTimeout(function() {
  3512. //console.log(15402)
  3513. ytdFlexyHiddenCheckBasic(ytdFlexyElm);
  3514. }, 40);
  3515. }
  3516.  
  3517. }
  3518.  
  3519.  
  3520.  
  3521.  
  3522. let switchTabActivity_lastTab = null
  3523.  
  3524. function setDisplayedPlaylist() {
  3525. //override the default youtube coding event prevention
  3526. let cssElm = kRef(ytdFlexy);
  3527. if (!scriptEnable || !cssElm) return;
  3528. displayedPlaylist = mWeakRef(document.querySelector('ytd-watch-flexy #tab-list:not(.tab-content-hidden) ytd-playlist-panel-renderer') || null);
  3529. }
  3530.  
  3531.  
  3532. let recordScrollTop = 0
  3533.  
  3534. function switchTabActivity(activeLink) {
  3535. if (!scriptEnable) return;
  3536.  
  3537. const ytdFlexyElm = kRef(ytdFlexy);
  3538.  
  3539. if (!ytdFlexyElm) return;
  3540.  
  3541. if (activeLink && activeLink.classList.contains('tab-btn-hidden')) return; // not allow to switch to hide tab
  3542.  
  3543. if (isTheater() && isWideScreenWithTwoColumns()) activeLink = null;
  3544.  
  3545. /*
  3546. let isPrevTabComments = document.querySelector('.tab-content-cld:not(.tab-content-hidden)');
  3547. isPrevTabComments=isPrevTabComments&&isPrevTabComments.matches('#tab-comments')
  3548.  
  3549. if(isPrevTabComments){
  3550. let comments_tab = document.querySelector('#tab-comments');
  3551. if(comments_tab){
  3552. let st = comments_tab.scrollTop;
  3553. if(st>=0) recordScrollTop = st;
  3554. }
  3555.  
  3556.  
  3557. }
  3558. */
  3559.  
  3560. function runAtEnd() {
  3561.  
  3562. //console.log(12312)
  3563.  
  3564. if (activeLink) lastShowTab = activeLink.getAttribute('userscript-tab-content')
  3565.  
  3566. displayedPlaylist = null;
  3567. scrollingVideosList = null;
  3568.  
  3569. if (activeLink && lastShowTab == '#tab-list') {
  3570. setDisplayedPlaylist();
  3571. } else if (activeLink && lastShowTab == '#tab-videos') {
  3572. scrollingVideosList = mWeakRef(document.querySelector('ytd-watch-flexy #tab-videos:not(.tab-content-hidden) [placeholder-videos]'));
  3573. }
  3574.  
  3575.  
  3576. ytdFlexyElm.setAttribute('tabview-selection', activeLink ? lastShowTab : '')
  3577.  
  3578. if (lastShowTab == '#tab-comments' && (ytdFlexyElm.getAttribute('tabview-youtube-comments') || '').lastIndexOf('S') >= 0) {
  3579.  
  3580. if(mtf_forceCheckLiveVideo_disable===2) {}
  3581. else{
  3582. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'L');
  3583.  
  3584. /*
  3585. requestAnimationFrame(() => {
  3586. let comments_tab = document.querySelector('#tab-comments');
  3587. if (comments_tab && comments_tab.scrollTop > 0) comments_tab.scrollTop = 0;
  3588. });
  3589. */
  3590. }
  3591.  
  3592. }
  3593.  
  3594. /*
  3595. let isNewTabComments = document.querySelector('.tab-content-cld:not(.tab-content-hidden)')
  3596. isNewTabComments=isNewTabComments&&isNewTabComments.matches('#tab-comments')
  3597.  
  3598. if(isNewTabComments){
  3599. let comments_tab = document.querySelector('#tab-comments');
  3600. if(comments_tab){
  3601. let st = comments_tab.scrollTop;
  3602. if(Math.abs(st-recordScrollTop)>0.9) comments_tab.scrollTop=recordScrollTop;
  3603. }
  3604.  
  3605. }
  3606. */
  3607.  
  3608.  
  3609. }
  3610.  
  3611. const links = document.querySelectorAll('#material-tabs a[userscript-tab-content]');
  3612.  
  3613.  
  3614.  
  3615. for (const link of links) {
  3616. let content = document.querySelector(link.getAttribute('userscript-tab-content'));
  3617. if (link && content) {
  3618. if (link !== activeLink) {
  3619. link.classList.remove("active");
  3620. content.classList.add("tab-content-hidden");
  3621. } else {
  3622. link.classList.add("active");
  3623. content.classList.remove("tab-content-hidden");
  3624. //timeline.setTimeout(()=>content.focus(),400);
  3625.  
  3626. }
  3627. }
  3628. }
  3629.  
  3630. runAtEnd();
  3631.  
  3632.  
  3633. }
  3634.  
  3635.  
  3636. const STORE_VERSION = 1;
  3637. const STORE_key = 'userscript-tabview-settings';
  3638. function getStore(){
  3639. let s = localStorage[STORE_key];
  3640. function resetStore(){
  3641. let ret = {
  3642. version: 1,
  3643. };
  3644. localStorage[STORE_key]=JSON.stringify(ret);
  3645. return ret;
  3646. }
  3647. if(!s) return resetStore();
  3648. let obj = null;
  3649. try{
  3650. obj = JSON.parse(s);
  3651. }catch(e){}
  3652. return obj && obj.version === STORE_VERSION ? obj : resetStore();
  3653. }
  3654.  
  3655. function setStore(obj){
  3656. if(!obj || typeof obj !=='object') return false;
  3657. if(obj.version !== STORE_VERSION) return false;
  3658. localStorage[STORE_key]=JSON.stringify(obj);
  3659. return true;
  3660. }
  3661.  
  3662. let tabsUiScript_setclick = false;
  3663.  
  3664. function prepareTabBtn() {
  3665.  
  3666. const materialTab = document.querySelector("#material-tabs")
  3667. if (!materialTab) return;
  3668.  
  3669. let noActiveTab = !!document.querySelector('ytd-watch-flexy[userscript-chatblock]:not([userscript-chat-collapsed])')
  3670.  
  3671. const activeLink = querySelectorFromAnchor.call(materialTab,'a[userscript-tab-content].active:not(.tab-btn-hidden)')
  3672. if (activeLink) switchTabActivity(noActiveTab ? null : activeLink)
  3673.  
  3674. if (!tabsUiScript_setclick) {
  3675. tabsUiScript_setclick = true;
  3676. $(materialTab).on("click", "a", function(evt) {
  3677.  
  3678. //console.log(8510)
  3679. let ytdFlexyElm = kRef(ytdFlexy);
  3680. if (!scriptEnable || !ytdFlexyElm) return null;
  3681.  
  3682. if (!this.hasAttribute('userscript-tab-content')) return;
  3683.  
  3684. if (evt.target.matches('.font-size-btn')) return;
  3685.  
  3686.  
  3687. evt.preventDefault();
  3688.  
  3689. //console.log(8511)
  3690.  
  3691. /*
  3692. if (this.getAttribute('userscript-tab-content') == '#tab-comments' && parseInt(ytdFlexyElm.getAttribute('tabview-youtube-comments') || '') < 0) {
  3693. console.log(8512)
  3694. return;
  3695. }*/
  3696.  
  3697. //console.log(8513)
  3698. new Promise(requestAnimationFrame).then(() => {
  3699.  
  3700.  
  3701. //console.log(8514)
  3702. layoutStatusMutex.lockWith(unlock => {
  3703.  
  3704. //console.log(8515)
  3705. switchTabActivity_lastTab = this.getAttribute('userscript-tab-content');
  3706.  
  3707. let isActiveAndVisible = this.classList.contains('tab-btn') && this.classList.contains('active') && !this.classList.contains('tab-btn-hidden')
  3708.  
  3709. if (isWideScreenWithTwoColumns() && !isTheater() && isActiveAndVisible) {
  3710. //optional
  3711. timeline.setTimeout(unlock, 80);
  3712. switchTabActivity(null);
  3713. ytBtnSetTheater();
  3714. } else if (isActiveAndVisible) {
  3715. timeline.setTimeout(unlock, 80);
  3716. switchTabActivity(null);
  3717. } else {
  3718. let pInterval = 60;
  3719. if (isChatExpand() && isWideScreenWithTwoColumns()) {
  3720. ytBtnCollapseChat();
  3721. } else if (isEngagementPanelExpanded() && isWideScreenWithTwoColumns()) {
  3722. ytBtnCloseEngagementPanels();
  3723. } else if (isWideScreenWithTwoColumns() && isTheater() && !isFullScreen()) {
  3724. ytBtnCancelTheater();
  3725. } else {
  3726. pInterval = 20;
  3727. }
  3728. //console.log(8518)
  3729. timeline.setTimeout(() => {
  3730. timeline.setTimeout(makeBodyScroll, 20); // this is to make the image render
  3731.  
  3732. timeline.setTimeout(() => {
  3733. let rightTabs = document.querySelector('#right-tabs');
  3734. if (!isWideScreenWithTwoColumns() && rightTabs && rightTabs.offsetTop > 0 && this.classList.contains('active')) {
  3735. let tabButtonBar = document.querySelector('#material-tabs');
  3736. let tabButtonBarHeight = tabButtonBar ? tabButtonBar.offsetHeight : 0;
  3737. window.scrollTo(0, rightTabs.offsetTop - tabButtonBarHeight);
  3738. }
  3739. }, 60)
  3740. // console.log(8519)
  3741.  
  3742. timeline.setTimeout(unlock, 80)
  3743. switchTabActivity(this)
  3744.  
  3745. }, pInterval);
  3746. }
  3747.  
  3748.  
  3749. })
  3750.  
  3751. })
  3752.  
  3753.  
  3754.  
  3755.  
  3756. });
  3757. /*
  3758.  
  3759. $(materialTab).on("mousedown", ".font-size-btn", function(evt){
  3760.  
  3761. evt.stopPropagation();
  3762. evt.stopImmediatePropagation();
  3763.  
  3764. });
  3765.  
  3766. $(materialTab).on("pointerdown", ".font-size-btn", function(evt){
  3767.  
  3768. evt.stopPropagation();
  3769. evt.stopImmediatePropagation();
  3770.  
  3771. });
  3772. $(materialTab).on("mouseup", ".font-size-btn", function(evt){
  3773.  
  3774. evt.stopPropagation();
  3775. evt.stopImmediatePropagation();
  3776.  
  3777. });
  3778.  
  3779. $(materialTab).on("pointerup", ".font-size-btn", function(evt){
  3780.  
  3781. evt.stopPropagation();
  3782. evt.stopImmediatePropagation();
  3783.  
  3784. });
  3785. */
  3786.  
  3787. function updateCSS_fontsize(){
  3788.  
  3789. let store = getStore();
  3790. let ytdFlexyElm = kRef(ytdFlexy);
  3791. if(ytdFlexyElm){
  3792. if(store['font-size-#tab-info'])
  3793. ytdFlexyElm.style.setProperty('--ut2257-info', store['font-size-#tab-info'])
  3794. if(store['font-size-#tab-comments'])
  3795. ytdFlexyElm.style.setProperty('--ut2257-comments', store['font-size-#tab-comments'])
  3796. if(store['font-size-#tab-videos'])
  3797. ytdFlexyElm.style.setProperty('--ut2257-videos', store['font-size-#tab-videos'])
  3798. if(store['font-size-#tab-list'])
  3799. ytdFlexyElm.style.setProperty('--ut2257-list', store['font-size-#tab-list'])
  3800. }
  3801.  
  3802. }
  3803.  
  3804. $(materialTab).on("click", ".font-size-btn", function(evt){
  3805.  
  3806. evt.preventDefault();
  3807. evt.stopPropagation();
  3808. evt.stopImmediatePropagation();
  3809.  
  3810. let value = evt.target.matches('.font-size-plus')?1: evt.target.matches('.font-size-minus')?-1 :0;
  3811.  
  3812. let active_tab_content = evt.target.closest('[userscript-tab-content]').getAttribute('userscript-tab-content');
  3813.  
  3814. let store = getStore();
  3815. let settingKey = `font-size-${active_tab_content}`
  3816. if(!store[settingKey]) store[settingKey] = 1.0;
  3817. if(value<0) store[settingKey] -= 0.05;
  3818. if(value>0) store[settingKey] += 0.05;
  3819. setStore(store);
  3820.  
  3821.  
  3822. updateCSS_fontsize();
  3823.  
  3824.  
  3825. //console.log(this.textContent)
  3826.  
  3827.  
  3828. });
  3829.  
  3830. updateCSS_fontsize();
  3831.  
  3832.  
  3833.  
  3834. }
  3835.  
  3836. }
  3837.  
  3838.  
  3839. // ---------------------------------------------------------------------------------------------
  3840. document.addEventListener("yt-navigate-finish", onNavigationEnd)
  3841. //yt-navigate-redirect
  3842. //"yt-page-data-fetched"
  3843. //yt-navigate-error
  3844. //yt-navigate-start
  3845. //yt-page-manager-navigate-start
  3846. //"yt-navigate"
  3847. //"yt-navigate-cache
  3848.  
  3849. document.addEventListener("yt-navigate-cache",()=>{
  3850. console.log('yt-navigate-cache')
  3851. })
  3852. document.addEventListener("yt-navigate-redirect",()=>{
  3853. console.log('yt-navigate-redirect')
  3854. })
  3855.  
  3856. function onReady(){
  3857. //might be earlier than yt-navigation-finish
  3858. console.log('html-onReady')
  3859. if(location.pathname=='/watch') script_inject_js1.inject();
  3860. }
  3861.  
  3862. if(document.readyState!=='loading'){
  3863. onReady();
  3864. }else{
  3865. document.addEventListener('DOMContentLoaded', onReady)
  3866. }
  3867.  
  3868. function forceConfig(){
  3869. let trial = false;
  3870. /*
  3871. let f=()=>{
  3872. if(trial) return;
  3873. let b = true;
  3874. try{
  3875. document.dispatchEvent(new CustomEvent("me-func"))
  3876. window.yt.config_.EXPERIMENT_FLAGS.kevlar_watch_metadata_refresh=true
  3877. }catch(e){
  3878. b=false;
  3879. }
  3880. if(b) trial = true;
  3881. }
  3882. f();
  3883. requestAnimationFrame(f)
  3884. setTimeout(f,30)
  3885. setTimeout(f,300)
  3886. */
  3887. }
  3888.  
  3889. document.addEventListener("yt-navigate-start",()=>{
  3890. console.log('yt-navigate-start') // not always trigger before navigate-end
  3891. script_inject_js1.inject();
  3892. forceConfig();
  3893. })
  3894.  
  3895. document.addEventListener("yt-page-manager-navigate-start",()=>{
  3896. console.log('yt-page-manager-navigate-start')
  3897. forceConfig();
  3898. })
  3899.  
  3900.  
  3901. document.addEventListener("loadstart", (evt) => {
  3902. if (!evt || !evt.target || evt.target.nodeName !== "VIDEO") return;
  3903. let elm = evt.target;
  3904. if (!elm.matches('#player video, #movie_player video, video[tabview-mainvideo]')) return;
  3905.  
  3906. mtc_store= Date.now()+2870
  3907.  
  3908. let src = elm.src;
  3909. if (src !== lastVideoURL) {
  3910. lastVideoURL = elm.src;
  3911. elm.setAttribute('tabview-mainvideo', ''); // mainly for mini playing
  3912. }
  3913.  
  3914. }, true)
  3915.  
  3916. // ---------------------------------------------------------------------------------------------
  3917.  
  3918. let scrolling_lastD = 0;
  3919.  
  3920. const singleColumnScrolling = function(/** @type {boolean} */ scrolling_lastF) {
  3921. if (!scriptEnable || deferredVarYTDHidden) return;
  3922.  
  3923. let pageY = scrollY;
  3924. if (pageY < 10 && scrolling_lastD === 0 && !scrolling_lastF) return;
  3925.  
  3926. let targetElm, header, navElm;
  3927.  
  3928. Promise.resolve().then(() => {
  3929.  
  3930. targetElm = document.querySelector("#right-tabs");
  3931. if (!targetElm) return;
  3932. header = querySelectorFromAnchor.call(targetElm,"header");
  3933. if (!header) return;
  3934. navElm = document.querySelector('#masthead-container, #masthead')
  3935. if (!navElm) return;
  3936. let navHeight = navElm ? navElm.offsetHeight : 0
  3937.  
  3938. let elmY = targetElm.offsetTop
  3939.  
  3940. let xyz = [elmY + navHeight, pageY, elmY - navHeight]
  3941.  
  3942. let xyStatus = 0
  3943. if (xyz[1] < xyz[2] && xyz[2] < xyz[0]) {
  3944. // 1
  3945. xyStatus = 1
  3946. }
  3947.  
  3948. if (xyz[0] > xyz[1] && xyz[1] > xyz[2]) {
  3949.  
  3950. //2
  3951. xyStatus = 2
  3952.  
  3953. }
  3954.  
  3955. if (xyz[2] < xyz[0] && xyz[0] < xyz[1]) {
  3956. // 3
  3957.  
  3958. xyStatus = 3
  3959.  
  3960.  
  3961. }
  3962.  
  3963. return xyStatus;
  3964.  
  3965. }).then((xyStatus) => {
  3966.  
  3967. if ((xyStatus == 2 || xyStatus == 3) && (scrolling_lastD === 0 || scrolling_lastF)) {
  3968. scrolling_lastD = 1;
  3969. let {
  3970. offsetHeight
  3971. } = header
  3972. let {
  3973. offsetWidth
  3974. } = targetElm
  3975.  
  3976. targetElm.style.setProperty("--userscript-sticky-width", offsetWidth + 'px')
  3977. targetElm.style.setProperty("--userscript-sticky", offsetHeight + 'px')
  3978.  
  3979. wAttr(targetElm, 'userscript-sticky', true);
  3980.  
  3981. } else if ((xyStatus == 1) && (scrolling_lastD === 1 || scrolling_lastF)) {
  3982. scrolling_lastD = 0;
  3983.  
  3984. wAttr(targetElm, 'userscript-sticky', false);
  3985. }
  3986.  
  3987.  
  3988. targetElm = null;
  3989. header = null;
  3990. navElm = null;
  3991.  
  3992. });
  3993.  
  3994. };
  3995.  
  3996. window.addEventListener("scroll", function() {
  3997. singleColumnScrolling(false)
  3998. }, {
  3999. capture: false,
  4000. passive: true
  4001. })
  4002.  
  4003. let lastResizeAt = 0;
  4004. window.addEventListener('resize', function() {
  4005.  
  4006. if (!scriptEnable) return;
  4007. if (deferredVarYTDHidden) return;
  4008. lastResizeAt = Date.now();
  4009.  
  4010. requestAnimationFrame(() => {
  4011. singleColumnScrolling(true)
  4012. })
  4013.  
  4014. }, {
  4015. capture: false,
  4016. passive: true
  4017. })
  4018.  
  4019.  
  4020.  
  4021. let hist = null
  4022. const getHistState = (history)=>`${history.length}|${history.state?history.state.entryTime:null}`;
  4023. function newVideoPageCheck(){
  4024. let hState = getHistState(history)
  4025. if(hist!==hState) {
  4026. hist=hState;
  4027. if(scriptEnable){
  4028. //scriptEnable = false;
  4029. let callTimeout = !newVideoPage.entryTime
  4030. newVideoPage.entryTime = 1
  4031. if(callTimeout) setTimeout(newVideoPage,0)
  4032. }
  4033. return true;
  4034. }
  4035. }
  4036. function newVideoPage(){
  4037. newVideoPage.entryTime = 0;
  4038.  
  4039. console.log('newVideoPage')
  4040. //console.log('newVideoPage-', 150, location.href)
  4041.  
  4042. let ytdFlexyElm = kRef(ytdFlexy);
  4043. if(!ytdFlexyElm) return;
  4044.  
  4045. timeline.reset();
  4046. layoutStatusMutex = new Mutex();
  4047.  
  4048. //console.log('newVideoPage-', 350, location.href)
  4049. let flag1= /^https?\:\/\/(\w+\.)*youtube\.com\/watch\?(\w+\=[^\/\?\&]+\&|\w+\=?\&)*v=[\w\-\_]+/.test(location.href)
  4050. let tf = ()=>{
  4051.  
  4052. let isFlexyHidden = (deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden'));
  4053.  
  4054. let flag2 = !isFlexyHidden;
  4055.  
  4056. if(flag1^flag2) return timeline.setTimeout(tf,7); else funcVisibleWatch();
  4057.  
  4058. tf= null;
  4059. funcVisibleWatch = null;
  4060. ytdFlexyElm=null
  4061.  
  4062. }
  4063.  
  4064. let funcVisibleWatch = ()=>{
  4065. //scriptEnable = true;
  4066.  
  4067. let isFlexyHidden = (deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden'));
  4068. ytdFlexyHiddenCheckBasic(ytdFlexyElm)
  4069.  
  4070. if(!isFlexyHidden) {
  4071.  
  4072. mtf_forceCheckLiveVideo_disable = 0;
  4073. mtc_store= Date.now()+2870
  4074.  
  4075. sect_lastUpdate = 0;
  4076. if(pendingOne){
  4077. // reset pendingOne = false if the element is already removed.
  4078. pendingOne = document.querySelectorAll(`ytd-watch-flexy ytd-comments#comments [tabview-cache-time]`).length>1;
  4079. }
  4080.  
  4081. timeline.setTimeout(()=>{
  4082. Q.mutationTarget=null;
  4083. FP.mtf_attrComments()
  4084. },2870)
  4085. if(pageInit_attrComments) hookSection();
  4086.  
  4087.  
  4088.  
  4089.  
  4090.  
  4091. let new_layoutStatus = wls.layoutStatus
  4092.  
  4093. const new_isExpandedChat = !(new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  4094. const new_isCollaspedChat = (new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  4095. const new_isTwoColumns = new_layoutStatus & LAYOUT_TWO_COLUMNS;
  4096. const new_isTheater = new_layoutStatus & LAYOUT_THEATER;
  4097. const new_isTabExpanded = new_layoutStatus & LAYOUT_TAB_EXPANDED;
  4098. const new_isFullScreen = new_layoutStatus & LAYOUT_FULLSCREEN;
  4099. const new_isExpandEPanel = new_layoutStatus & LAYOUT_ENGAGEMENT_PANEL_EXPAND;
  4100. if( ytdFlexyElm.getAttribute('tabview-selection')==='' && new_isTwoColumns && !new_isTheater && !new_isTabExpanded && !new_isFullScreen && !new_isExpandEPanel && !new_isExpandedChat ){
  4101. // e.g. engage panel removed after miniview and change video
  4102. setToActiveTab();
  4103. }else if(new_isExpandEPanel && querySelectorAllFromAnchor.call(ytdFlexyElm,'ytd-engagement-panel-section-list-renderer[visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"]').length===0){
  4104. wls.layoutStatus = new_layoutStatus & (~LAYOUT_ENGAGEMENT_PANEL_EXPAND)
  4105. }
  4106.  
  4107. //mtf_attrFlexy();
  4108.  
  4109. FP.mtf_attrEngagementPanel();
  4110. FP.mtf_attrPlaylist();
  4111. FP.mtf_attrComments();
  4112. FP.mtf_attrChatroom();
  4113.  
  4114.  
  4115. }
  4116.  
  4117. regularCheck(1,0,null); // mutation happens when the page is not ready; call again as the page is ready.
  4118.  
  4119.  
  4120.  
  4121.  
  4122. }
  4123.  
  4124. tf();
  4125.  
  4126.  
  4127. }
  4128.  
  4129.  
  4130.  
  4131. function browserHistoryState(){
  4132. let maxCount = 5
  4133.  
  4134. if (!scriptEnable) return;
  4135. let ytdFlexyElm = kRef(ytdFlexy);
  4136. if(!ytdFlexyElm) return;
  4137.  
  4138. let cid = timeline.setInterval(function(){
  4139. if(newVideoPageCheck()){
  4140. timeline.clearInterval(cid);
  4141. }
  4142. if(--maxCount===0) timeline.clearInterval(cid);
  4143. },7)
  4144.  
  4145. }
  4146.  
  4147.  
  4148. window.addEventListener('hashchange', function() {
  4149. if (!scriptEnable) return;
  4150. console.log('hashchange');
  4151. browserHistoryState();
  4152. }, { capture: true })
  4153.  
  4154. window.addEventListener('popstate', function() {
  4155. if (!scriptEnable) return;
  4156. console.log('popstate');
  4157. browserHistoryState();
  4158. }, { capture: true })
  4159.  
  4160.  
  4161. // function clearMutationObserver(o, key) {
  4162. // if (o[key]) {
  4163. // o[key].takeRecords();
  4164. // o[key].disconnect();
  4165. // o[key] = null;
  4166. // return true;
  4167. // }
  4168. // }
  4169.  
  4170. // function initMutationObserver(o, key, callback) {
  4171. // clearMutationObserver(o, key);
  4172. // const mto = new MutationObserver(callback);
  4173. // o[key] = mto;
  4174. // return mto;
  4175. // }
  4176. // function initMutationObserver2(o, key, mtoFunc) {
  4177. // clearMutationObserver(o, key);
  4178. // const mto = mtoFunc();
  4179. // o[key] = mto;
  4180. // return mto;
  4181. // }
  4182.  
  4183. document.addEventListener('wheel', function(evt) {
  4184.  
  4185. if (!scriptEnable) return;
  4186. const displayedPlaylist_element = kRef(displayedPlaylist);
  4187. if (displayedPlaylist_element && displayedPlaylist_element.contains(evt.target)) {
  4188. evt.stopPropagation();
  4189. evt.stopImmediatePropagation();
  4190. }
  4191. }, { capture: true, passive: true });
  4192.  
  4193.  
  4194. function setVideosTwoColumns(/** @type {number} */ flag, /** @type {boolean} */ bool) {
  4195.  
  4196. //two columns to one column
  4197.  
  4198. /*
  4199. [placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy
  4200.  
  4201. is-two-columns ="" => no is-two-columns
  4202. [placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer
  4203. no hidden => hidden =""
  4204. [placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer
  4205. hidden ="" => no hidden
  4206.  
  4207. */
  4208.  
  4209. let cssSelector1 = '[placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy'
  4210.  
  4211. let cssSelector2 = '[placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer'
  4212.  
  4213. let cssSelector3 = '[placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer'
  4214.  
  4215. let res = {}
  4216. if (flag & 1) {
  4217. res.m1 = document.querySelector(cssSelector1)
  4218. if (res.m1) wAttr(res.m1, 'is-two-columns', bool ? '' : false);
  4219. }
  4220.  
  4221. if (flag & 2) {
  4222. res.m2 = document.querySelector(cssSelector2)
  4223. if (res.m2) wAttr(res.m2, 'hidden', bool ? false : '');
  4224. }
  4225.  
  4226. if (flag & 4) {
  4227. res.m3 = document.querySelector(cssSelector3)
  4228. if (res.m3) wAttr(res.m3, 'hidden', bool ? '' : false);
  4229. }
  4230.  
  4231.  
  4232. return res
  4233.  
  4234.  
  4235.  
  4236.  
  4237. }
  4238.  
  4239. let lastScrollFetch = 0;
  4240. // function isScrolledToEnd(){
  4241. // return (window.innerHeight + window.pageYOffset) >= document.scrollingElement.scrollHeight - 2;
  4242. // }
  4243. let lastOffsetTop = 0;
  4244. window.addEventListener('scroll', function(evt) {
  4245.  
  4246. //console.log(evt.target)
  4247.  
  4248. if (!scriptEnable) return;
  4249.  
  4250.  
  4251. if (!kRef(scrollingVideosList)) return;
  4252. if (videoListBeforeSearch) return;
  4253.  
  4254.  
  4255.  
  4256. let visibleHeight = document.scrollingElement.clientHeight;
  4257. let totalHeight = document.scrollingElement.scrollHeight;
  4258.  
  4259. if (totalHeight < visibleHeight * 1.5) return; // filter out two column view;
  4260.  
  4261. let z = window.pageYOffset + visibleHeight;
  4262. let h_advanced = totalHeight - (visibleHeight > 5 * 40 ? visibleHeight * 0.5 : 40);
  4263.  
  4264.  
  4265.  
  4266. if (z > h_advanced && !isWideScreenWithTwoColumns()) {
  4267.  
  4268. let ct = Date.now();
  4269. if (ct - lastScrollFetch < 500) return; //prevent continuous calling
  4270.  
  4271. lastScrollFetch = ct;
  4272.  
  4273. let res = setVideosTwoColumns(2 | 4, true)
  4274. if (res.m3 && res.m2) {
  4275.  
  4276. //wait for DOM change, just in case
  4277. requestAnimationFrame(() => {
  4278. let { offsetTop } = res.m2 // as visibility of m2 & m3 switched.
  4279.  
  4280. if (offsetTop - lastOffsetTop < 40) return; // in case bug, or repeating calling. // the next button shall below the this button
  4281. lastOffsetTop = offsetTop
  4282.  
  4283. res.m2.parentNode.dispatchEvent(new Event('yt-service-request-sent-button-renderer'))
  4284.  
  4285. res = null
  4286. })
  4287.  
  4288. } else {
  4289.  
  4290. res = null
  4291. }
  4292.  
  4293.  
  4294. }
  4295.  
  4296.  
  4297.  
  4298.  
  4299. }, { passive: true })
  4300.  
  4301. let sect_lastUpdate = 0;
  4302.  
  4303. let sect_holder = null;
  4304. let sect_hText = null;
  4305. let sect_hTime = 0;
  4306.  
  4307. let pendingOne = false;
  4308. let mtf_forceCheckLiveVideo_disable = 0;
  4309.  
  4310. let storeLastPanel = null;
  4311.  
  4312. /** @type {boolean | null} */
  4313. let deferredVarYTDHidden = null;
  4314. let scheduledCommentRefresh = false;
  4315.  
  4316. let pageInit_attrComments = false;
  4317.  
  4318.  
  4319.  
  4320. let mgChatFrame = {
  4321. setVar(elm) {
  4322. mgChatFrame.kVar = mWeakRef(elm)
  4323. },
  4324. getVar() {
  4325. return kRef(mgChatFrame.kVar)
  4326. },
  4327. inPage() {
  4328. let elm = mgChatFrame.getVar();
  4329. if (!elm) return false;
  4330. let ytdFlexyElm = kRef(ytdFlexy);
  4331. if(!ytdFlexyElm) return false;
  4332. return ytdFlexyElm.contains(elm)
  4333. }
  4334. };
  4335.  
  4336. const timeline = {
  4337. // after initialized (initObserver)
  4338. cn1:{},
  4339. cn2:{},
  4340. setTimeout( /** @type {TimerHandler} */ f,/** @type {number} */ d){
  4341. return timeline.cn1[setTimeout(f,d)]=true
  4342. },
  4343. clearTimeout(/** @type {number} */ cid){
  4344. timeline.cn1[cid]=false; return clearTimeout(cid)
  4345. },
  4346. setInterval(/** @type {TimerHandler} */ f,/** @type {number} */ d){
  4347. return timeline.cn2[setInterval(f,d)]=true
  4348. },
  4349. clearInterval(/** @type {number} */ cid){
  4350. timeline.cn2[cid]=false; return clearInterval(cid)
  4351. },
  4352. reset(){
  4353. for(let cid in timeline.cn1) timeline.cn1[cid] && clearTimeout(cid)
  4354. for(let cid in timeline.cn2) timeline.cn2[cid] && clearInterval(cid)
  4355. timeline.cn1={}
  4356. timeline.cn2={}
  4357. }
  4358. }
  4359.  
  4360. class AttributeMutationObserver extends MutationObserver {
  4361. constructor(flist){
  4362. super((mutations, observer)=>{
  4363. for(const mutation of mutations){
  4364. if (mutation.type === 'attributes') {
  4365. this.checker(mutation.target, mutation.attributeName)
  4366. }
  4367. }
  4368. })
  4369. this.flist=flist;
  4370. this.res={}
  4371. }
  4372. takeRecords(){
  4373. super.takeRecords();
  4374. }
  4375. disconnect(){
  4376. this._target = null;
  4377. super.disconnect();
  4378. }
  4379. observe(/** @type {Node} */ target){
  4380. if(this._target) return;
  4381. this._target = mWeakRef(target);
  4382. const options = {
  4383. attributes: true,
  4384. attributeFilter: Object.keys(this.flist),
  4385. //attributeFilter: [ "status", "username" ],
  4386. attributeOldValue: true
  4387. }
  4388. super.observe(target, options)
  4389. }
  4390. checker(/** @type {Node} */ target,/** @type {string} */ attributeName){
  4391. let nv = target.getAttribute(attributeName);
  4392. if(this.res[attributeName]!==nv){
  4393. this.res[attributeName] = nv
  4394. let f = this.flist[attributeName];
  4395. if(f) f(attributeName, nv);
  4396.  
  4397. }
  4398. }
  4399. check(delay = 0){
  4400. setTimeout(()=>{
  4401. let target = kRef(this._target)
  4402. for(const key of Object.keys(this.flist)){
  4403. this.checker(target,key)
  4404. }
  4405. target = null;
  4406. },delay)
  4407. }
  4408. }
  4409.  
  4410. function goYoutubeGeniusLyrics(){
  4411.  
  4412. setTimeout(function $f(){
  4413.  
  4414. if(!document.documentElement.hasAttribute('w-engagement-panel-genius-lyrics')) return setTimeout($f,100)
  4415.  
  4416. document.documentElement.dispatchEvent(new CustomEvent('engagement-panel-genius-lyrics'))
  4417.  
  4418.  
  4419. },100)
  4420.  
  4421.  
  4422.  
  4423. }
  4424.  
  4425.  
  4426. /*
  4427.  
  4428. To be implement: timeline
  4429.  
  4430. timeline.setTimeout
  4431. timeline.clearTimeout
  4432. timeline.setInterval
  4433. timeline.clearInterval
  4434.  
  4435. */
  4436.  
  4437.  
  4438.  
  4439. //Object.keys($0).filter(key=>!(key in $0.constructor.prototype))
  4440.  
  4441. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML'))
  4442. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML')).filter(k=>$0 instanceof window[k])
  4443.  
  4444.  
  4445. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  4446.  
  4447. /*
  4448. fix bug for comment section - version 1.8.7
  4449. This issue is the bug in browser's rendering
  4450. I guess, this is due to the lines clamp with display:-webkit-box
  4451. use stupid coding to let it re-render when its content become visible
  4452. /*
  4453.  
  4454. ytd-expander[should-use-number-of-lines][collapsed] > #content.ytd-expander {
  4455. color: var(--yt-spec-text-primary);
  4456. display: -webkit-box;
  4457. overflow: hidden;
  4458. max-height: none;
  4459. -webkit-box-orient: vertical;
  4460. -webkit-line-clamp: var(--ytd-expander-max-lines, 4);
  4461. }
  4462.  
  4463. // v1.8.36 imposed a effective solution for fixing this bug
  4464.  
  4465. */
  4466.  
  4467. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  4468.  
  4469.  
  4470. /**
  4471. *
  4472.  
  4473.  
  4474. f.initChildrenObserver=function(){var a=this;this.observer=new MutationObserver(function(){return a.childrenChanged()});
  4475. this.observer.observe(this.$.content,{subtree:!0,childList:!0,attributes:!0});this.childrenChanged()};
  4476. 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()})}))};
  4477.  
  4478.  
  4479. f.onIronResize=function(){this.recomputeOnResize&&this.childrenChanged()};
  4480.  
  4481.  
  4482. onButtonClick_:function(){this.fire("yt-close-upsell-dialog")},
  4483. 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};
  4484. n(xI,L);f=xI.prototype;f.alwaysToggleableChanged=function(){this.alwaysToggleable&&(this.canToggle=!0)};
  4485.  
  4486.  
  4487. f.calculateCanCollapse=function(){this.canToggle=this.shouldUseNumberOfLines?this.alwaysToggleable||this.$.content.offsetHeight<this.$.content.scrollHeight:this.alwaysToggleable||this.$.content.scrollHeight>this.collapsedHeight};
  4488. f.detachObserver=function(){this.observer&&this.observer.disconnect()};
  4489.  
  4490. *
  4491. *
  4492. *
  4493. */
  4494.  
  4495.  
  4496.  
  4497.  
  4498. })();
  4499.  
  4500.  
  4501.  
  4502.  
  4503.  
  4504.  
  4505.  
  4506.  
  4507.  
  4508.  
  4509.  
  4510.  
  4511.  
  4512.  
  4513.  
  4514.  
  4515.  
  4516.  
  4517.  
  4518.  
  4519.  
  4520.  
  4521.  
  4522.  
  4523.  
  4524.  
  4525.  
  4526.  
  4527.  
  4528.  
  4529.  
  4530.  
  4531.  
  4532.  
  4533.  
  4534.  
  4535.  
  4536.  
  4537.  
  4538.  
  4539.  
  4540.  
  4541. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  4542.  
  4543. }
  4544.  
  4545.  
  4546. ;!(function $$() {
  4547. 'use strict';
  4548.  
  4549. if(document.documentElement==null) return window.requestAnimationFrame($$)
  4550.  
  4551. const cssTxt = GM_getResourceText("contentCSS");
  4552.  
  4553. function addStyle (styleText) {
  4554. const styleNode = document.createElement('style');
  4555. styleNode.type = 'text/css';
  4556. styleNode.textContent = styleText;
  4557. document.documentElement.appendChild(styleNode);
  4558. return styleNode;
  4559. }
  4560.  
  4561. addStyle (cssTxt);
  4562.  
  4563. main(window.$);
  4564.  
  4565.  
  4566. // Your code here...
  4567. })();