Tabview Youtube

Make comments and lists into tabs for YouTube Videos

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

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