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.12
  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;
  1633. const expander = closestDOM.call(domElement, 'ytd-watch-flexy #tab-info ytd-expander')
  1634. if(!expander || expander.nodeType!==1) return;
  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;
  1663.  
  1664. if (domElement.hasAttribute('collapsed')) wAttr(domElement, 'collapsed', false);
  1665. if (domElement.hasAttribute('collapsible')) wAttr(domElement, 'collapsible', false);
  1666. }, 40)
  1667. }
  1668.  
  1669.  
  1670. }
  1671.  
  1672.  
  1673. }
  1674.  
  1675.  
  1676.  
  1677. function isNullComments() {
  1678.  
  1679. let comments = document.querySelector('ytd-comments#comments')
  1680. if (!comments || comments.hasAttribute('hidden')) return true;
  1681.  
  1682. }
  1683.  
  1684. function _innerCommentsLoader( /** @type {HTMLElement} */ rootElement) {
  1685.  
  1686. /** @type {HTMLElement | null} */
  1687. let ytdFlexyElm = kRef(ytdFlexy);
  1688. if (!scriptEnable || !ytdFlexyElm) return;
  1689. if (deferredVarYTDHidden) return;
  1690.  
  1691.  
  1692. let messageElm, messageStr, commentRenderer;
  1693. let diffCSS = `[tabview-cache-time="${sect_hTime}"]`
  1694.  
  1695. if (commentRenderer = querySelectorFromAnchor.call(rootElement,`ytd-comments#comments #count.ytd-comments-header-renderer:not(${diffCSS})`)) {
  1696.  
  1697. scheduledCommentRefresh=false;
  1698. let eTime = Date.now();
  1699.  
  1700. sect_holder = mWeakRef(commentRenderer);
  1701. sect_hText = commentRenderer.textContent;
  1702. sect_hTime = eTime;
  1703. commentRenderer.setAttribute('tabview-cache-time', eTime);
  1704.  
  1705. return {
  1706. status: 1,
  1707. f: () => {
  1708.  
  1709. let span = document.querySelector("span#tab3-txt-loader")
  1710. let r = '0';
  1711. let txt = commentRenderer.textContent
  1712. if (typeof txt == 'string') {
  1713. let m = txt.match(/[\d\,\s]+/)
  1714. if (m) {
  1715. r = m[0].trim()
  1716.  
  1717.  
  1718. }
  1719. }
  1720. if (span){
  1721.  
  1722. let tab_btn = closestDOM.call(span,'.tab-btn[userscript-tab-content="#tab-comments"]')
  1723. if(tab_btn)tab_btn.setAttribute('loaded-comment','normal')
  1724. span.textContent = r;
  1725. }
  1726. //console.log(754)
  1727. mtoInterval = mtoInterval2;
  1728. scheduledCommentRefresh=false;
  1729. setCommentSection(1);
  1730. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents'))
  1731. }
  1732. }
  1733.  
  1734. } 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
  1735. // it is possible to get the message before the header generation.
  1736. // sample link - https://www.youtube.com/watch?v=PVUZ8Nvr1ic
  1737. // sample link - https://www.youtube.com/watch?v=yz8AiQc1Bk8
  1738.  
  1739. scheduledCommentRefresh=false;
  1740. let eTime = Date.now();
  1741.  
  1742. sect_holder = mWeakRef(messageElm);
  1743. sect_hText = messageElm.textContent;
  1744. sect_hTime = eTime;
  1745. messageElm.setAttribute('tabview-cache-time', eTime);
  1746.  
  1747. return {
  1748. status: 2,
  1749. f: () => {
  1750. timeline.setTimeout(function() {
  1751. let span = document.querySelector("span#tab3-txt-loader")
  1752. const mainMsg = querySelectorFromAnchor.call(messageElm,'#message, #submessage')
  1753. if (mainMsg && mainMsg.textContent) {
  1754. for (const msg of querySelectorAllFromAnchor.call(mainMsg,'*:not(:empty)')) {
  1755. if (msg.childElementCount === 0 && msg.textContent) {
  1756. messageStr = msg.textContent.trim()
  1757. break
  1758. }
  1759. }
  1760. }
  1761. if (span){
  1762. let tab_btn = closestDOM.call(span,'.tab-btn[userscript-tab-content="#tab-comments"]')
  1763. if(tab_btn)tab_btn.setAttribute('loaded-comment','message')
  1764. span.textContent ='\u200B';
  1765. }
  1766. mtoInterval = mtoInterval2;
  1767. scheduledCommentRefresh=false;
  1768. setCommentSection(1);
  1769. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents'))
  1770. }, 40);
  1771. }
  1772. }
  1773.  
  1774. }
  1775.  
  1776. }
  1777.  
  1778. const atChange = async ()=>{
  1779.  
  1780. // call when video change / popstate change / switch back from mini-view
  1781.  
  1782. let ytdFlexyElm = kRef(ytdFlexy);
  1783. if(!ytdFlexyElm) return;
  1784.  
  1785. mtf_forceCheckLiveVideo_disable = 0;
  1786. mtf_forceCheckLiveVideo();
  1787.  
  1788. if(Q.comments_section_loaded===0){
  1789.  
  1790. const tabBtn = document.querySelector('[userscript-tab-content="#tab-comments"].tab-btn-hidden')
  1791. if(tabBtn) {
  1792. tabBtn.classList.remove("tab-btn-hidden") //if contains
  1793. }
  1794.  
  1795. }
  1796. }
  1797.  
  1798.  
  1799.  
  1800. function hookSection(){
  1801.  
  1802.  
  1803. //console.log(3300)
  1804.  
  1805. let ytdFlexyElm = kRef(ytdFlexy);
  1806. if (!scriptEnable || !ytdFlexyElm) return ;
  1807.  
  1808. const comments = querySelectorFromAnchor.call(ytdFlexyElm,'ytd-comments#comments')
  1809. if (!comments) return ;
  1810.  
  1811. if(deferredVarYTDHidden) return;
  1812.  
  1813. //console.log(3310)
  1814.  
  1815. //new MutationObserver(function(){console.log(comments.querySelectorAll('*').length)}).observe(comments,{ attributes: true, childList: true, subtree: true })
  1816.  
  1817. function foundSection(sections){
  1818.  
  1819. //console.log(3320)
  1820.  
  1821. function ulfx() {
  1822. //console.log(1220)
  1823.  
  1824.  
  1825. const rootElement = comments.parentNode
  1826.  
  1827.  
  1828. if (pendingOne && querySelectorAllFromAnchor.call(comments,'[tabview-cache-time]').length > 1) return;
  1829. pendingOne = false;
  1830. if(!rootElement) return; //prevent unknown condition
  1831.  
  1832.  
  1833. let innerCommentsLoaderRet = _innerCommentsLoader(rootElement);
  1834.  
  1835. //console.log(1222,_innerCommentsLoader)
  1836.  
  1837. if (!innerCommentsLoaderRet) {
  1838.  
  1839.  
  1840. let holder = kRef(sect_holder);
  1841. if (holder && comments.contains(holder)) {
  1842.  
  1843. if (sect_lastUpdate) return;
  1844. sect_lastUpdate = 1;
  1845.  
  1846. timeline.setTimeout(function() {
  1847. //console.log(2633)
  1848. if (holder.textContent !== sect_hText && sect_hTime > 0) {
  1849.  
  1850. if (querySelectorAllFromAnchor.call(comments,'[tabview-cache-time]').length === 1) {
  1851.  
  1852. sect_hTime--;
  1853.  
  1854. let innerCommentsLoaderRet = _innerCommentsLoader(rootElement);
  1855.  
  1856. if (innerCommentsLoaderRet) {
  1857. //console.log(9442)
  1858. innerCommentsLoaderRet.f();
  1859. fetchCommentsFinished();
  1860. }
  1861.  
  1862. pendingOne = false;
  1863.  
  1864. }
  1865.  
  1866.  
  1867. }
  1868. sect_lastUpdate = 0
  1869. }, 400)
  1870.  
  1871. } else if (sect_holder) {
  1872. sect_holder = null
  1873. sect_hTime = 0;
  1874. sect_lastUpdate = 0;
  1875. pendingOne = false;
  1876. timeline.setTimeout(()=>{
  1877. if(!deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0 && comments.hasAttribute('hidden')){
  1878.  
  1879. scheduledCommentRefresh=false; // logic tbc
  1880. resetCommentSection();
  1881. }
  1882. },142);
  1883. Q.mutationTarget=null;
  1884. FP.mtf_attrComments(); // in case for popstate
  1885. }
  1886.  
  1887.  
  1888. } else {
  1889.  
  1890. //console.log(9443)
  1891. innerCommentsLoaderRet.f();
  1892. fetchCommentsFinished();
  1893.  
  1894. pendingOne = true;
  1895.  
  1896. }
  1897.  
  1898.  
  1899.  
  1900. }
  1901.  
  1902. function observerHook(mutationsList, observer){
  1903.  
  1904. let valid = false
  1905. for (const mutation of mutationsList) {
  1906.  
  1907. let target = mutation.target;
  1908. if (!target) break;
  1909. if (!target.id) break;
  1910. let classList = target.classList;
  1911.  
  1912.  
  1913. if (
  1914. classList.contains('ytd-item-section-renderer') ||
  1915. classList.contains('ytd-comments-header-renderer') ||
  1916. classList.contains('ytd-message-renderer')) {
  1917. valid = true
  1918. break;
  1919. }
  1920.  
  1921. break; // only outest mutation
  1922.  
  1923.  
  1924. }
  1925. if (valid) ulfx();
  1926. }
  1927.  
  1928. if(sections.hasAttribute('tabview-comment-section-checked')){
  1929.  
  1930. //console.log(3612)
  1931. ulfx();
  1932.  
  1933. }else{
  1934.  
  1935. pendingOne = false;
  1936. //console.log(3611)
  1937. const observer = new MutationObserver(observerHook)
  1938. sections.setAttribute('tabview-comment-section-checked','')
  1939. const config = { childList: true, subtree: true };
  1940. observer.observe(sections, config);
  1941. ulfx();
  1942.  
  1943.  
  1944. }
  1945.  
  1946.  
  1947.  
  1948. }
  1949. //console.log(3241, location.href)
  1950. let cid_render_section = timeline.setInterval(function() {
  1951.  
  1952. // console.log(3244, location.href)
  1953.  
  1954.  
  1955. const rootElement = comments.parentNode
  1956.  
  1957. let sections = querySelectorFromAnchor.call(rootElement,'ytd-comments#comments > ytd-item-section-renderer#sections');
  1958.  
  1959.  
  1960. if (sections) {
  1961.  
  1962. timeline.clearInterval(cid_render_section);
  1963. foundSection(sections);
  1964.  
  1965. }
  1966.  
  1967. }, 30)
  1968.  
  1969.  
  1970.  
  1971. }
  1972.  
  1973.  
  1974. let mtc_store=0;
  1975. let mtc_cid = 0;
  1976. const cssOnceFunc = {
  1977. [`ytd-comments#comments:not([o3r-${sa_comments}])`]:(comments)=>{
  1978. // once per {ytd-comments#comments} detection
  1979.  
  1980. let ytdFlexyElm = kRef(ytdFlexy);
  1981. if (!scriptEnable || !ytdFlexyElm) return;
  1982.  
  1983. if (!comments) return;
  1984.  
  1985.  
  1986.  
  1987.  
  1988. if(mtoVisibility_Comments.bindElement(comments)){
  1989. mtoVisibility_Comments.observer.check(9);
  1990. }
  1991. pageInit_attrComments = true
  1992. hookSection();
  1993.  
  1994. //let dComments = comments
  1995. //timeline.setTimeout(() => nativeFunc(dComments, "loadComments"), 20)
  1996. //comments = null;
  1997.  
  1998. },
  1999. [`ytd-playlist-panel-renderer#playlist:not([o3r-${sa_playlist}])`]:(playlist)=>{
  2000.  
  2001. // once per {ytd-playlist-panel-renderer#playlist} detection
  2002.  
  2003. let ytdFlexyElm = kRef(ytdFlexy);
  2004. if (!scriptEnable || !ytdFlexyElm) return;
  2005.  
  2006. if (!playlist) return;
  2007.  
  2008. if(mtoVisibility_Playlist.bindElement(playlist)){
  2009. mtoVisibility_Playlist.observer.check(9) //delay check required for browser bug - hidden changed not triggered
  2010. }
  2011. playlist = null;
  2012.  
  2013. return;
  2014.  
  2015. },
  2016. '#meta-contents ytd-expander:not([tabview-info-expander])':(expander)=>{
  2017.  
  2018. // once per $$native-info-description$$ {#meta-contents ytd-expander} detection
  2019.  
  2020. let ytdFlexyElm = kRef(ytdFlexy);
  2021. if (!scriptEnable || !ytdFlexyElm) return ;
  2022.  
  2023. if (!expander) return ;
  2024. expander.setAttribute('tabview-info-expander','')
  2025. $(expander).appendTo("#tab-info").attr('data-dom-changed-by-tabview-youtube', scriptVersionForExternal)
  2026.  
  2027. },
  2028. '#description-and-actions.style-scope.ytd-watch-metadata > #description ytd-text-inline-expander:not([tabview-removed-duplicate])': (teaserInfo)=>{
  2029.  
  2030.  
  2031. // for Teaser UI
  2032. // once per {#description-and-actions.style-scope.ytd-watch-metadata > #description > ytd-text-inline-expander} detection
  2033.  
  2034. let ytdFlexyElm = kRef(ytdFlexy);
  2035. if (!scriptEnable || !ytdFlexyElm) return ;
  2036. let addedInfo = document.querySelector('#tab-info ytd-expander[tabview-info-expander]');
  2037.  
  2038. if(!addedInfo) return;
  2039.  
  2040. if(!document.documentElement.hasAttribute('tabview-injection-js-1-ready')) return;
  2041.  
  2042. teaserInfo.setAttribute('tabview-removed-duplicate','')
  2043.  
  2044.  
  2045. teaserInfo.dispatchEvent(new CustomEvent('tabview-no-duplicate-info'))
  2046. //console.log(56)
  2047.  
  2048. }
  2049. }
  2050. const cssOnce = Object.keys(cssOnceFunc).join(', ')
  2051.  
  2052. const regularCheck = (addP, removeP, mutationTarget)=>{
  2053.  
  2054.  
  2055. let isInvalidAdding = mutationTarget && !mutationTarget.parentNode
  2056.  
  2057. let promisesForAddition = !scriptEnable ? [] : addP > 0 && !isInvalidAdding ? [
  2058.  
  2059. (async () => {
  2060.  
  2061. //$callOnce('mtf_checkFlexy');
  2062.  
  2063. const rootElement = Q.mutationTarget || kRef(ytdFlexy);
  2064.  
  2065. if(rootElement){
  2066.  
  2067. let fElms = querySelectorAllFromAnchor.call(rootElement,cssOnce)
  2068. if(fElms.length>0){
  2069.  
  2070. for(const fElm of fElms){
  2071. for(let cssSelctor in cssOnceFunc){
  2072. if(fElm.matches(cssSelctor)){
  2073. let f= cssOnceFunc[cssSelctor]
  2074. if(typeof f=='function') f(fElm);
  2075. break;
  2076. }
  2077.  
  2078. }
  2079. }
  2080.  
  2081. //$callOnce('mtf_initalAttr_comments');
  2082. //$callOnce('mtf_initalAttr_playlist');
  2083. // $callOnce('mtf_checkDescriptionLoaded');
  2084. }
  2085.  
  2086. }
  2087.  
  2088. })(),
  2089. (async () => {
  2090.  
  2091.  
  2092. FP.mtf_initalAttr_chatroom();
  2093. FP.mtf_initalAttr_engagement_panel();
  2094. //$callOnce('mtf_initalAttr_chatroom');
  2095. // $callOnce('mtf_initalAttr_engagement_panel');
  2096.  
  2097. mtf_forceCheckLiveVideo();
  2098. mtf_append_comments();
  2099. mtf_liveChatBtnF();
  2100. fixTabs();
  2101. mtf_AfterFixTabs();
  2102. mtf_append_playlist();
  2103.  
  2104. })()
  2105.  
  2106. ] : [];
  2107. let promisesForEveryMutation = !scriptEnable ? [] : [
  2108. (async () => {
  2109. mtf_fix_details();
  2110. mtf_ChatExist();
  2111. })()
  2112. ];
  2113.  
  2114. return [...promisesForAddition, ...promisesForEveryMutation]
  2115.  
  2116.  
  2117. }
  2118.  
  2119. function setOnlyOneEPanel(ePanel){
  2120.  
  2121. layoutStatusMutex.lockWith(unlock => {
  2122.  
  2123. let cPanels = engagement_panels_();
  2124. for (const entry of cPanels.list) {
  2125. if (entry.ePanel != ePanel && entry.visible) ytBtnCloseEngagementPanel(entry.ePanel);
  2126. }
  2127. setTimeout(unlock, 30)
  2128.  
  2129. })
  2130.  
  2131. }
  2132.  
  2133. const FP = {
  2134.  
  2135. mtoNav_delayedF: () => {
  2136.  
  2137. let { addP, removeP, mutationTarget } = Q;
  2138.  
  2139. Q.addP = 0;
  2140. Q.removeP = 0;
  2141. mtc_store=Date.now()+1870
  2142.  
  2143.  
  2144. let regularChecks = regularCheck(addP, removeP, mutationTarget);
  2145.  
  2146. Promise.all(regularChecks).then(() => {
  2147. regularChecks = null;
  2148. mtc_store= Date.now() + 3870 // pending Comments start to load
  2149. Q.mutationTarget = null;
  2150.  
  2151. Q.mtoNav_requestNo--;
  2152. //console.log('motnav reduced to', mtoNav_requestNo)
  2153. if (Q.mtoNav_requestNo > 0) {
  2154. Q.mtoNav_requestNo = 1;
  2155. setTimeout(FP.mtoNav_delayedF, mtoInterval);
  2156. }
  2157. })
  2158.  
  2159.  
  2160. },
  2161.  
  2162. mtoNavF: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  2163. //subtree DOM mutation checker - {ytd-watch-flexy} \single \subtree
  2164.  
  2165. newVideoPageCheck()
  2166.  
  2167. if (!scriptEnable) return;
  2168. if (deferredVarYTDHidden) return;
  2169.  
  2170. let ch = false;
  2171.  
  2172. let reg = [];
  2173. let dTarget = null;
  2174.  
  2175. let wAddP = 0,
  2176. wRemoveP = 0;
  2177.  
  2178. let _last_mto_target = null;
  2179. let _last_mto_target_valid = null;
  2180.  
  2181. for (const mutation of mutations) {
  2182. if (!mutation || !mutation.target || !mutation.target.parentNode) continue;
  2183.  
  2184. let elementalMutation = false;
  2185. let tAddP = 0,
  2186. tRemoveP = 0;
  2187.  
  2188. for (const addedNode of mutation.addedNodes) { //theoretically faster: only reading of states
  2189. if (addedNode.nodeType === 1) {
  2190. tAddP++;
  2191. elementalMutation = true;
  2192. }
  2193. }
  2194.  
  2195. for (const removedNode of mutation.removedNodes) { //theoretically faster: only reading of states
  2196. if (removedNode.nodeType === 1) {
  2197. tRemoveP++;
  2198. elementalMutation = true;
  2199. }
  2200. }
  2201.  
  2202. if (elementalMutation) { //skip all addition and removal operations without elemental changes (e.g. textNode modification)
  2203.  
  2204. if (_last_mto_target === mutation.target) {
  2205. // due to addition and removal operations to the same DOM
  2206. if (_last_mto_target_valid) {
  2207. // AddP & RemoveP is still valid
  2208. wAddP += tAddP;
  2209. wRemoveP += tRemoveP;
  2210. }
  2211. continue;
  2212. }
  2213. _last_mto_target = mutation.target;
  2214.  
  2215. if (isMtoTargetSkip(mutation)) {
  2216. _last_mto_target_valid = false;
  2217. continue; //theoretically slower: creation of string variables
  2218. } else {
  2219. _last_mto_target_valid = true;
  2220. wAddP += tAddP;
  2221. wRemoveP += tRemoveP;
  2222. }
  2223.  
  2224.  
  2225.  
  2226. ch = true;
  2227.  
  2228. reg.push(mutation);
  2229.  
  2230. if (dTarget === null) dTarget = mutation.target; //first
  2231. else if (dTarget === true) {} //ytdFlexy
  2232. else if (dTarget.contains(mutation.target)) {} //first node is the container to all subsequential targets
  2233. else { dTarget = true; } //the target is not the child of first node
  2234.  
  2235. }
  2236.  
  2237. }
  2238.  
  2239. if (!ch) return; // dTarget must be true OR HTMLElement
  2240.  
  2241. if (dTarget === true) dTarget = kRef(ytdFlexy); // major mutation occurance
  2242. else if (dTarget === kRef(comments_section_loaded_elm) && wAddP > wRemoveP) return true; // ignore if comments are loaded (adding comments)
  2243. else if (isMtoOverallSkip(dTarget)) return; // allow for multiple mutations at the same time - determinated after looping
  2244.  
  2245.  
  2246.  
  2247. // 4 ~ 16 times per full page loading
  2248.  
  2249. Q.addP += wAddP;
  2250. Q.removeP += wRemoveP;
  2251.  
  2252. if (Q.mutationTarget === null) Q.mutationTarget = dTarget;
  2253. else if (Q.mutationTarget != dTarget) Q.mutationTarget = kRef(ytdFlexy);
  2254.  
  2255. //console.log(prettyElm(dTarget), wAddP , wRemoveP, mtoInterval)
  2256. //console.log(prettyElm(dTarget), reg.map(m=>prettyElm(m.target)))
  2257. //console.log(7015, performance.now())
  2258.  
  2259.  
  2260.  
  2261. Q.mtoNav_requestNo++;
  2262. if (Q.mtoNav_requestNo == 1) setTimeout(FP.mtoNav_delayedF, mtoInterval);
  2263.  
  2264. },
  2265.  
  2266.  
  2267. mtoBodyF: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  2268. //subtree DOM mutation checker - {body} \single \subtree
  2269.  
  2270. if (!scriptEnable) return;
  2271. if (deferredVarYTDHidden) return;
  2272.  
  2273. for (const mutation of mutations) {
  2274. for (const addedNode of mutation.addedNodes)
  2275. if (addedNode.nodeType === 1) {
  2276. if (addedNode.nodeName == "DIV" && addedNode.matches('.autocomplete-suggestion:not([autocomplete-disable-updatesc])') ) {
  2277. mtf_fixAutoCompletePosition(addedNode)
  2278. }else if(addedNode.nodeName == "DIV" && (addedNode.id==='lyricscontainer' || addedNode.id==='showlyricsbutton')){
  2279.  
  2280. goYoutubeGeniusLyrics();
  2281.  
  2282. }
  2283. }
  2284. }
  2285.  
  2286. },
  2287.  
  2288. mtf_attrPlaylist: (attrName, newValue) => {
  2289. //attr mutation checker - {ytd-playlist-panel-renderer#playlist} \single
  2290. //::attr ~ hidden
  2291. //console.log(1210)
  2292.  
  2293. if (!scriptEnable) return;
  2294. if (deferredVarYTDHidden) return;
  2295. let cssElm = kRef(ytdFlexy);
  2296. if (!cssElm) return;
  2297.  
  2298. let playlist = document.querySelector('ytd-playlist-panel-renderer#playlist')
  2299. const tabBtn = document.querySelector('[userscript-tab-content="#tab-list"]');
  2300. let isPlaylistHidden = playlist.hasAttribute('hidden')
  2301. //console.log(1212.2, isPlaylistHidden, playlist.getAttribute('hidden'))
  2302. if (tabBtn) {
  2303. //console.log('attr playlist changed')
  2304. if (tabBtn.classList.contains('tab-btn-hidden') && !isPlaylistHidden) {
  2305. //console.log('attr playlist changed - no hide')
  2306. tabBtn.classList.remove("tab-btn-hidden");
  2307. } else if (!tabBtn.classList.contains('tab-btn-hidden') && isPlaylistHidden) {
  2308. //console.log('attr playlist changed - add hide')
  2309. hideTabBtn(tabBtn);
  2310. }
  2311. }
  2312. /* visible layout for triggering hidden removal */
  2313. akAttr(cssElm, 'tabview-youtube-playlist', isPlaylistHidden);
  2314. },
  2315. mtf_attrComments: (attrName, newValue) => {
  2316. //attr mutation checker - {ytd-comments#comments} \single
  2317. //::attr ~ hidden
  2318.  
  2319. let ytdFlexyElm = kRef(ytdFlexy);
  2320. if (!scriptEnable || !ytdFlexyElm) return;
  2321. if (deferredVarYTDHidden) return;
  2322.  
  2323. let comments = document.querySelector('ytd-comments#comments')
  2324. const tabBtn = document.querySelector('[userscript-tab-content="#tab-comments"]');
  2325. if (!comments || !tabBtn) return;
  2326. let isCommentHidden = comments.hasAttribute('hidden')
  2327. //console.log('attr comments changed')
  2328.  
  2329. mtoInterval = mtoInterval1;
  2330. mtc_store=Date.now()+2870
  2331.  
  2332. if( mtf_forceCheckLiveVideo_disable === 2 ){
  2333.  
  2334. }else if (!isCommentHidden) {
  2335.  
  2336. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'K');
  2337.  
  2338.  
  2339.  
  2340. //console.log('attr comments changed - no hide')
  2341. tabBtn.classList.remove("tab-btn-hidden") //if contains
  2342.  
  2343. //console.log(703)
  2344.  
  2345. mtc_cid&&timeline.clearInterval(mtc_cid);
  2346.  
  2347. } else if (isCommentHidden) {
  2348.  
  2349. akAttr(ytdFlexyElm, 'tabview-youtube-comments', true, 'K');
  2350. timeline.setTimeout(function(){
  2351. if(!deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0 && comments.hasAttribute('hidden')){
  2352. //console.log(3434)
  2353. scheduledCommentRefresh=false; //logic tbc
  2354. resetCommentSection();
  2355. //console.log(8022)
  2356. }
  2357. },142)
  2358.  
  2359. if(!mtc_cid) mtc_cid=timeline.setInterval(()=>{
  2360. if(mtc_store>Date.now()) return;
  2361. timeline.clearInterval(mtc_cid)
  2362. mtc_cid=0;
  2363. if(mtf_forceCheckLiveVideo_disable===2)return;
  2364. if(isNullComments()) _disableComments();
  2365.  
  2366. },80)
  2367.  
  2368. }
  2369.  
  2370.  
  2371. },
  2372.  
  2373.  
  2374. mtf_attrChatroom: (attrName, newValue) => {
  2375. //attr mutation checker - {ytd-live-chat-frame#chat} \single
  2376. //::attr ~ collapsed
  2377.  
  2378. let ytdFlexyElm = kRef(ytdFlexy);
  2379. if (!scriptEnable || !ytdFlexyElm) return;
  2380. if (deferredVarYTDHidden) return;
  2381.  
  2382. layoutStatusMutex.lockWith(unlock => {
  2383.  
  2384. const chatBlock = document.querySelector('ytd-live-chat-frame#chat')
  2385. const cssElm = kRef(ytdFlexy)
  2386.  
  2387. if (!chatBlock || !cssElm) {
  2388. unlock();
  2389. return;
  2390. }
  2391.  
  2392. if (deferredVarYTDHidden) {
  2393. unlock();
  2394. return;
  2395. }
  2396.  
  2397. if (!cssElm.hasAttribute('userscript-chatblock')) wAttr(cssElm, 'userscript-chatblock', true);
  2398. let isCollapsed = !!chatBlock.hasAttribute('collapsed');
  2399. wAttr(cssElm, 'userscript-chat-collapsed', isCollapsed);
  2400.  
  2401. if (cssElm.hasAttribute('userscript-chatblock') && !isCollapsed) lastShowTab = '#chatroom';
  2402.  
  2403. if (!isCollapsed && document.querySelector('#right-tabs .tab-btn.active') && isWideScreenWithTwoColumns() && !isTheater()) {
  2404. switchTabActivity(null);
  2405. timeline.setTimeout(unlock, 40);
  2406. } else {
  2407. unlock();
  2408. }
  2409.  
  2410. if (!isCollapsed) {
  2411. runAfterExpandChat();
  2412. } else {
  2413. chatBlock.removeAttribute('yt-userscript-iframe-loaded');
  2414. }
  2415.  
  2416. })
  2417.  
  2418.  
  2419.  
  2420.  
  2421. },
  2422.  
  2423. mtf_attrEngagementPanel: ( /** @type {MutationRecord[]} */ mutations, /** @type {MutationObserver} */ observer) => {
  2424. //attr mutation checker - {ytd-engagement-panel-section-list-renderer} \mutiple
  2425. //::attr ~ visibility
  2426.  
  2427. let ytdFlexyElm = kRef(ytdFlexy);
  2428. if (!scriptEnable || !ytdFlexyElm) return;
  2429.  
  2430. //multiple instance
  2431. if (mutations) {
  2432. for (const mutation of mutations) {
  2433. let ePanel = mutation.target;
  2434. if (ePanel.getAttribute('visibility') == 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED') {
  2435. setOnlyOneEPanel(ePanel);
  2436. break;
  2437. }
  2438. }
  2439. }
  2440. if (deferredVarYTDHidden) return;
  2441.  
  2442. layoutStatusMutex.lockWith(unlock => {
  2443.  
  2444. const ePanel = document.querySelector('ytd-watch-flexy ytd-engagement-panel-section-list-renderer')
  2445. const cssElm = kRef(ytdFlexy)
  2446.  
  2447. if (!ePanel || !cssElm) {
  2448. unlock();
  2449. return;
  2450. }
  2451. let previousValue = +cssElm.getAttribute('userscript-engagement-panel') || 0;
  2452.  
  2453. let { shownRes, value, count } = engagement_panels_();
  2454. let nextValue = value;
  2455. let nextCount = count;
  2456.  
  2457.  
  2458. if (nextCount == 0 && cssElm.hasAttribute('userscript-engagement-panel')) {
  2459. storeLastPanel=null;
  2460. wAttr(cssElm, 'userscript-engagement-panel', false);
  2461. unlock();
  2462. } else {
  2463.  
  2464. if ((nextCount > 1) || (cssElm.hasAttribute('userscript-engagement-panel') && previousValue === nextValue)) {
  2465. unlock();
  2466. return;
  2467. }
  2468.  
  2469. cssElm.setAttribute('userscript-engagement-panel', nextValue);
  2470.  
  2471. let b = false;
  2472. if (previousValue != nextValue && nextValue > 0) {
  2473. lastShowTab = `#engagement-panel-${nextValue}`;
  2474. b = true;
  2475. storeLastPanel = mWeakRef( shownRes[0])
  2476. //console.log(9999, shownRes[0])
  2477. }
  2478.  
  2479. if (b && document.querySelector('#right-tabs .tab-btn.active') && isWideScreenWithTwoColumns() && !isTheater()) {
  2480. switchTabActivity(null);
  2481. timeline.setTimeout(unlock, 40);
  2482. } else {
  2483. unlock();
  2484. }
  2485. }
  2486.  
  2487. })
  2488.  
  2489.  
  2490.  
  2491.  
  2492. },
  2493.  
  2494. mtf_initalAttr_playlist: () => {
  2495. },
  2496.  
  2497. mtf_initalAttr_comments: () => {
  2498. },
  2499.  
  2500. mtf_initalAttr_chatroom: () => {
  2501. // every per [new] {ytd-live-chat-frame#chat} detection - reset after mini-playview
  2502. let ytdFlexyElm = kRef(ytdFlexy);
  2503. if (!scriptEnable || !ytdFlexyElm) return true;
  2504.  
  2505. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2506.  
  2507.  
  2508. if (!mgChatFrame.inPage()) {
  2509.  
  2510. mtoVisibility_Chatroom.clear(true);
  2511.  
  2512. let chatroom = querySelectorFromAnchor.call(rootElement,`ytd-live-chat-frame#chat:not([${sa_chatroom}]`)
  2513. if (chatroom) {
  2514. mgChatFrame.setVar(chatroom);
  2515.  
  2516. if(mtoVisibility_Chatroom.bindElement(chatroom)){
  2517. mtoVisibility_Chatroom.observer.check(9)
  2518. }
  2519.  
  2520. chatroom = null
  2521. }
  2522. }
  2523. return true;
  2524.  
  2525. },
  2526.  
  2527. mtf_initalAttr_engagement_panel: () => {
  2528. // every per $$non-checked-section-list$$ {ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([o3r-XXXXX])} detection
  2529. let ytdFlexyElm = kRef(ytdFlexy);
  2530. if (!scriptEnable || !ytdFlexyElm) return true;
  2531.  
  2532. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2533.  
  2534. let toCheck = false;
  2535. for (const engagement_panel of querySelectorAllFromAnchor.call(rootElement,
  2536. `ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([o3r-${sa_epanel}])`
  2537. )) {
  2538.  
  2539.  
  2540.  
  2541. let bindRes = mtoVisibility_EngagementPanel.bindElement(engagement_panel, {
  2542. attributes: true,
  2543. attributeFilter: ['visibility'],
  2544. attributeOldValue: true
  2545. })
  2546.  
  2547. if(bindRes) toCheck = true;
  2548. }
  2549.  
  2550. if (toCheck) FP.mtf_attrEngagementPanel()
  2551.  
  2552. return true;
  2553. },
  2554.  
  2555.  
  2556.  
  2557. //live-chat / chat-replay
  2558.  
  2559. fireOnce_forceCheckLiveVideo_tf: () => {
  2560. // once per $$player-playback-timestamp$$ {#ytd-player .ytp-time-display} && $$chat-frame$$ {ytd-live-chat-frame#chat} detection
  2561.  
  2562. let ytdFlexyElm = kRef(ytdFlexy);
  2563. if (!scriptEnable || !ytdFlexyElm) return;
  2564.  
  2565. let elm = document.querySelector('#ytd-player .ytp-time-display');
  2566. if (elm && elm.classList.contains('ytp-live')) {
  2567. //console.log(7006)
  2568. ytdFlexyElm.setAttribute('userscript-chatblock', 'chat-live')
  2569. //console.log(2441)
  2570. mtf_forceCheckLiveVideo_disable = 2;
  2571. _disableComments();
  2572. //console.log(701)
  2573. //disableComments_LiveChat();
  2574. }
  2575. },
  2576.  
  2577.  
  2578. //comments
  2579. /*
  2580. mtf_advancedComments: () => {
  2581. // once per {ytd-comments#comments #continuations} detection
  2582.  
  2583. //let ytdFlexyElm = kRef(ytdFlexy);
  2584. //if (!scriptEnable || !ytdFlexyElm) return true;
  2585.  
  2586. //const rootElement = Q.mutationTarget || ytdFlexyElm;
  2587. //const continuations = document.querySelector("ytd-comments#comments #continuations");
  2588. //if (!continuations) return true;
  2589. //requestingComments = document.querySelector('ytd-comments#comments');
  2590. //scrollForComments();
  2591. return false;
  2592. }
  2593. */
  2594.  
  2595.  
  2596. }
  2597.  
  2598.  
  2599.  
  2600.  
  2601.  
  2602. /** @type {WeakRef | null} */
  2603. let displayedPlaylist = null;
  2604. /** @type {WeakRef | null} */
  2605. let scrollingVideosList = null;
  2606.  
  2607. let scriptEnable = false;
  2608. let scriptEC = 0;
  2609. let lastShowTab = null;
  2610.  
  2611. let _cachedLastVideo = null;
  2612. let videoListBeforeSearch = null;
  2613. let no_fix_contents_until = 0;
  2614. let no_fix_playlist_until = 0;
  2615. let statusCollasped = 0;
  2616.  
  2617. /** @type {WeakRef | null} */
  2618. let ytdFlexy = null;
  2619.  
  2620. function pluginUnhook() {
  2621. _pluginUnhook();
  2622. resetCommentSection();
  2623. }
  2624.  
  2625. function _pluginUnhook() {
  2626.  
  2627. sect_lastUpdate = 0;
  2628. sect_holder = null;
  2629. sect_hTime = 0;
  2630.  
  2631. //console.log(8001)
  2632.  
  2633. videoListBeforeSearch = null;
  2634. statusCollasped = 0;
  2635. _cachedLastVideo = null;
  2636. lastShowTab = null;
  2637. displayedPlaylist = null;
  2638. scrollingVideosList = null;
  2639. scriptEnable = false;
  2640. scriptEC++;
  2641. if (scriptEC > 788888888) scriptEC = 188888888;
  2642. ytdFlexy = null;
  2643. wls.layoutStatus = null;
  2644.  
  2645. //console.log('unc01')
  2646.  
  2647. mtoVisibility_EngagementPanel.clear(true)
  2648. mtoVisibility_Playlist.clear(true)
  2649. mtoVisibility_Comments.clear(true)
  2650.  
  2651. mgChatFrame.kVar = null;
  2652. mtoVisibility_Chatroom.clear(true)
  2653. mtoFlexyAttr.clear(true)
  2654.  
  2655.  
  2656. for (const elem of document.querySelectorAll(
  2657. ['ytd-expander[tabview-info-expander]'].join(', ')
  2658. )) {
  2659. elem.removeAttribute('tabview-info-expander');
  2660. }
  2661.  
  2662. mtoMutation_body.clear(true)
  2663. mtoMutation_watchFlexy.clear(true)
  2664. //FOnce.mtf_checkFlexy = null;
  2665. //FOnce.mtf_initalAttr_comments = null;
  2666. //FOnce.mtf_initalAttr_playlist = null;
  2667. //FOnce.mtf_initalAttr_chatroom = null;
  2668. //FOnce.mtf_initalAttr_engagement_panel = null;
  2669. //FOnce.mtf_advancedComments = null;
  2670. //FOnce.mtf_checkDescriptionLoaded = null;
  2671. //FOnce.mtf_forceCheckLiveVideo = null;
  2672. Q.mtf_chatBlockQ = null;
  2673.  
  2674.  
  2675. mtoInterval = mtoInterval1;
  2676.  
  2677. }
  2678.  
  2679. let comments_section_loaded_elm = null;
  2680.  
  2681.  
  2682.  
  2683. function getTabsHTML() {
  2684.  
  2685. const sTabBtnVideos = `${svgElm(16,16,298,298,svgVideos)}<span>Videos</span>`
  2686. const sTabBtnInfo = `${svgElm(16,16,23.625,23.625,svgInfo)}<span>Info</span>`
  2687. const sTabBtnPlayList = `${svgElm(16,16,426.667,426.667,svgPlayList)}<span>Playlist</span>`
  2688.  
  2689. let str1 = `
  2690. <paper-ripple class="style-scope yt-icon-button">
  2691. <div id="background" class="style-scope paper-ripple" style="opacity:0;"></div>
  2692. <div id="waves" class="style-scope paper-ripple"></div>
  2693. </paper-ripple>
  2694. `;
  2695.  
  2696. let str_fbtns = `
  2697. <div class="font-size-right">
  2698. <div class="font-size-btn font-size-plus">
  2699. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  2700. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  2701. <path d="M12 25h26"/><path d="M25 12v26"/>
  2702. </svg>
  2703. </div><div class="font-size-btn font-size-minus">
  2704. <svg width="12" height="12" viewbox="0 0 50 50" preserveAspectRatio="xMidYMid meet"
  2705. stroke="currentColor" stroke-width="6" stroke-linecap="round" vector-effect="non-scaling-size">
  2706. <path d="M12 25h26"/>
  2707. </svg>
  2708. </div>
  2709. </div>
  2710. `.replace(/[\r\n]+/g,'')
  2711.  
  2712. const str_tabs = [
  2713. `<a id="tab-btn1" data-name="info" userscript-tab-content="#tab-info" class="tab-btn">${sTabBtnInfo}${str1}${str_fbtns}</a>`,
  2714. `<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>`,
  2715. `<a id="tab-btn4" userscript-tab-content="#tab-videos" data-name="videos" class="tab-btn">${sTabBtnVideos}${str1}${str_fbtns}</a>`,
  2716. `<a id="tab-btn5" userscript-tab-content="#tab-list" class="tab-btn">${sTabBtnPlayList}${str1}${str_fbtns}</a>`
  2717. ].join('')
  2718.  
  2719. let addHTML = `
  2720. <div id="right-tabs">
  2721. <header>
  2722. <div id="material-tabs">
  2723. ${str_tabs}
  2724. </div>
  2725. </header>
  2726. <div class="tab-content">
  2727. <div id="tab-info" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2728. <div id="tab-comments" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2729. <div id="tab-videos" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2730. <div id="tab-list" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2731. </div>
  2732. </div>
  2733. `;
  2734.  
  2735. return addHTML
  2736.  
  2737. }
  2738.  
  2739.  
  2740. function onVideoChange() {
  2741. // for popstate & next video
  2742.  
  2743. newVideoPageCheck();
  2744.  
  2745. scheduledCommentRefresh=true;
  2746. let comments = document.querySelector('ytd-comments#comments')
  2747. if(!deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0 && comments.hasAttribute('hidden')){
  2748.  
  2749. scheduledCommentRefresh=false;
  2750. // comment tab btn - hide by timer in attribute change
  2751. resetCommentSection();
  2752. }
  2753.  
  2754. mtf_forceCheckLiveVideo_disable = 0
  2755. mtc_store= Date.now()+3870
  2756.  
  2757. if (deferredVarYTDHidden) { // reset info when hidden
  2758. resetCommentSection();
  2759. }else{
  2760. checkVisibleEngagementPanel();
  2761. atChange(); // in case no mutation occurance
  2762. }
  2763.  
  2764.  
  2765.  
  2766. }
  2767.  
  2768. function onNavigationEnd(evt) {
  2769. console.log('yt-navigate-finish')
  2770. no_fix_contents_until = 0;
  2771. no_fix_playlist_until = 0;
  2772. document.documentElement.setAttribute('youtube-ready','')
  2773. script_inject_js1.inject();
  2774. document.documentElement.dispatchEvent(new CustomEvent('tabview-ce-hack'))
  2775.  
  2776. forceConfig();
  2777. /*
  2778. console.log(window.ytcfg)
  2779. try{
  2780. window.ytcfg.set({
  2781. "EXPERIMENT_FLAGS": {"kevlar_watch_metadata_refresh":false}})
  2782. }catch(e){}
  2783. */
  2784.  
  2785. newVideoPageCheck(); // required for init
  2786.  
  2787. let mRet =
  2788. (/^https?\:\/\/(\w+\.)*youtube\.com\/watch\?(\w+\=[^\/\?\&]+\&|\w+\=?\&)*v=[\w\-\_]+/.test(window.location.href) ? 1 : 0) +
  2789. (document.querySelector('ytd-watch-flexy[tabview-selection]') ? 2 : 0);
  2790.  
  2791. if (mRet === 1) {
  2792.  
  2793. document.addEventListener('loadedmetadata', function(evt) {
  2794. if (evt.target.matches('video[tabview-mainvideo]')) {
  2795. setTimeout(onVideoChange, 30)
  2796. }
  2797. }, true)
  2798.  
  2799. pluginUnhook(); // in case not triggered by popstate - say mini playing
  2800.  
  2801. let timeout = 4; // max. 4 animation frames
  2802.  
  2803. let tf = () => {
  2804.  
  2805. if (--timeout > 0 && !document.querySelector('#player video')) return requestAnimationFrame(tf);
  2806.  
  2807. let ytdFlexyElm = document.querySelector('ytd-watch-flexy')
  2808.  
  2809. if(!ytdFlexyElm) return;
  2810.  
  2811.  
  2812. scriptEnable = true;
  2813. scriptEC++;
  2814.  
  2815. no_fix_contents_until = 0;
  2816. no_fix_playlist_until = 0;
  2817.  
  2818. ytdFlexy = mWeakRef(ytdFlexyElm)
  2819.  
  2820. let timeoutR_findRelated = new Timeout();
  2821. timeoutR_findRelated.set(function() {
  2822. let ytdFlexyElm = kRef(ytdFlexy);
  2823. if(!ytdFlexyElm) return true;
  2824. let related = querySelectorFromAnchor.call(ytdFlexyElm,"#related");
  2825. if (!related) return true;
  2826. foundRelated(related);
  2827. }, 100, 10)
  2828.  
  2829. function foundRelated(related) {
  2830. let promise = Promise.resolve();
  2831. if (!document.querySelector("#right-tabs")) {
  2832. promise = promise.then(() => {
  2833. $(getTabsHTML()).insertBefore(related).attr('data-dom-created-by-tabview-youtube', scriptVersionForExternal);
  2834. })
  2835. }
  2836. promise.then(runAfterTabAppended)
  2837. }
  2838.  
  2839. /*
  2840. setTimeout(() => {
  2841. for (const s of document.querySelectorAll('#right-tabs [userscript-scrollbar-render]')) {
  2842. Promise.resolve(s).then(s => {
  2843. if (s && s.scrollTop > 0) s.scrollTop = 0;
  2844. let child = s.firstElementChild;
  2845. if (child && child.scrollTop > 0) child.scrollTop = 0;
  2846. });
  2847. }
  2848. }, 90)
  2849. */
  2850.  
  2851.  
  2852. }
  2853.  
  2854. tf();
  2855.  
  2856. } else if (mRet === 3) {
  2857.  
  2858. if(!scriptEnable) return;
  2859.  
  2860. let elmComments = document.querySelector('ytd-comments#comments')
  2861.  
  2862. if (elmComments) {
  2863. nativeFunc(elmComments, "loadComments")
  2864. }
  2865.  
  2866. } else if (mRet === 0) {
  2867.  
  2868. pluginUnhook(); // in case not triggered by popstate - say mini playing
  2869.  
  2870. }
  2871.  
  2872. if(mRet & 1){
  2873. setTimeout(()=>{
  2874. Q.mutationTarget=null;
  2875. atChange(); // in case no mutation occurance
  2876. FP.mtf_attrComments()
  2877. },160);
  2878. }
  2879.  
  2880. }
  2881.  
  2882.  
  2883. function setToActiveTab(defaultTab) {
  2884. if (isTheater() && isWideScreenWithTwoColumns()) return;
  2885. const jElm = document.querySelector(`a[userscript-tab-content="${switchTabActivity_lastTab}"]:not(.tab-btn-hidden)`) ||
  2886. document.querySelector(`a[userscript-tab-content="${(defaultTab||settings.defaultTab)}"]:not(.tab-btn-hidden)`) ||
  2887. document.querySelector("a[userscript-tab-content]:not(.tab-btn-hidden)") ||
  2888. null;
  2889. switchTabActivity(jElm);
  2890. return !!jElm;
  2891. }
  2892.  
  2893. function getWrapper(wrapperId) {
  2894. let $wrapper = $(`#${wrapperId}`);
  2895. if (!$wrapper[0]) $wrapper = $(`<div id="${wrapperId}"></div>`)
  2896. return $wrapper.first();
  2897. }
  2898.  
  2899. function runAfterTabAppended() {
  2900.  
  2901. document.documentElement.setAttribute('plugin-tabview-youtube', '')
  2902.  
  2903. const ytdFlexyElm = kRef(ytdFlexy)
  2904. if(!ytdFlexyElm) return;
  2905. if (!ytdFlexyElm.hasAttribute('tabview-selection')) ytdFlexyElm.setAttribute('tabview-selection', '')
  2906.  
  2907.  
  2908. //console.log('unc02')
  2909.  
  2910. // append the next videos
  2911. // it exists as "related" is already here
  2912. fixTabs();
  2913.  
  2914. // just switch to the default tab
  2915. setToActiveTab();
  2916.  
  2917.  
  2918. prepareTabBtn();
  2919.  
  2920.  
  2921. // append the detailed meta contents to the tab-info
  2922. // ** FOnce.mtf_checkDescriptionLoaded = FP.mtf_checkDescriptionLoaded;
  2923. // ** if (Q.mutationTarget === null) $callOnceAsync('mtf_checkDescriptionLoaded');
  2924.  
  2925. // force window scroll when #continuations is first detected and #comments still [hidden]
  2926. //FOnce.mtf_advancedComments = FP.mtf_advancedComments;
  2927. //if (Q.mutationTarget === null) $callOnceAsync('mtf_advancedComments');
  2928.  
  2929. // use video player's element to detect the live-chat situation (no commenting section)
  2930. // 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
  2931. //FOnce.mtf_forceCheckLiveVideo = FP.mtf_forceCheckLiveVideo;
  2932. //if (Q.mutationTarget === null) $callOnceAsync('mtf_forceCheckLiveVideo');
  2933. //mtf_forceCheckLiveVideo();
  2934.  
  2935.  
  2936. // Attr Mutation Observer - #playlist - hidden
  2937. //clearMutationObserver(mtoVs, 'mtoVisibility_Playlist')
  2938. // Attr Mutation Observer callback - #playlist - hidden
  2939.  
  2940. // pending for #playlist and set Attribute Observer
  2941. // ** FOnce.mtf_initalAttr_playlist = FP.mtf_initalAttr_playlist
  2942. // ** if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_playlist');
  2943.  
  2944. // Attr Mutation Observer - ytd-comments#comments - hidden
  2945. //clearMutationObserver(mtoVs, 'mtoVisibility_Comments')
  2946. // Attr Mutation Observer callback - ytd-comments#comments - hidden
  2947.  
  2948. // pending for #comments and set Attribute Observer
  2949. // ** FOnce.mtf_initalAttr_comments = FP.mtf_initalAttr_comments;
  2950. // ** if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_comments');
  2951.  
  2952.  
  2953. //clearMutationObserver(mtoVs, 'mtoVisibility_Chatroom');
  2954. //FOnce.mtf_initalAttr_chatroom = FP.mtf_initalAttr_chatroom
  2955. //if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_chatroom');
  2956.  
  2957. // clearMutationObserver(mtoVs, 'mtoVisibility_EngagementPanel');
  2958. // for (const engagement_panel of document.querySelectorAll('ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([tabview-attr-checked])')) {
  2959. // engagement_panel.removeAttribute('tabview-attr-checked');
  2960. // }
  2961. //FOnce.mtf_initalAttr_engagement_panel = FP.mtf_initalAttr_engagement_panel
  2962. //if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_engagement_panel');
  2963.  
  2964.  
  2965. mtoFlexyAttr.clear(true)
  2966. mtf_checkFlexy()
  2967.  
  2968.  
  2969. document.querySelector("#right-tabs .tab-content").addEventListener('scroll', makeBodyScrollByEvt, true);
  2970.  
  2971.  
  2972. Q.addP = 0;
  2973. Q.removeP = 0;
  2974. Q.mutationTarget = null;
  2975.  
  2976. Q.mtoNav_requestNo = 0;
  2977.  
  2978.  
  2979. mtoMutation_watchFlexy.bindElement(ytdFlexyElm, {
  2980. childList: true,
  2981. subtree: true,
  2982. attributes: false
  2983. })
  2984.  
  2985. // for automcomplete plugin or other userscript plugins
  2986. // document.body for Firefox >= 60
  2987. mtoMutation_body.bindElement(document.querySelector('body'), {
  2988. childList: true,
  2989. subtree: false,
  2990. attributes: false
  2991. })
  2992.  
  2993.  
  2994. no_fix_contents_until = 0;
  2995. no_fix_playlist_until = 0;
  2996. scriptEnable = true;
  2997. regularCheck(1, 0, null);
  2998.  
  2999.  
  3000.  
  3001.  
  3002. }
  3003.  
  3004.  
  3005. function fetchCommentsFinished() {
  3006. let ytdFlexyElm = kRef(ytdFlexy);
  3007. if (!scriptEnable || !ytdFlexyElm) return;
  3008. if(mtf_forceCheckLiveVideo_disable===2) return;
  3009. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'LS')
  3010. }
  3011.  
  3012. function setCommentSection( /** @type {number} */ value) {
  3013.  
  3014. Q.comments_section_loaded = value;
  3015.  
  3016. if (value === 0) {
  3017. sect_lastUpdate = 0;
  3018. comments_section_loaded_elm = null;
  3019. }
  3020.  
  3021. }
  3022.  
  3023. function resetCommentSection(){
  3024.  
  3025. let tab_btn = document.querySelector('.tab-btn[userscript-tab-content="#tab-comments"]')
  3026.  
  3027.  
  3028. if(tab_btn){
  3029.  
  3030. let span = querySelectorFromAnchor.call(tab_btn,'span#tab3-txt-loader');
  3031.  
  3032. tab_btn.removeAttribute('loaded-comment')
  3033. tab_btn.classList.remove('tab-btn-hidden')
  3034. if(span){
  3035. span.textContent='';
  3036. }
  3037. }
  3038.  
  3039.  
  3040. setCommentSection(0);
  3041.  
  3042.  
  3043. }
  3044.  
  3045. function _disableComments() {
  3046. //requestingComments = null;
  3047. mtc_cid && timeline.clearInterval(mtc_cid)
  3048. mtc_cid=0;
  3049.  
  3050. if (!scriptEnable) return;
  3051. let cssElm = kRef(ytdFlexy);
  3052. if (!cssElm) return;
  3053.  
  3054. mtoInterval = mtoInterval2;
  3055.  
  3056. if(Q.comments_section_loaded>0) return; //already displayed / disabled
  3057.  
  3058. scheduledCommentRefresh=false;
  3059. setCommentSection(2);
  3060.  
  3061. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents') || null)
  3062.  
  3063. let tabBtn = document.querySelector('.tab-btn[userscript-tab-content="#tab-comments"]');
  3064. if(tabBtn) {
  3065. tabBtn.removeAttribute('loaded-comment')
  3066. if (!tabBtn.classList.contains('tab-btn-hidden')) {
  3067. hideTabBtn(tabBtn)
  3068. }
  3069. }
  3070.  
  3071. akAttr(cssElm, 'tabview-youtube-comments', true, 'D');
  3072.  
  3073.  
  3074. }
  3075.  
  3076.  
  3077.  
  3078.  
  3079. let layoutStatusMutex = new Mutex();
  3080.  
  3081. function forceDisplayChatReplay() {
  3082. let items = chatFrameElement('yt-live-chat-item-list-renderer #items');
  3083. if (items && items.childElementCount !== 0) return;
  3084.  
  3085. let ytd_player = document.querySelector('ytd-player#ytd-player');
  3086. if (!ytd_player) return;
  3087. let videoElm = querySelectorFromAnchor.call(ytd_player,'video');
  3088. if (!videoElm) return;
  3089.  
  3090. let video = videoElm;
  3091. if (videoElm && video.currentTime > 0 && !video.ended && video.readyState > video.HAVE_CURRENT_DATA) {
  3092. let chat = document.querySelector('ytd-live-chat-frame#chat');
  3093. if (chat) {
  3094. nativeFunc(chat, "postToContentWindow", [{ "yt-player-video-progress": videoElm.currentTime }])
  3095. }
  3096. }
  3097.  
  3098. }
  3099.  
  3100.  
  3101.  
  3102. function runAfterExpandChat() {
  3103.  
  3104.  
  3105. if(runAfterExpandChat.cid_chatFrameCheck1) timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3106. if(runAfterExpandChat.cid_chatFrameCheck2) timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3107. runAfterExpandChat.cid_chatFrameCheck1=0;
  3108. runAfterExpandChat.cid_chatFrameCheck2=0;
  3109.  
  3110. new Promise(resolve => {
  3111.  
  3112. let chatFrame_st = Date.now();
  3113. runAfterExpandChat.cid_chatFrameCheck1 = 0;
  3114.  
  3115. let sEF = new ScriptEF();
  3116. runAfterExpandChat.cid_chatFrameCheck1 = timeline.setInterval(() => {
  3117. if (!sEF.isValid()) return runAfterExpandChat.cid_chatFrameCheck1 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3118. let cDoc = chatFrameContentDocument();
  3119. if (cDoc) {
  3120. runAfterExpandChat.cid_chatFrameCheck1 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3121. resolve();
  3122. } else if (!scriptEnable || !isChatExpand() || Date.now() - chatFrame_st > 6750) {
  3123. runAfterExpandChat.cid_chatFrameCheck1 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck1);
  3124. }
  3125. }, 60);
  3126.  
  3127.  
  3128. }).then(() => new Promise(resolve => {
  3129.  
  3130.  
  3131. let chatFrame_st = Date.now();
  3132. runAfterExpandChat.cid_chatFrameCheck2 = 0;
  3133.  
  3134. let sEF = new ScriptEF();
  3135. runAfterExpandChat.cid_chatFrameCheck2 = timeline.setInterval(() => {
  3136. if (!sEF.isValid()) return runAfterExpandChat.cid_chatFrameCheck2 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3137. let app = chatFrameElement('yt-live-chat-app');
  3138. if (app) {
  3139. runAfterExpandChat.cid_chatFrameCheck2 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3140. resolve(app);
  3141. } else if (!scriptEnable || !isChatExpand() || Date.now() - chatFrame_st > 6750*3) {
  3142. runAfterExpandChat.cid_chatFrameCheck2 = timeline.clearInterval(runAfterExpandChat.cid_chatFrameCheck2);
  3143. }
  3144. }, 60);
  3145.  
  3146.  
  3147. })).then(app => {
  3148.  
  3149.  
  3150. let cDoc = app.ownerDocument;
  3151.  
  3152. if (!scriptEnable || !isChatExpand()) return;
  3153. if(cDoc.querySelector('#userscript-tabview-chatroom-css')) return;
  3154. addStyle(`
  3155. body #input-panel.yt-live-chat-renderer::after {
  3156. background: transparent;
  3157. }
  3158. #items.yt-live-chat-item-list-renderer{
  3159. contain: content;
  3160. }
  3161. yt-live-chat-text-message-renderer{
  3162. contain: content;
  3163. }
  3164. #item-offset.yt-live-chat-item-list-renderer{
  3165. contain: content;
  3166. }
  3167. #item-scroller.yt-live-chat-item-list-renderer{
  3168. contain: strict;
  3169. }
  3170. img[width][height]{
  3171. contain: strict;
  3172. }
  3173. #item-list > yt-live-chat-item-list-renderer, #item-list > yt-live-chat-item-list-renderer > #contents{
  3174. contain: strict;
  3175. }
  3176.  
  3177.  
  3178. #chat.style-scope.yt-live-chat-renderer,
  3179. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer,
  3180. #item-scroller,
  3181. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer .style-scope.yt-live-chat-text-message-renderer,
  3182. yt-live-chat-ticker-paid-message-item-renderer
  3183. {
  3184. contain: layout paint style;
  3185. }
  3186. yt-img-shadow#author-photo.style-scope{
  3187. contain: layout paint style;
  3188. content-visibility: auto;
  3189. contain-intrinsic-size: 24px 24px;
  3190. }
  3191. #item-offset.style-scope.yt-live-chat-item-list-renderer,
  3192. #items.style-scope.yt-live-chat-item-list-renderer {
  3193. contain: layout paint;
  3194. }
  3195. .style-scope.yt-live-chat-text-message-renderer {
  3196. cursor: default;
  3197. }
  3198. #author-photo.style-scope.yt-live-chat-text-message-renderer,
  3199. yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer,
  3200. yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer ~ span#message.style-scope.yt-live-chat-text-message-renderer
  3201. {
  3202. pointer-events: none;
  3203. }
  3204. span#message.style-scope.yt-live-chat-text-message-renderer > img.emoji.yt-formatted-string.style-scope.yt-live-chat-text-message-renderer{
  3205. contain: layout paint style;
  3206. cursor: default;
  3207. pointer-events: none;
  3208. }
  3209. body yt-live-chat-app{
  3210. contain: size layout paint style;
  3211. content-visibility: auto;
  3212. transform: translate3d(0,0,0);
  3213. overflow: hidden;
  3214. }
  3215.  
  3216.  
  3217. /*
  3218. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer:nth-last-of-type(n+20){
  3219. content-visibility: auto;
  3220. }
  3221. */
  3222.  
  3223. /*
  3224. @supports (contain-intrinsic-size: auto 1px){
  3225.  
  3226. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer{
  3227. content-visibility: auto;
  3228. contain-intrinsic-size: auto 24px;
  3229. }
  3230.  
  3231. }
  3232. */
  3233. .style-scope.yt-live-chat-item-list-renderer{
  3234. box-sizing: border-box;
  3235. }
  3236.  
  3237. /*
  3238. .style-scope.yt-live-chat-item-list-renderer[style*="--tabview-crm-height"]{
  3239. content-visibility: auto;
  3240. contain-intrinsic-size: 1px var(--tabview-crm-height, 24px);
  3241. }
  3242.  
  3243. #item-offset.style-scope.yt-live-chat-item-list-renderer{
  3244. height: auto !important;
  3245. }
  3246. #item-offset.style-scope.yt-live-chat-item-list-renderer > #items:only-child{
  3247. position: relative !important;
  3248. }*/
  3249.  
  3250. #item-offset.style-scope.yt-live-chat-item-list-renderer{
  3251. contain: size layout paint style;
  3252. }
  3253. #item-offset.style-scope.yt-live-chat-item-list-renderer > #items:only-child{
  3254. contain: layout paint style;
  3255. }
  3256.  
  3257. `, cDoc.documentElement).id='userscript-tabview-chatroom-css'
  3258.  
  3259. let frc= 0;
  3260. let fullReady = ()=>{
  3261.  
  3262.  
  3263. if(!cDoc.documentElement.hasAttribute('style') && ++frc<900) return timeline.setTimeout(fullReady,10);
  3264.  
  3265. if (cDoc.querySelector('yt-live-chat-renderer #continuations')) {
  3266. timeline.setTimeout(() => mtf_ChatExist(), 40);
  3267. $(document.querySelector('ytd-live-chat-frame#chat')).attr('yt-userscript-iframe-loaded', '')
  3268. }
  3269.  
  3270. forceDisplayChatReplay();
  3271.  
  3272. let iframe = document.querySelector('ytd-live-chat-frame iframe#chatframe');
  3273.  
  3274.  
  3275. iframe.dispatchEvent(new CustomEvent("tabview-chatroom-ready"))
  3276.  
  3277.  
  3278.  
  3279. }
  3280. fullReady();
  3281.  
  3282.  
  3283.  
  3284. })
  3285.  
  3286. }
  3287.  
  3288. function flexyAttr_toggleFlag(mFlag, b, flag) {
  3289. if (b) mFlag = mFlag | flag;
  3290. else mFlag = mFlag & ~flag;
  3291. return mFlag;
  3292. }
  3293.  
  3294. function flexAttr_toLayoutStatus(nls, attributeName) {
  3295.  
  3296. let attrElm, b, v;
  3297. switch (attributeName) {
  3298. case 'theater':
  3299. nls = flexyAttr_toggleFlag(nls, isTheater(), LAYOUT_THEATER);
  3300. break;
  3301. case 'userscript-chat-collapsed':
  3302. case 'userscript-chatblock':
  3303. attrElm = kRef(ytdFlexy);
  3304. if (hasAttribute(attrElm, 'userscript-chat-collapsed')) {
  3305. nls = flexyAttr_toggleFlag(nls, true, LAYOUT_CHATROOM | LAYOUT_CHATROOM_COLLASPED);
  3306. } else {
  3307. nls = flexyAttr_toggleFlag(nls, hasAttribute(attrElm, 'userscript-chatblock'), LAYOUT_CHATROOM);
  3308. nls = flexyAttr_toggleFlag(nls, false, LAYOUT_CHATROOM_COLLASPED);
  3309. }
  3310. break;
  3311. case 'is-two-columns_':
  3312. nls = flexyAttr_toggleFlag(nls, isWideScreenWithTwoColumns(), LAYOUT_TWO_COLUMNS);
  3313. break;
  3314.  
  3315. case 'tabview-selection':
  3316. b = isNonEmptyString(kRef(ytdFlexy).getAttribute('tabview-selection'));
  3317. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_TAB_EXPANDED);
  3318. break;
  3319.  
  3320. case 'fullscreen':
  3321. b = isNonEmptyString(kRef(ytdFlexy).getAttribute('fullscreen'));
  3322. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_FULLSCREEN);
  3323. break;
  3324.  
  3325. case 'userscript-engagement-panel':
  3326. v = kRef(ytdFlexy).getAttribute('userscript-engagement-panel');
  3327. b = (+v > 0)
  3328. nls = flexyAttr_toggleFlag(nls, b, LAYOUT_ENGAGEMENT_PANEL_EXPAND);
  3329. break;
  3330.  
  3331. }
  3332.  
  3333. return nls;
  3334.  
  3335.  
  3336. }
  3337.  
  3338. let mtf_attrFlexy = (mutations, observer) => {
  3339.  
  3340. //attr mutation checker - $$ytdFlexyElm$$ {ytd-watch-flexy} \single
  3341. //::attr
  3342. // ~ 'userscript-chat-collapsed', 'userscript-chatblock', 'theater', 'is-two-columns_',
  3343. // ~ 'tabview-selection', 'fullscreen', 'userscript-engagement-panel',
  3344. // ~ 'hidden'
  3345.  
  3346. //console.log(15330, scriptEnable, kRef(ytdFlexy), mutations)
  3347.  
  3348. if (!scriptEnable) return;
  3349.  
  3350. const cssElm = kRef(ytdFlexy)
  3351. if (!cssElm) return;
  3352.  
  3353. if (!mutations) return;
  3354.  
  3355. //console.log(15340)
  3356. ytdFlexyHiddenCheck(mutations);
  3357.  
  3358. const old_layoutStatus = wls.layoutStatus
  3359. if (old_layoutStatus === null) return;
  3360. let new_layoutStatus = old_layoutStatus;
  3361.  
  3362. let checkedChat = false;
  3363.  
  3364. for (const mutation of mutations) {
  3365. new_layoutStatus = flexAttr_toLayoutStatus(new_layoutStatus, mutation.attributeName);
  3366. if (mutation.attributeName == 'userscript-chat-collapsed' || mutation.attributeName == 'userscript-chatblock') {
  3367.  
  3368. if(!checkedChat){
  3369. checkedChat = true; // avoid double call
  3370.  
  3371. if (cssElm.getAttribute('userscript-chatblock') === 'chat-live') {
  3372. // assigned new attribute - "chat-live" => disable comments section
  3373. _disableComments();
  3374. }
  3375.  
  3376. if (!cssElm.hasAttribute('userscript-chatblock')) {
  3377. // might or might not collapsed before
  3378. timeline.setTimeout(() => {
  3379. if (!scriptEnable) return;
  3380. //delayed call => check with the "no active focus" condition with chatroom status
  3381. if (!isAnyActiveTab() && !isChatExpand() && !isTheater() && isWideScreenWithTwoColumns() && !isFullScreen()) {
  3382. setToActiveTab();
  3383. }
  3384. }, 240);
  3385. }
  3386. }
  3387.  
  3388. }else if(mutation.attributeName == 'userscript-engagement-panel'){
  3389. // assume any other active component such as tab content and chatroom
  3390. if (+(cssElm.getAttribute('userscript-engagement-panel')||0)===0 && +mutation.oldValue>0) {
  3391. timeline.setTimeout(() => {
  3392. if (!scriptEnable) return;
  3393. //delayed call => check with the "no active focus" condition with engagement panel status
  3394. if (!isAnyActiveTab() && !isEngagementPanelExpanded() && !isTheater() && isWideScreenWithTwoColumns() && !isFullScreen() && !isChatExpand()) {
  3395. setToActiveTab();
  3396. }
  3397. }, 240);
  3398. }
  3399. }
  3400. }
  3401.  
  3402. if (new_layoutStatus !== old_layoutStatus) wls.layoutStatus = new_layoutStatus
  3403.  
  3404. }
  3405.  
  3406. const mtf_checkFlexy = () => {
  3407. // once per $$native-ytd-watch-flexy$$ {ytd-watch-flexy} detection
  3408.  
  3409. let ytdFlexyElm = kRef(ytdFlexy);
  3410. if (!scriptEnable || !ytdFlexyElm) return true;
  3411.  
  3412.  
  3413. wls.layoutStatus = null;
  3414.  
  3415. let isFlexyHidden = (deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden'));
  3416.  
  3417. if (!isFlexyHidden) {
  3418. let rChatExist = base_ChatExist();
  3419. if (rChatExist) {
  3420. let { attr_chatblock, attr_chatcollapsed } = rChatExist;
  3421. if (attr_chatblock === null) {
  3422. //remove attribute if it is unknown
  3423. attr_chatblock = false;
  3424. attr_chatcollapsed = false;
  3425. }
  3426. wAttr(ytdFlexyElm, 'userscript-chatblock', attr_chatblock)
  3427. wAttr(ytdFlexyElm, 'userscript-chat-collapsed', attr_chatcollapsed)
  3428. }
  3429. }
  3430.  
  3431. let rTabSelection = [...querySelectorAllFromAnchor.call(ytdFlexyElm,'.tab-btn[userscript-tab-content]')]
  3432. .map(elm => ({ elm, hidden: elm.classList.contains('tab-btn-hidden') }));
  3433.  
  3434. if(rTabSelection.length === 0){
  3435. wAttr(ytdFlexyElm, 'tabview-selection', false);
  3436. }else{
  3437. rTabSelection=rTabSelection.filter(entry => entry.hidden !== true); // all available tabs
  3438. if (rTabSelection.length === 0) wAttr(ytdFlexyElm, 'tabview-selection', '');
  3439. }
  3440. rTabSelection = null;
  3441. let rEP = engagement_panels_();
  3442. if (rEP && rEP.count > 0) wAttr(ytdFlexyElm, 'userscript-engagement-panel', false);
  3443. //else wAttr(ytdFlexyElm, 'userscript-engagement-panel', rEP.value + ""); // can be 0
  3444. else if(rEP.value>0) wAttr(ytdFlexyElm, 'userscript-engagement-panel', rEP.value + ""); // can be 0
  3445.  
  3446. let ls = 0;
  3447. ls = flexAttr_toLayoutStatus(ls, 'theater')
  3448. ls = flexAttr_toLayoutStatus(ls, 'userscript-chat-collapsed')
  3449. ls = flexAttr_toLayoutStatus(ls, 'userscript-chatblock')
  3450. ls = flexAttr_toLayoutStatus(ls, 'is-two-columns_')
  3451. ls = flexAttr_toLayoutStatus(ls, 'tabview-selection')
  3452. ls = flexAttr_toLayoutStatus(ls, 'fullscreen')
  3453. ls = flexAttr_toLayoutStatus(ls, 'userscript-engagement-panel')
  3454.  
  3455. wls.layoutStatus = ls
  3456.  
  3457. mtoFlexyAttr.bindElement(ytdFlexyElm,{
  3458. attributes: true,
  3459. attributeFilter: ['userscript-chat-collapsed', 'userscript-chatblock', 'theater', 'is-two-columns_', 'tabview-selection', 'fullscreen', 'userscript-engagement-panel', 'hidden'],
  3460. attributeOldValue: true
  3461. })
  3462.  
  3463. ytdFlexyHiddenCheckBasic(ytdFlexyElm);
  3464.  
  3465.  
  3466. let columns = document.querySelector('ytd-page-manager#page-manager #columns')
  3467. if (columns) {
  3468. wAttr(columns, 'userscript-scrollbar-render', true);
  3469. }
  3470.  
  3471. return false;
  3472. }
  3473.  
  3474. function ytdFlexyHiddenCheckBasic(ytdFlexyElm){
  3475. // for both hidden and non-hidden ytd-watch-flexy
  3476.  
  3477. deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden');
  3478.  
  3479. // console.log(15403)
  3480. document.documentElement.classList.toggle('tabview-normal-player',!deferredVarYTDHidden)
  3481.  
  3482. }
  3483.  
  3484. function checkVisibleEngagementPanel(){
  3485. if(storeLastPanel){
  3486.  
  3487. let elm_storeLastPanel = kRef(storeLastPanel);
  3488.  
  3489. if(elm_storeLastPanel && !isDOMVisible(elm_storeLastPanel) ){
  3490. storeLastPanel=null;
  3491. ytBtnCloseEngagementPanels();
  3492. }
  3493.  
  3494. }
  3495.  
  3496. }
  3497.  
  3498. function ytdFlexyHiddenCheck(mutations) {
  3499.  
  3500. //console.log(15350)
  3501.  
  3502. const ytdFlexyElm = kRef(ytdFlexy)
  3503. if (!ytdFlexyElm) return;
  3504. let muHidden = false
  3505.  
  3506. for (const mutation of mutations) {
  3507. if (mutation.attributeName === 'hidden') {
  3508. //console.log(343)
  3509. muHidden = true;
  3510. break;
  3511. }
  3512. }
  3513.  
  3514. if (!muHidden) return;
  3515.  
  3516. mtc_store= Date.now()+2870
  3517. //console.log(7004)
  3518. deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden');
  3519.  
  3520. if(deferredVarYTDHidden && scheduledCommentRefresh && Q.comments_section_loaded>0){
  3521. scheduledCommentRefresh=false;
  3522. }
  3523.  
  3524. //console.log(15400)
  3525. if(!deferredVarYTDHidden){
  3526. mtf_forceCheckLiveVideo_disable = 0
  3527. timeline.setTimeout(function() {
  3528. mtf_ChatExist();
  3529. layoutStatusMutex.lockWith(unlock=>{
  3530. atChange(); // in case no mutation occurance
  3531. ytdFlexyHiddenCheckBasic(ytdFlexyElm);
  3532. dispatchWindowResize(); // player control positioning
  3533. timeline.setTimeout(unlock, 40);
  3534. })
  3535. }, 40);
  3536. }else{
  3537. //console.log(15401)
  3538. timeline.setTimeout(function() {
  3539. //console.log(15402)
  3540. ytdFlexyHiddenCheckBasic(ytdFlexyElm);
  3541. }, 40);
  3542. }
  3543.  
  3544. }
  3545.  
  3546.  
  3547.  
  3548.  
  3549. let switchTabActivity_lastTab = null
  3550.  
  3551. function setDisplayedPlaylist() {
  3552. //override the default youtube coding event prevention
  3553. let cssElm = kRef(ytdFlexy);
  3554. if (!scriptEnable || !cssElm) return;
  3555. displayedPlaylist = mWeakRef(document.querySelector('ytd-watch-flexy #tab-list:not(.tab-content-hidden) ytd-playlist-panel-renderer') || null);
  3556. }
  3557.  
  3558.  
  3559. let recordScrollTop = 0
  3560.  
  3561. function switchTabActivity(activeLink) {
  3562. if (!scriptEnable) return;
  3563.  
  3564. const ytdFlexyElm = kRef(ytdFlexy);
  3565.  
  3566. if (!ytdFlexyElm) return;
  3567.  
  3568. if (activeLink && activeLink.classList.contains('tab-btn-hidden')) return; // not allow to switch to hide tab
  3569.  
  3570. if (isTheater() && isWideScreenWithTwoColumns()) activeLink = null;
  3571.  
  3572. /*
  3573. let isPrevTabComments = document.querySelector('.tab-content-cld:not(.tab-content-hidden)');
  3574. isPrevTabComments=isPrevTabComments&&isPrevTabComments.matches('#tab-comments')
  3575.  
  3576. if(isPrevTabComments){
  3577. let comments_tab = document.querySelector('#tab-comments');
  3578. if(comments_tab){
  3579. let st = comments_tab.scrollTop;
  3580. if(st>=0) recordScrollTop = st;
  3581. }
  3582.  
  3583.  
  3584. }
  3585. */
  3586.  
  3587. function runAtEnd() {
  3588.  
  3589. //console.log(12312)
  3590.  
  3591. if (activeLink) lastShowTab = activeLink.getAttribute('userscript-tab-content')
  3592.  
  3593. displayedPlaylist = null;
  3594. scrollingVideosList = null;
  3595.  
  3596. if (activeLink && lastShowTab == '#tab-list') {
  3597. setDisplayedPlaylist();
  3598. } else if (activeLink && lastShowTab == '#tab-videos') {
  3599. scrollingVideosList = mWeakRef(document.querySelector('ytd-watch-flexy #tab-videos:not(.tab-content-hidden) [placeholder-videos]'));
  3600. }
  3601.  
  3602.  
  3603. ytdFlexyElm.setAttribute('tabview-selection', activeLink ? lastShowTab : '')
  3604.  
  3605. if (lastShowTab == '#tab-comments' && (ytdFlexyElm.getAttribute('tabview-youtube-comments') || '').lastIndexOf('S') >= 0) {
  3606.  
  3607. if(mtf_forceCheckLiveVideo_disable===2) {}
  3608. else{
  3609. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'L');
  3610.  
  3611. /*
  3612. requestAnimationFrame(() => {
  3613. let comments_tab = document.querySelector('#tab-comments');
  3614. if (comments_tab && comments_tab.scrollTop > 0) comments_tab.scrollTop = 0;
  3615. });
  3616. */
  3617. }
  3618.  
  3619. }
  3620.  
  3621. /*
  3622. let isNewTabComments = document.querySelector('.tab-content-cld:not(.tab-content-hidden)')
  3623. isNewTabComments=isNewTabComments&&isNewTabComments.matches('#tab-comments')
  3624.  
  3625. if(isNewTabComments){
  3626. let comments_tab = document.querySelector('#tab-comments');
  3627. if(comments_tab){
  3628. let st = comments_tab.scrollTop;
  3629. if(Math.abs(st-recordScrollTop)>0.9) comments_tab.scrollTop=recordScrollTop;
  3630. }
  3631.  
  3632. }
  3633. */
  3634.  
  3635.  
  3636. }
  3637.  
  3638. const links = document.querySelectorAll('#material-tabs a[userscript-tab-content]');
  3639.  
  3640.  
  3641.  
  3642. for (const link of links) {
  3643. let content = document.querySelector(link.getAttribute('userscript-tab-content'));
  3644. if (link && content) {
  3645. if (link !== activeLink) {
  3646. link.classList.remove("active");
  3647. content.classList.add("tab-content-hidden");
  3648. } else {
  3649. link.classList.add("active");
  3650. content.classList.remove("tab-content-hidden");
  3651. //timeline.setTimeout(()=>content.focus(),400);
  3652.  
  3653. }
  3654. }
  3655. }
  3656.  
  3657. runAtEnd();
  3658.  
  3659.  
  3660. }
  3661.  
  3662.  
  3663. const STORE_VERSION = 1;
  3664. const STORE_key = 'userscript-tabview-settings';
  3665. function getStore(){
  3666. let s = localStorage[STORE_key];
  3667. function resetStore(){
  3668. let ret = {
  3669. version: 1,
  3670. };
  3671. localStorage[STORE_key]=JSON.stringify(ret);
  3672. return ret;
  3673. }
  3674. if(!s) return resetStore();
  3675. let obj = null;
  3676. try{
  3677. obj = JSON.parse(s);
  3678. }catch(e){}
  3679. return obj && obj.version === STORE_VERSION ? obj : resetStore();
  3680. }
  3681.  
  3682. function setStore(obj){
  3683. if(!obj || typeof obj !=='object') return false;
  3684. if(obj.version !== STORE_VERSION) return false;
  3685. localStorage[STORE_key]=JSON.stringify(obj);
  3686. return true;
  3687. }
  3688.  
  3689. let tabsUiScript_setclick = false;
  3690.  
  3691. function prepareTabBtn() {
  3692.  
  3693. const materialTab = document.querySelector("#material-tabs")
  3694. if (!materialTab) return;
  3695.  
  3696. let noActiveTab = !!document.querySelector('ytd-watch-flexy[userscript-chatblock]:not([userscript-chat-collapsed])')
  3697.  
  3698. const activeLink = querySelectorFromAnchor.call(materialTab,'a[userscript-tab-content].active:not(.tab-btn-hidden)')
  3699. if (activeLink) switchTabActivity(noActiveTab ? null : activeLink)
  3700.  
  3701. if (!tabsUiScript_setclick) {
  3702. tabsUiScript_setclick = true;
  3703. $(materialTab).on("click", "a", function(evt) {
  3704.  
  3705. //console.log(8510)
  3706. let ytdFlexyElm = kRef(ytdFlexy);
  3707. if (!scriptEnable || !ytdFlexyElm) return null;
  3708.  
  3709. if (!this.hasAttribute('userscript-tab-content')) return;
  3710.  
  3711. if (evt.target.matches('.font-size-btn')) return;
  3712.  
  3713.  
  3714. evt.preventDefault();
  3715.  
  3716. //console.log(8511)
  3717.  
  3718. /*
  3719. if (this.getAttribute('userscript-tab-content') == '#tab-comments' && parseInt(ytdFlexyElm.getAttribute('tabview-youtube-comments') || '') < 0) {
  3720. console.log(8512)
  3721. return;
  3722. }*/
  3723.  
  3724. //console.log(8513)
  3725. new Promise(requestAnimationFrame).then(() => {
  3726.  
  3727.  
  3728. //console.log(8514)
  3729. layoutStatusMutex.lockWith(unlock => {
  3730.  
  3731. //console.log(8515)
  3732. switchTabActivity_lastTab = this.getAttribute('userscript-tab-content');
  3733.  
  3734. let isActiveAndVisible = this.classList.contains('tab-btn') && this.classList.contains('active') && !this.classList.contains('tab-btn-hidden')
  3735.  
  3736. if (isWideScreenWithTwoColumns() && !isTheater() && isActiveAndVisible) {
  3737. //optional
  3738. timeline.setTimeout(unlock, 80);
  3739. switchTabActivity(null);
  3740. ytBtnSetTheater();
  3741. } else if (isActiveAndVisible) {
  3742. timeline.setTimeout(unlock, 80);
  3743. switchTabActivity(null);
  3744. } else {
  3745. let pInterval = 60;
  3746. if (isChatExpand() && isWideScreenWithTwoColumns()) {
  3747. ytBtnCollapseChat();
  3748. } else if (isEngagementPanelExpanded() && isWideScreenWithTwoColumns()) {
  3749. ytBtnCloseEngagementPanels();
  3750. } else if (isWideScreenWithTwoColumns() && isTheater() && !isFullScreen()) {
  3751. ytBtnCancelTheater();
  3752. } else {
  3753. pInterval = 20;
  3754. }
  3755. //console.log(8518)
  3756. timeline.setTimeout(() => {
  3757. timeline.setTimeout(makeBodyScroll, 20); // this is to make the image render
  3758.  
  3759. timeline.setTimeout(() => {
  3760. let rightTabs = document.querySelector('#right-tabs');
  3761. if (!isWideScreenWithTwoColumns() && rightTabs && rightTabs.offsetTop > 0 && this.classList.contains('active')) {
  3762. let tabButtonBar = document.querySelector('#material-tabs');
  3763. let tabButtonBarHeight = tabButtonBar ? tabButtonBar.offsetHeight : 0;
  3764. window.scrollTo(0, rightTabs.offsetTop - tabButtonBarHeight);
  3765. }
  3766. }, 60)
  3767. // console.log(8519)
  3768.  
  3769. timeline.setTimeout(unlock, 80)
  3770. switchTabActivity(this)
  3771.  
  3772. }, pInterval);
  3773. }
  3774.  
  3775.  
  3776. })
  3777.  
  3778. })
  3779.  
  3780.  
  3781.  
  3782.  
  3783. });
  3784. /*
  3785.  
  3786. $(materialTab).on("mousedown", ".font-size-btn", function(evt){
  3787.  
  3788. evt.stopPropagation();
  3789. evt.stopImmediatePropagation();
  3790.  
  3791. });
  3792.  
  3793. $(materialTab).on("pointerdown", ".font-size-btn", function(evt){
  3794.  
  3795. evt.stopPropagation();
  3796. evt.stopImmediatePropagation();
  3797.  
  3798. });
  3799. $(materialTab).on("mouseup", ".font-size-btn", function(evt){
  3800.  
  3801. evt.stopPropagation();
  3802. evt.stopImmediatePropagation();
  3803.  
  3804. });
  3805.  
  3806. $(materialTab).on("pointerup", ".font-size-btn", function(evt){
  3807.  
  3808. evt.stopPropagation();
  3809. evt.stopImmediatePropagation();
  3810.  
  3811. });
  3812. */
  3813.  
  3814. function updateCSS_fontsize(){
  3815.  
  3816. let store = getStore();
  3817. let ytdFlexyElm = kRef(ytdFlexy);
  3818. if(ytdFlexyElm){
  3819. if(store['font-size-#tab-info'])
  3820. ytdFlexyElm.style.setProperty('--ut2257-info', store['font-size-#tab-info'])
  3821. if(store['font-size-#tab-comments'])
  3822. ytdFlexyElm.style.setProperty('--ut2257-comments', store['font-size-#tab-comments'])
  3823. if(store['font-size-#tab-videos'])
  3824. ytdFlexyElm.style.setProperty('--ut2257-videos', store['font-size-#tab-videos'])
  3825. if(store['font-size-#tab-list'])
  3826. ytdFlexyElm.style.setProperty('--ut2257-list', store['font-size-#tab-list'])
  3827. }
  3828.  
  3829. }
  3830.  
  3831. $(materialTab).on("click", ".font-size-btn", function(evt){
  3832.  
  3833. evt.preventDefault();
  3834. evt.stopPropagation();
  3835. evt.stopImmediatePropagation();
  3836.  
  3837. let value = evt.target.matches('.font-size-plus')?1: evt.target.matches('.font-size-minus')?-1 :0;
  3838.  
  3839. let active_tab_content = closestDOM.call(evt.target,'[userscript-tab-content]').getAttribute('userscript-tab-content');
  3840.  
  3841. let store = getStore();
  3842. let settingKey = `font-size-${active_tab_content}`
  3843. if(!store[settingKey]) store[settingKey] = 1.0;
  3844. if(value<0) store[settingKey] -= 0.05;
  3845. else if(value>0) store[settingKey] += 0.05;
  3846. if(store[settingKey]<0.1) store[settingKey] = 0.1;
  3847. else if(store[settingKey]>10) store[settingKey] = 10.0;
  3848. setStore(store);
  3849.  
  3850.  
  3851. updateCSS_fontsize();
  3852.  
  3853.  
  3854. //console.log(this.textContent)
  3855.  
  3856.  
  3857. });
  3858.  
  3859. updateCSS_fontsize();
  3860.  
  3861.  
  3862.  
  3863. }
  3864.  
  3865. }
  3866.  
  3867.  
  3868. // ---------------------------------------------------------------------------------------------
  3869. document.addEventListener("yt-navigate-finish", onNavigationEnd)
  3870. //yt-navigate-redirect
  3871. //"yt-page-data-fetched"
  3872. //yt-navigate-error
  3873. //yt-navigate-start
  3874. //yt-page-manager-navigate-start
  3875. //"yt-navigate"
  3876. //"yt-navigate-cache
  3877.  
  3878. document.addEventListener("yt-navigate-cache",()=>{
  3879. console.log('yt-navigate-cache')
  3880. })
  3881. document.addEventListener("yt-navigate-redirect",()=>{
  3882. console.log('yt-navigate-redirect')
  3883. })
  3884.  
  3885. function onReady(){
  3886. //might be earlier than yt-navigation-finish
  3887. console.log('html-onReady')
  3888. if(location.pathname=='/watch') script_inject_js1.inject();
  3889. }
  3890.  
  3891. if(document.readyState!=='loading'){
  3892. onReady();
  3893. }else{
  3894. document.addEventListener('DOMContentLoaded', onReady)
  3895. }
  3896.  
  3897. function forceConfig(){
  3898. let trial = false;
  3899. /*
  3900. let f=()=>{
  3901. if(trial) return;
  3902. let b = true;
  3903. try{
  3904. document.dispatchEvent(new CustomEvent("me-func"))
  3905. window.yt.config_.EXPERIMENT_FLAGS.kevlar_watch_metadata_refresh=true
  3906. }catch(e){
  3907. b=false;
  3908. }
  3909. if(b) trial = true;
  3910. }
  3911. f();
  3912. requestAnimationFrame(f)
  3913. setTimeout(f,30)
  3914. setTimeout(f,300)
  3915. */
  3916. }
  3917.  
  3918. document.addEventListener("yt-navigate-start",()=>{
  3919. console.log('yt-navigate-start') // not always trigger before navigate-end
  3920. no_fix_contents_until = 0;
  3921. no_fix_playlist_until = 0;
  3922.  
  3923. script_inject_js1.inject();
  3924. forceConfig();
  3925. })
  3926.  
  3927. document.addEventListener("yt-page-manager-navigate-start",()=>{
  3928. console.log('yt-page-manager-navigate-start')
  3929. forceConfig();
  3930. })
  3931.  
  3932.  
  3933. document.addEventListener("loadstart", (evt) => {
  3934. if (!evt || !evt.target || evt.target.nodeName !== "VIDEO") return;
  3935. let elm = evt.target;
  3936. if (!elm.matches('#player video, #movie_player video, video[tabview-mainvideo]')) return;
  3937.  
  3938. mtc_store= Date.now()+2870
  3939.  
  3940. let src = elm.src;
  3941. if (src !== lastVideoURL) {
  3942. lastVideoURL = elm.src;
  3943. elm.setAttribute('tabview-mainvideo', ''); // mainly for mini playing
  3944. no_fix_contents_until = 0;
  3945. no_fix_playlist_until = 0;
  3946. regularCheck(1,0,null); // mutation happens when the page is not ready; call again as the page is ready.
  3947.  
  3948. }
  3949.  
  3950. }, true)
  3951.  
  3952. // ---------------------------------------------------------------------------------------------
  3953.  
  3954. let scrolling_lastD = 0;
  3955.  
  3956. const singleColumnScrolling = function(/** @type {boolean} */ scrolling_lastF) {
  3957. if (!scriptEnable || deferredVarYTDHidden) return;
  3958.  
  3959. let pageY = scrollY;
  3960. if (pageY < 10 && scrolling_lastD === 0 && !scrolling_lastF) return;
  3961.  
  3962. let targetElm, header, navElm;
  3963.  
  3964. Promise.resolve().then(() => {
  3965.  
  3966. targetElm = document.querySelector("#right-tabs");
  3967. if (!targetElm) return;
  3968. header = querySelectorFromAnchor.call(targetElm,"header");
  3969. if (!header) return;
  3970. navElm = document.querySelector('#masthead-container, #masthead')
  3971. if (!navElm) return;
  3972. let navHeight = navElm ? navElm.offsetHeight : 0
  3973.  
  3974. let elmY = targetElm.offsetTop
  3975.  
  3976. let xyz = [elmY + navHeight, pageY, elmY - navHeight]
  3977.  
  3978. let xyStatus = 0
  3979. if (xyz[1] < xyz[2] && xyz[2] < xyz[0]) {
  3980. // 1
  3981. xyStatus = 1
  3982. }
  3983.  
  3984. if (xyz[0] > xyz[1] && xyz[1] > xyz[2]) {
  3985.  
  3986. //2
  3987. xyStatus = 2
  3988.  
  3989. }
  3990.  
  3991. if (xyz[2] < xyz[0] && xyz[0] < xyz[1]) {
  3992. // 3
  3993.  
  3994. xyStatus = 3
  3995.  
  3996.  
  3997. }
  3998.  
  3999. return xyStatus;
  4000.  
  4001. }).then((xyStatus) => {
  4002.  
  4003. if ((xyStatus == 2 || xyStatus == 3) && (scrolling_lastD === 0 || scrolling_lastF)) {
  4004. scrolling_lastD = 1;
  4005. let {
  4006. offsetHeight
  4007. } = header
  4008. let {
  4009. offsetWidth
  4010. } = targetElm
  4011.  
  4012. targetElm.style.setProperty("--userscript-sticky-width", offsetWidth + 'px')
  4013. targetElm.style.setProperty("--userscript-sticky", offsetHeight + 'px')
  4014.  
  4015. wAttr(targetElm, 'userscript-sticky', true);
  4016.  
  4017. } else if ((xyStatus == 1) && (scrolling_lastD === 1 || scrolling_lastF)) {
  4018. scrolling_lastD = 0;
  4019.  
  4020. wAttr(targetElm, 'userscript-sticky', false);
  4021. }
  4022.  
  4023.  
  4024. targetElm = null;
  4025. header = null;
  4026. navElm = null;
  4027.  
  4028. });
  4029.  
  4030. };
  4031.  
  4032. window.addEventListener("scroll", function() {
  4033. singleColumnScrolling(false)
  4034. }, {
  4035. capture: false,
  4036. passive: true
  4037. })
  4038.  
  4039. let lastResizeAt = 0;
  4040. window.addEventListener('resize', function() {
  4041.  
  4042. if (!scriptEnable) return;
  4043. if (deferredVarYTDHidden) return;
  4044. lastResizeAt = Date.now();
  4045.  
  4046. requestAnimationFrame(() => {
  4047. singleColumnScrolling(true)
  4048. })
  4049.  
  4050. }, {
  4051. capture: false,
  4052. passive: true
  4053. })
  4054.  
  4055.  
  4056.  
  4057. let hist = null
  4058. const getHistState = (history)=>`${history.length}|${history.state?history.state.entryTime:null}`;
  4059. function newVideoPageCheck(){
  4060. let hState = getHistState(history)
  4061. if(hist!==hState) {
  4062. hist=hState;
  4063. if(scriptEnable){
  4064. //scriptEnable = false;
  4065. let callTimeout = !newVideoPage.entryTime
  4066. newVideoPage.entryTime = 1
  4067. if(callTimeout) setTimeout(newVideoPage,0)
  4068. }
  4069. return true;
  4070. }
  4071. }
  4072. function newVideoPage(){
  4073. newVideoPage.entryTime = 0;
  4074.  
  4075. console.log('newVideoPage')
  4076. //console.log('newVideoPage-', 150, location.href)
  4077.  
  4078. let ytdFlexyElm = kRef(ytdFlexy);
  4079. if(!ytdFlexyElm) return;
  4080.  
  4081. timeline.reset();
  4082. layoutStatusMutex = new Mutex();
  4083.  
  4084. //console.log('newVideoPage-', 350, location.href)
  4085. let flag1= /^https?\:\/\/(\w+\.)*youtube\.com\/watch\?(\w+\=[^\/\?\&]+\&|\w+\=?\&)*v=[\w\-\_]+/.test(location.href)
  4086. let tf = ()=>{
  4087.  
  4088. let isFlexyHidden = (deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden'));
  4089.  
  4090. let flag2 = !isFlexyHidden;
  4091.  
  4092. if(flag1^flag2) return timeline.setTimeout(tf,7); else funcVisibleWatch();
  4093.  
  4094. tf= null;
  4095. funcVisibleWatch = null;
  4096. ytdFlexyElm=null
  4097.  
  4098. }
  4099.  
  4100. let funcVisibleWatch = ()=>{
  4101. //scriptEnable = true;
  4102.  
  4103. let isFlexyHidden = (deferredVarYTDHidden = ytdFlexyElm.hasAttribute('hidden'));
  4104. ytdFlexyHiddenCheckBasic(ytdFlexyElm)
  4105.  
  4106. if(!isFlexyHidden) {
  4107.  
  4108. mtf_forceCheckLiveVideo_disable = 0;
  4109. mtc_store= Date.now()+2870
  4110.  
  4111. sect_lastUpdate = 0;
  4112. if(pendingOne){
  4113. // reset pendingOne = false if the element is already removed.
  4114. pendingOne = document.querySelectorAll(`ytd-watch-flexy ytd-comments#comments [tabview-cache-time]`).length>1;
  4115. }
  4116.  
  4117. timeline.setTimeout(()=>{
  4118. Q.mutationTarget=null;
  4119. FP.mtf_attrComments()
  4120. },2870)
  4121. if(pageInit_attrComments) hookSection();
  4122.  
  4123.  
  4124.  
  4125.  
  4126.  
  4127. let new_layoutStatus = wls.layoutStatus
  4128.  
  4129. const new_isExpandedChat = !(new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  4130. const new_isCollaspedChat = (new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  4131. const new_isTwoColumns = new_layoutStatus & LAYOUT_TWO_COLUMNS;
  4132. const new_isTheater = new_layoutStatus & LAYOUT_THEATER;
  4133. const new_isTabExpanded = new_layoutStatus & LAYOUT_TAB_EXPANDED;
  4134. const new_isFullScreen = new_layoutStatus & LAYOUT_FULLSCREEN;
  4135. const new_isExpandEPanel = new_layoutStatus & LAYOUT_ENGAGEMENT_PANEL_EXPAND;
  4136. if( ytdFlexyElm.getAttribute('tabview-selection')==='' && new_isTwoColumns && !new_isTheater && !new_isTabExpanded && !new_isFullScreen && !new_isExpandEPanel && !new_isExpandedChat ){
  4137. // e.g. engage panel removed after miniview and change video
  4138. setToActiveTab();
  4139. }else if(new_isExpandEPanel && querySelectorAllFromAnchor.call(ytdFlexyElm,'ytd-engagement-panel-section-list-renderer[visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"]').length===0){
  4140. wls.layoutStatus = new_layoutStatus & (~LAYOUT_ENGAGEMENT_PANEL_EXPAND)
  4141. }
  4142.  
  4143. //mtf_attrFlexy();
  4144.  
  4145. FP.mtf_attrEngagementPanel();
  4146. FP.mtf_attrPlaylist();
  4147. FP.mtf_attrComments();
  4148. FP.mtf_attrChatroom();
  4149.  
  4150.  
  4151. }
  4152.  
  4153. no_fix_contents_until = 0;
  4154. no_fix_playlist_until = 0;
  4155. scriptEnable = true;
  4156. regularCheck(1,0,null); // mutation happens when the page is not ready; call again as the page is ready.
  4157.  
  4158.  
  4159.  
  4160.  
  4161. }
  4162.  
  4163. tf();
  4164.  
  4165.  
  4166. }
  4167.  
  4168.  
  4169.  
  4170. function browserHistoryState(){
  4171. let maxCount = 5
  4172.  
  4173. if (!scriptEnable) return;
  4174. let ytdFlexyElm = kRef(ytdFlexy);
  4175. if(!ytdFlexyElm) return;
  4176.  
  4177. let cid = timeline.setInterval(function(){
  4178. if(newVideoPageCheck()){
  4179. timeline.clearInterval(cid);
  4180. }
  4181. if(--maxCount===0) timeline.clearInterval(cid);
  4182. },7)
  4183.  
  4184. }
  4185.  
  4186.  
  4187. window.addEventListener('hashchange', function() {
  4188. if (!scriptEnable) return;
  4189. console.log('hashchange');
  4190. browserHistoryState();
  4191. }, { capture: true })
  4192.  
  4193. window.addEventListener('popstate', function() {
  4194. if (!scriptEnable) return;
  4195. console.log('popstate');
  4196. browserHistoryState();
  4197. }, { capture: true })
  4198.  
  4199.  
  4200. // function clearMutationObserver(o, key) {
  4201. // if (o[key]) {
  4202. // o[key].takeRecords();
  4203. // o[key].disconnect();
  4204. // o[key] = null;
  4205. // return true;
  4206. // }
  4207. // }
  4208.  
  4209. // function initMutationObserver(o, key, callback) {
  4210. // clearMutationObserver(o, key);
  4211. // const mto = new MutationObserver(callback);
  4212. // o[key] = mto;
  4213. // return mto;
  4214. // }
  4215. // function initMutationObserver2(o, key, mtoFunc) {
  4216. // clearMutationObserver(o, key);
  4217. // const mto = mtoFunc();
  4218. // o[key] = mto;
  4219. // return mto;
  4220. // }
  4221.  
  4222. document.addEventListener('wheel', function(evt) {
  4223.  
  4224. if (!scriptEnable) return;
  4225. const displayedPlaylist_element = kRef(displayedPlaylist);
  4226. if (displayedPlaylist_element && displayedPlaylist_element.contains(evt.target)) {
  4227. evt.stopPropagation();
  4228. evt.stopImmediatePropagation();
  4229. }
  4230. }, { capture: true, passive: true });
  4231.  
  4232.  
  4233. function setVideosTwoColumns(/** @type {number} */ flag, /** @type {boolean} */ bool) {
  4234.  
  4235. //two columns to one column
  4236.  
  4237. /*
  4238. [placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy
  4239.  
  4240. is-two-columns ="" => no is-two-columns
  4241. [placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer
  4242. no hidden => hidden =""
  4243. [placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer
  4244. hidden ="" => no hidden
  4245.  
  4246. */
  4247.  
  4248. let cssSelector1 = '[placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy'
  4249.  
  4250. let cssSelector2 = '[placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer'
  4251.  
  4252. let cssSelector3 = '[placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer'
  4253.  
  4254. let res = {}
  4255. if (flag & 1) {
  4256. res.m1 = document.querySelector(cssSelector1)
  4257. if (res.m1) wAttr(res.m1, 'is-two-columns', bool ? '' : false);
  4258. }
  4259.  
  4260. if (flag & 2) {
  4261. res.m2 = document.querySelector(cssSelector2)
  4262. if (res.m2) wAttr(res.m2, 'hidden', bool ? false : '');
  4263. }
  4264.  
  4265. if (flag & 4) {
  4266. res.m3 = document.querySelector(cssSelector3)
  4267. if (res.m3) wAttr(res.m3, 'hidden', bool ? '' : false);
  4268. }
  4269.  
  4270.  
  4271. return res
  4272.  
  4273.  
  4274.  
  4275.  
  4276. }
  4277.  
  4278. let lastScrollFetch = 0;
  4279. // function isScrolledToEnd(){
  4280. // return (window.innerHeight + window.pageYOffset) >= document.scrollingElement.scrollHeight - 2;
  4281. // }
  4282. let lastOffsetTop = 0;
  4283. window.addEventListener('scroll', function(evt) {
  4284.  
  4285. //console.log(evt.target)
  4286.  
  4287. if (!scriptEnable) return;
  4288.  
  4289.  
  4290. if (!kRef(scrollingVideosList)) return;
  4291. if (videoListBeforeSearch) return;
  4292.  
  4293.  
  4294.  
  4295. let visibleHeight = document.scrollingElement.clientHeight;
  4296. let totalHeight = document.scrollingElement.scrollHeight;
  4297.  
  4298. if (totalHeight < visibleHeight * 1.5) return; // filter out two column view;
  4299.  
  4300. let z = window.pageYOffset + visibleHeight;
  4301. let h_advanced = totalHeight - (visibleHeight > 5 * 40 ? visibleHeight * 0.5 : 40);
  4302.  
  4303.  
  4304.  
  4305. if (z > h_advanced && !isWideScreenWithTwoColumns()) {
  4306.  
  4307. let ct = Date.now();
  4308. if (ct - lastScrollFetch < 500) return; //prevent continuous calling
  4309.  
  4310. lastScrollFetch = ct;
  4311.  
  4312. let res = setVideosTwoColumns(2 | 4, true)
  4313. if (res.m3 && res.m2) {
  4314.  
  4315. //wait for DOM change, just in case
  4316. requestAnimationFrame(() => {
  4317. let { offsetTop } = res.m2 // as visibility of m2 & m3 switched.
  4318.  
  4319. if (offsetTop - lastOffsetTop < 40) return; // in case bug, or repeating calling. // the next button shall below the this button
  4320. lastOffsetTop = offsetTop
  4321.  
  4322. res.m2.parentNode.dispatchEvent(new Event('yt-service-request-sent-button-renderer'))
  4323.  
  4324. res = null
  4325. })
  4326.  
  4327. } else {
  4328.  
  4329. res = null
  4330. }
  4331.  
  4332.  
  4333. }
  4334.  
  4335.  
  4336.  
  4337.  
  4338. }, { passive: true })
  4339.  
  4340. let sect_lastUpdate = 0;
  4341.  
  4342. let sect_holder = null;
  4343. let sect_hText = null;
  4344. let sect_hTime = 0;
  4345.  
  4346. let pendingOne = false;
  4347. let mtf_forceCheckLiveVideo_disable = 0;
  4348.  
  4349. let storeLastPanel = null;
  4350.  
  4351. /** @type {boolean | null} */
  4352. let deferredVarYTDHidden = null;
  4353. let scheduledCommentRefresh = false;
  4354.  
  4355. let pageInit_attrComments = false;
  4356.  
  4357.  
  4358.  
  4359. let mgChatFrame = {
  4360. setVar(elm) {
  4361. mgChatFrame.kVar = mWeakRef(elm)
  4362. },
  4363. getVar() {
  4364. return kRef(mgChatFrame.kVar)
  4365. },
  4366. inPage() {
  4367. let elm = mgChatFrame.getVar();
  4368. if (!elm) return false;
  4369. let ytdFlexyElm = kRef(ytdFlexy);
  4370. if(!ytdFlexyElm) return false;
  4371. return ytdFlexyElm.contains(elm)
  4372. }
  4373. };
  4374.  
  4375. const timeline = {
  4376. // after initialized (initObserver)
  4377. cn1:{},
  4378. cn2:{},
  4379. setTimeout( /** @type {TimerHandler} */ f,/** @type {number} */ d){
  4380. return timeline.cn1[setTimeout(f,d)]=true
  4381. },
  4382. clearTimeout(/** @type {number} */ cid){
  4383. timeline.cn1[cid]=false; return clearTimeout(cid)
  4384. },
  4385. setInterval(/** @type {TimerHandler} */ f,/** @type {number} */ d){
  4386. return timeline.cn2[setInterval(f,d)]=true
  4387. },
  4388. clearInterval(/** @type {number} */ cid){
  4389. timeline.cn2[cid]=false; return clearInterval(cid)
  4390. },
  4391. reset(){
  4392. for(let cid in timeline.cn1) timeline.cn1[cid] && clearTimeout(cid)
  4393. for(let cid in timeline.cn2) timeline.cn2[cid] && clearInterval(cid)
  4394. timeline.cn1={}
  4395. timeline.cn2={}
  4396. }
  4397. }
  4398.  
  4399. class AttributeMutationObserver extends MutationObserver {
  4400. constructor(flist){
  4401. super((mutations, observer)=>{
  4402. for(const mutation of mutations){
  4403. if (mutation.type === 'attributes') {
  4404. this.checker(mutation.target, mutation.attributeName)
  4405. }
  4406. }
  4407. })
  4408. this.flist=flist;
  4409. this.res={}
  4410. }
  4411. takeRecords(){
  4412. super.takeRecords();
  4413. }
  4414. disconnect(){
  4415. this._target = null;
  4416. super.disconnect();
  4417. }
  4418. observe(/** @type {Node} */ target){
  4419. if(this._target) return;
  4420. this._target = mWeakRef(target);
  4421. const options = {
  4422. attributes: true,
  4423. attributeFilter: Object.keys(this.flist),
  4424. //attributeFilter: [ "status", "username" ],
  4425. attributeOldValue: true
  4426. }
  4427. super.observe(target, options)
  4428. }
  4429. checker(/** @type {Node} */ target,/** @type {string} */ attributeName){
  4430. let nv = target.getAttribute(attributeName);
  4431. if(this.res[attributeName]!==nv){
  4432. this.res[attributeName] = nv
  4433. let f = this.flist[attributeName];
  4434. if(f) f(attributeName, nv);
  4435.  
  4436. }
  4437. }
  4438. check(delay = 0){
  4439. setTimeout(()=>{
  4440. let target = kRef(this._target)
  4441. for(const key of Object.keys(this.flist)){
  4442. this.checker(target,key)
  4443. }
  4444. target = null;
  4445. },delay)
  4446. }
  4447. }
  4448.  
  4449. function goYoutubeGeniusLyrics(){
  4450.  
  4451. setTimeout(function $f(){
  4452.  
  4453. if(!document.documentElement.hasAttribute('w-engagement-panel-genius-lyrics')) return setTimeout($f,100)
  4454.  
  4455. document.documentElement.dispatchEvent(new CustomEvent('engagement-panel-genius-lyrics'))
  4456.  
  4457.  
  4458. },100)
  4459.  
  4460.  
  4461.  
  4462. }
  4463.  
  4464.  
  4465. /*
  4466.  
  4467. To be implement: timeline
  4468.  
  4469. timeline.setTimeout
  4470. timeline.clearTimeout
  4471. timeline.setInterval
  4472. timeline.clearInterval
  4473.  
  4474. */
  4475.  
  4476.  
  4477.  
  4478. //Object.keys($0).filter(key=>!(key in $0.constructor.prototype))
  4479.  
  4480. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML'))
  4481. //Object.getOwnPropertyNames(window).filter(k=>k.startsWith('HTML')).filter(k=>$0 instanceof window[k])
  4482.  
  4483.  
  4484. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  4485.  
  4486. /*
  4487. fix bug for comment section - version 1.8.7
  4488. This issue is the bug in browser's rendering
  4489. I guess, this is due to the lines clamp with display:-webkit-box
  4490. use stupid coding to let it re-render when its content become visible
  4491. /*
  4492.  
  4493. ytd-expander[should-use-number-of-lines][collapsed] > #content.ytd-expander {
  4494. color: var(--yt-spec-text-primary);
  4495. display: -webkit-box;
  4496. overflow: hidden;
  4497. max-height: none;
  4498. -webkit-box-orient: vertical;
  4499. -webkit-line-clamp: var(--ytd-expander-max-lines, 4);
  4500. }
  4501.  
  4502. // v1.8.36 imposed a effective solution for fixing this bug
  4503.  
  4504. */
  4505.  
  4506. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  4507.  
  4508.  
  4509. /**
  4510. *
  4511.  
  4512.  
  4513. f.initChildrenObserver=function(){var a=this;this.observer=new MutationObserver(function(){return a.childrenChanged()});
  4514. this.observer.observe(this.$.content,{subtree:!0,childList:!0,attributes:!0});this.childrenChanged()};
  4515. 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()})}))};
  4516.  
  4517.  
  4518. f.onIronResize=function(){this.recomputeOnResize&&this.childrenChanged()};
  4519.  
  4520.  
  4521. onButtonClick_:function(){this.fire("yt-close-upsell-dialog")},
  4522. 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};
  4523. n(xI,L);f=xI.prototype;f.alwaysToggleableChanged=function(){this.alwaysToggleable&&(this.canToggle=!0)};
  4524.  
  4525.  
  4526. f.calculateCanCollapse=function(){this.canToggle=this.shouldUseNumberOfLines?this.alwaysToggleable||this.$.content.offsetHeight<this.$.content.scrollHeight:this.alwaysToggleable||this.$.content.scrollHeight>this.collapsedHeight};
  4527. f.detachObserver=function(){this.observer&&this.observer.disconnect()};
  4528.  
  4529. *
  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. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  4581.  
  4582. }
  4583.  
  4584.  
  4585. ;!(function $$() {
  4586. 'use strict';
  4587.  
  4588. if(document.documentElement==null) return window.requestAnimationFrame($$)
  4589.  
  4590. const cssTxt = GM_getResourceText("contentCSS");
  4591.  
  4592. function addStyle (styleText) {
  4593. const styleNode = document.createElement('style');
  4594. styleNode.type = 'text/css';
  4595. styleNode.textContent = styleText;
  4596. document.documentElement.appendChild(styleNode);
  4597. return styleNode;
  4598. }
  4599.  
  4600. addStyle (cssTxt);
  4601.  
  4602. main(window.$);
  4603.  
  4604.  
  4605. // Your code here...
  4606. })();