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