Tabview Youtube

Make comments and lists into tabs

当前为 2022-04-29 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Tabview Youtube
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.8.46
  5. // @description Make comments and lists into tabs
  6. // @author CY Fung
  7. // @match https://www.youtube.com/*
  8. // @resource contentCSS https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube/3fde26368c782c0abb35e0bbdb0e37529b26125e/css/style_content.css
  9. // @icon https://github.com/cyfung1031/Tabview-Youtube/raw/main/images/icon128p.png
  10. // @require https://cdnjs.cloudflare.com/ajax/libs/cash/8.1.0/cash.min.js
  11. // @grant GM_getResourceText
  12. // @run-at document-start
  13. // @license MIT https://github.com/cyfung1031/Tabview-Youtube/blob/main/LICENSE
  14. // @noframes
  15. // ==/UserScript==
  16.  
  17. /* jshint esversion:6 */
  18.  
  19. function main($){
  20. // MIT License
  21. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46. -(function() {
  47.  
  48. function inIframe() {
  49. try {
  50. return window.self !== window.top;
  51. } catch (e) {
  52. return true;
  53. }
  54. }
  55.  
  56. if (inIframe()) return;
  57.  
  58. if (!$) return;
  59.  
  60. /**
  61. * SVG resources:
  62. * <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>
  63. */
  64.  
  65. const scriptVersionForExternal = '2021/07/03';
  66.  
  67. const githubURLBase = "https://raw.githubusercontent.com/cyfung1031/Tabview-Youtube";
  68. const githubURLCommit = "bdf401045266e5224663f80b276bc7f56d122b8d";
  69.  
  70. const isMyScriptInChromeRuntime = () => typeof ((((window||0).chrome||0).runtime||0).getURL) == 'function'
  71.  
  72.  
  73. const svgComments = `
  74. <path d="M40.068,13.465L5.93,13.535c-3.27,0-5.93,2.66-5.93,5.93v21.141c0,3.27,2.66,5.929,5.93,5.929H12v10
  75. c0,0.413,0.254,0.784,0.64,0.933c0.117,0.045,0.239,0.067,0.36,0.067c0.276,0,0.547-0.115,0.74-0.327l9.704-10.675l16.626-0.068
  76. c3.27,0,5.93-2.66,5.93-5.929V19.395C46,16.125,43.34,13.465,40.068,13.465z M10,23.465h13c0.553,0,1,0.448,1,1s-0.447,1-1,1H10
  77. c-0.553,0-1-0.448-1-1S9.447,23.465,10,23.465z M36,37.465H10c-0.553,0-1-0.448-1-1s0.447-1,1-1h26c0.553,0,1,0.448,1,1
  78. S36.553,37.465,36,37.465z M36,31.465H10c-0.553,0-1-0.448-1-1s0.447-1,1-1h26c0.553,0,1,0.448,1,1S36.553,31.465,36,31.465z"/>
  79. <path d="M54.072,2.535L19.93,2.465c-3.27,0-5.93,2.66-5.93,5.93v3.124l26.064-0.054c4.377,0,7.936,3.557,7.936,7.93v21.07v0.071
  80. v2.087l3.26,3.586c0.193,0.212,0.464,0.327,0.74,0.327c0.121,0,0.243-0.022,0.36-0.067c0.386-0.149,0.64-0.52,0.64-0.933v-10h1.07
  81. c3.27,0,5.93-2.66,5.93-5.929V8.465C60,5.195,57.34,2.535,54.072,2.535z"/>
  82. `.trim();
  83.  
  84. 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,24h250c13.255,0,24-10.745,24-24V33
  85. z M91,39h43v34H91V39z M61,259H30v-34h31V259z M61,73H30V39h31V73z M134,259H91v-34h43V259z M123,176.708v-55.417
  86. c0-8.25,5.868-11.302,12.77-6.783l40.237,26.272c6.902,4.519,6.958,11.914,0.056,16.434l-40.321,26.277
  87. C128.84,188.011,123,184.958,123,176.708z M207,259h-43v-34h43V259z M207,73h-43V39h43V73z M268,259h-31v-34h31V259z M268,73h-31V39
  88. h31V73z"/>`.trim();
  89.  
  90. const svgInfo = `<path d="M11.812,0C5.289,0,0,5.289,0,11.812s5.289,11.813,11.812,11.813s11.813-5.29,11.813-11.813
  91. S18.335,0,11.812,0z M14.271,18.307c-0.608,0.24-1.092,0.422-1.455,0.548c-0.362,0.126-0.783,0.189-1.262,0.189
  92. c-0.736,0-1.309-0.18-1.717-0.539s-0.611-0.814-0.611-1.367c0-0.215,0.015-0.435,0.045-0.659c0.031-0.224,0.08-0.476,0.147-0.759
  93. l0.761-2.688c0.067-0.258,0.125-0.503,0.171-0.731c0.046-0.23,0.068-0.441,0.068-0.633c0-0.342-0.071-0.582-0.212-0.717
  94. c-0.143-0.135-0.412-0.201-0.813-0.201c-0.196,0-0.398,0.029-0.605,0.09c-0.205,0.063-0.383,0.12-0.529,0.176l0.201-0.828
  95. c0.498-0.203,0.975-0.377,1.43-0.521c0.455-0.146,0.885-0.218,1.29-0.218c0.731,0,1.295,0.178,1.692,0.53
  96. c0.395,0.353,0.594,0.812,0.594,1.376c0,0.117-0.014,0.323-0.041,0.617c-0.027,0.295-0.078,0.564-0.152,0.811l-0.757,2.68
  97. c-0.062,0.215-0.117,0.461-0.167,0.736c-0.049,0.275-0.073,0.485-0.073,0.626c0,0.356,0.079,0.599,0.239,0.728
  98. c0.158,0.129,0.435,0.194,0.827,0.194c0.185,0,0.392-0.033,0.626-0.097c0.232-0.064,0.4-0.121,0.506-0.17L14.271,18.307z
  99. M14.137,7.429c-0.353,0.328-0.778,0.492-1.275,0.492c-0.496,0-0.924-0.164-1.28-0.492c-0.354-0.328-0.533-0.727-0.533-1.193
  100. c0-0.465,0.18-0.865,0.533-1.196c0.356-0.332,0.784-0.497,1.28-0.497c0.497,0,0.923,0.165,1.275,0.497
  101. c0.353,0.331,0.53,0.731,0.53,1.196C14.667,6.703,14.49,7.101,14.137,7.429z"/>`.trim();
  102.  
  103. const svgPlayList = `
  104. <rect x="0" y="64" width="256" height="42.667"/>
  105. <rect x="0" y="149.333" width="256" height="42.667"/>
  106. <rect x="0" y="234.667" width="170.667" height="42.667"/>
  107. <polygon points="341.333,234.667 341.333,149.333 298.667,149.333 298.667,234.667 213.333,234.667 213.333,277.333
  108. 298.667,277.333 298.667,362.667 341.333,362.667 341.333,277.333 426.667,277.333 426.667,234.667"/>
  109. `.trim();
  110.  
  111. // --- Youtube Video Testing :
  112. // Square Video: https://www.youtube.com/watch?v=L0RXVnRbFg8
  113. // Square Video: https://www.youtube.com/watch?v=bK_rKhMIotU
  114. // ---
  115.  
  116.  
  117. const LAYOUT_TWO_COLUMNS = 1;
  118. const LAYOUT_THEATER = 2;
  119. const LAYOUT_FULLSCREEN = 4;
  120. const LAYOUT_CHATROOM = 8;
  121. const LAYOUT_CHATROOM_COLLASPED = 16;
  122. const LAYOUT_TAB_EXPANDED = 32;
  123. const LAYOUT_ENGAGEMENT_PANEL_EXPAND = 64;
  124.  
  125. const mtoInterval1 = 40;
  126. const mtoInterval2 = 150;
  127.  
  128. let lastVideoURL = null;
  129.  
  130.  
  131. const WeakRef = window.WeakRef;
  132. const mWeakRef = WeakRef ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  133. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  134.  
  135. let cmItem = null;
  136.  
  137.  
  138. function tracer(key, cmp) {
  139. if (cmp > 0) return tracer[key] === cmp;
  140. return (tracer[key] = Date.now());
  141. }
  142.  
  143. function racer(key, f) {
  144. let now = Date.now();
  145. const kTime = `${key}$$1`
  146. let t = racer[kTime] || 0;
  147.  
  148. if (now < t) {
  149. const kCount = `${key}$$2`;
  150. racer[kCount] = (racer[kCount] || 0) + 1;
  151. if (racer[kCount] === 1) {
  152. let g = f;
  153. requestAnimationFrame(() => {
  154. racer[kCount] = 0;
  155. g();
  156. g = null;
  157. })
  158. }
  159. } else {
  160. racer[kTime] = now + 16;
  161. f();
  162. }
  163. }
  164.  
  165. class ScriptEF {
  166. constructor() {
  167. this._id = scriptEC;
  168. }
  169. isValid() {
  170. return this._id === scriptEC;
  171. }
  172. }
  173.  
  174. class Timeout {
  175.  
  176. set(f, d, repeatCount) {
  177. if (this.cid > 0) return;
  178. let sEF = new ScriptEF();
  179. if (repeatCount > 0) {
  180.  
  181. let rc = repeatCount;
  182. const g = () => {
  183. this.cid = 0;
  184. if (!sEF.isValid()) return;
  185. let res = f();
  186. if (--rc <= 0) return;
  187. if (res === true) this.cid = setTimeout(g, d);
  188. }
  189. g();
  190.  
  191. } else {
  192.  
  193. const g = () => {
  194. this.cid = 0;
  195. if (!sEF.isValid()) return;
  196. if (f() === true) this.cid = setTimeout(g, d);
  197. }
  198. this.cid = setTimeout(g, d);
  199. }
  200. }
  201.  
  202. clear() {
  203. if (this.cid > 0) clearTimeout(this.cid);
  204. }
  205.  
  206. isEmpty() {
  207. return !this.cid
  208. }
  209.  
  210.  
  211. }
  212.  
  213. class Mutex {
  214.  
  215. constructor() {
  216. this.p = Promise.resolve()
  217. }
  218.  
  219. lockWith(f) {
  220.  
  221. this.p = this.p.then(() => {
  222. return new Promise(f)
  223. }).catch(console.warn)
  224. }
  225.  
  226. }
  227.  
  228.  
  229.  
  230. function prettyElm(elm) {
  231. if (!elm || !elm.nodeName) return null;
  232. const eId = elm.id || null;
  233. const eClsName = elm.className || null;
  234. return [elm.nodeName.toLowerCase(), typeof eId == 'string' ? "#" + eId : '', typeof eClsName == 'string' ? '.' + eClsName.replace(/\s+/g, '.') : ''].join('').trim();
  235. }
  236.  
  237. function extractTextContent(elm) {
  238. 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, '')
  239. }
  240.  
  241. function addScript(scriptText) {
  242. const scriptNode = document.createElement('script');
  243. scriptNode.type = 'text/javascript';
  244. scriptNode.textContent = scriptText;
  245. document.documentElement.appendChild(scriptNode);
  246. return scriptNode;
  247. }
  248.  
  249. function addScriptByURL(scriptURL) {
  250. const scriptNode = document.createElement('script');
  251. scriptNode.type = 'text/javascript';
  252. scriptNode.src = scriptURL;
  253. document.documentElement.appendChild(scriptNode);
  254. return scriptNode;
  255. }
  256.  
  257. function addStyle(styleText, container) {
  258. const styleNode = document.createElement('style');
  259. //styleNode.type = 'text/css';
  260. styleNode.textContent = styleText;
  261. (container || document.documentElement).appendChild(styleNode);
  262. return styleNode;
  263. }
  264.  
  265.  
  266.  
  267.  
  268. function isDOMVisible(elem) {
  269. // jQuery version : https://github.com/jquery/jquery/blob/a684e6ba836f7c553968d7d026ed7941e1a612d8/src/css/hiddenVisibleSelectors.js
  270. return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
  271. }
  272.  
  273. function isNonEmptyString(s) {
  274. return typeof s == 'string' && s.length > 0;
  275. }
  276.  
  277.  
  278. function nativeFunc(dom, property, args) {
  279. dom.dispatchEvent(new CustomEvent("userscript-call-dom-func", { detail: { property, args } }))
  280. }
  281.  
  282. function akAttr(cssElm, attrName, isNegative, flag) {
  283.  
  284. let u = parseInt(cssElm.getAttribute(attrName) || 0) || 0;
  285. let ak = Math.abs(u);
  286.  
  287. if (ak > 100 && isNegative && u < 0) {
  288.  
  289. } else if (ak > 100 && !isNegative && u > 0) {
  290.  
  291. } else {
  292. if (ak <= 100) {
  293. ak = 101;
  294. } else {
  295. ak++;
  296. if (ak >= 800) ak = 101;
  297. }
  298. // 101, 102, ... 799, 101
  299. }
  300.  
  301. let s = '' + (isNegative ? -ak : ak);
  302. flag = flag || '';
  303.  
  304.  
  305. cssElm.setAttribute(attrName, s + flag)
  306. }
  307.  
  308.  
  309.  
  310. let timeout_resize_for_layout_change = new Timeout();
  311.  
  312.  
  313.  
  314. function layoutStatusChanged(old_layoutStatus, new_layoutStatus) {
  315.  
  316.  
  317. if (old_layoutStatus === new_layoutStatus) return;
  318.  
  319. const cssElm = kRef(ytdFlexy);
  320.  
  321. if (!cssElm) return;
  322.  
  323.  
  324. const new_isExpandedChat = !(new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  325. const new_isCollaspedChat = (new_layoutStatus & LAYOUT_CHATROOM_COLLASPED) && (new_layoutStatus & LAYOUT_CHATROOM)
  326.  
  327. const new_isTwoColumns = new_layoutStatus & LAYOUT_TWO_COLUMNS;
  328. const new_isTheater = new_layoutStatus & LAYOUT_THEATER;
  329. const new_isTabExpanded = new_layoutStatus & LAYOUT_TAB_EXPANDED;
  330. const new_isFullScreen = new_layoutStatus & LAYOUT_FULLSCREEN;
  331. const new_isExpandEPanel = new_layoutStatus & LAYOUT_ENGAGEMENT_PANEL_EXPAND;
  332.  
  333.  
  334. function showTabOrChat() {
  335.  
  336. layoutStatusMutex.lockWith(unlock => {
  337.  
  338. if (lastShowTab == '#chatroom') {
  339.  
  340. if (new_isTabExpanded) switchTabActivity(null)
  341. if (!new_isExpandedChat) ytBtnExpandChat();
  342.  
  343. } else if (lastShowTab && lastShowTab.indexOf('#engagement-panel-') == 0) {
  344.  
  345. if (new_isTabExpanded) switchTabActivity(null)
  346. if (!new_isExpandEPanel) ytBtnOpenEngagementPanel(lastShowTab);
  347.  
  348. } else {
  349.  
  350. if (new_isExpandedChat) ytBtnCollapseChat()
  351. if (!new_isTabExpanded) setToActiveTab();
  352.  
  353. }
  354.  
  355. setTimeout(unlock, 40);
  356.  
  357. })
  358. }
  359.  
  360. function hideTabAndChat() {
  361.  
  362. layoutStatusMutex.lockWith(unlock => {
  363.  
  364. if (new_isTabExpanded) switchTabActivity(null)
  365. if (new_isExpandedChat) ytBtnCollapseChat()
  366. if (new_isExpandEPanel) ytBtnCloseEngagementPanels();
  367.  
  368.  
  369. setTimeout(unlock, 40);
  370.  
  371. })
  372.  
  373. }
  374.  
  375.  
  376. if (new_isExpandedChat || new_isTabExpanded || new_isExpandEPanel) {
  377. if (statusCollasped !== 1) statusCollasped = 1;
  378. } else {
  379. if (statusCollasped === 1) statusCollasped = 2;
  380. }
  381.  
  382. let changes = 0;
  383.  
  384. if (old_layoutStatus !== null) changes = old_layoutStatus ^ new_layoutStatus;
  385.  
  386. let chat_collasped_changed = !!(changes & LAYOUT_CHATROOM_COLLASPED)
  387. let tab_expanded_changed = !!(changes & LAYOUT_TAB_EXPANDED)
  388. let theater_mode_changed = !!(changes & LAYOUT_THEATER)
  389. let column_mode_changed = !!(changes & LAYOUT_TWO_COLUMNS)
  390. let fullscreen_mode_changed = !!(changes & LAYOUT_FULLSCREEN)
  391. let epanel_expanded_changed = !!(changes & LAYOUT_ENGAGEMENT_PANEL_EXPAND)
  392.  
  393. let tab_change = (tab_expanded_changed ? 1 : 0) | (chat_collasped_changed ? 2 : 0) | (epanel_expanded_changed ? 4 : 0);
  394.  
  395. let isChatOrTabExpandTriggering = tab_change == 0 ? false : (
  396. (tab_expanded_changed && new_isTabExpanded) ||
  397. (chat_collasped_changed && new_isExpandedChat) ||
  398. (epanel_expanded_changed && new_isExpandEPanel)
  399. );
  400.  
  401. let isChatOrTabCollaspeTriggering = tab_change == 0 ? false : (
  402. (tab_expanded_changed && !new_isTabExpanded) ||
  403. (chat_collasped_changed && new_isCollaspedChat) ||
  404. (epanel_expanded_changed && !new_isExpandEPanel)
  405. );
  406.  
  407.  
  408.  
  409. let moreThanOneShown = (new_isTabExpanded + new_isExpandedChat + new_isExpandEPanel) > 1
  410.  
  411. let requestVideoResize = false;
  412.  
  413. if (fullscreen_mode_changed || new_isFullScreen) {
  414.  
  415. } else if (tab_change == 0 && column_mode_changed && new_isTwoColumns && !new_isTheater && statusCollasped === 1 && moreThanOneShown) {
  416.  
  417. showTabOrChat();
  418. requestVideoResize = true;
  419.  
  420. } else if (tab_change == 2 && new_isExpandedChat && new_isTwoColumns && !new_isTheater && statusCollasped === 1 && new_isTabExpanded && !column_mode_changed) {
  421.  
  422. switchTabActivity(null);
  423. requestVideoResize = true;
  424.  
  425. } else if (isChatOrTabExpandTriggering && new_isTwoColumns && new_isTheater && statusCollasped === 1 && !theater_mode_changed && !column_mode_changed) {
  426.  
  427. ytBtnCancelTheater();
  428. requestVideoResize = true;
  429.  
  430. } else if (new_isTwoColumns && new_isTheater && statusCollasped === 1) {
  431.  
  432. hideTabAndChat();
  433. requestVideoResize = true;
  434.  
  435. } else if (isChatOrTabCollaspeTriggering && new_isTwoColumns && !new_isTheater && statusCollasped === 2 && !column_mode_changed) {
  436.  
  437. ytBtnSetTheater();
  438. requestVideoResize = true;
  439.  
  440. } else if (tab_change == 0 && (column_mode_changed || theater_mode_changed) && new_isTwoColumns && !new_isTheater && statusCollasped !== 1) {
  441.  
  442. showTabOrChat();
  443. requestVideoResize = true;
  444.  
  445. } else if (!new_isFullScreen && new_isTwoColumns && !new_isTheater && !new_isTabExpanded &&
  446. (new_isCollaspedChat || !new_isExpandedChat) &&
  447. !new_isExpandEPanel
  448. ) {
  449. // bug fix for restoring from mini player
  450.  
  451. layoutStatusMutex.lockWith(unlock => {
  452.  
  453. if (new_isExpandedChat) ytBtnCollapseChat()
  454. setToActiveTab();
  455.  
  456. setTimeout(unlock, 40);
  457.  
  458. })
  459.  
  460. requestVideoResize = true;
  461.  
  462. } else if (tab_expanded_changed) {
  463.  
  464. requestVideoResize = true;
  465.  
  466. }
  467.  
  468.  
  469. if (column_mode_changed && !chat_collasped_changed && new_isExpandedChat) {
  470.  
  471. runAfterExpandChat();
  472.  
  473. }
  474.  
  475.  
  476.  
  477. if (requestVideoResize) {
  478.  
  479. timeout_resize_for_layout_change.clear();
  480. timeout_resize_for_layout_change.set(() => {
  481. window.dispatchEvent(new Event('resize'))
  482. }, 92)
  483.  
  484. } else if (timeout_resize_for_layout_change.isEmpty() && (Date.now()) - lastResizeAt > 600) {
  485. timeout_resize_for_layout_change.set(() => {
  486. if ((Date.now()) - lastResizeAt > 600) window.dispatchEvent(new Event('resize'));
  487. }, 62)
  488. }
  489.  
  490.  
  491.  
  492.  
  493. }
  494.  
  495.  
  496. const $ws = {
  497. _layoutStatus: null,
  498. layoutStatus_pending: false
  499. }
  500.  
  501. let wls = new class {
  502. get layoutStatus() {
  503. return this._layoutStatus;
  504. }
  505. set layoutStatus(nv) {
  506.  
  507. if (nv === null) {
  508. this._layoutStatus = null;
  509. statusCollasped = 0;
  510. return;
  511. }
  512. if (nv === this._layoutStatus) return;
  513.  
  514. if (!this.layoutStatus_pending) {
  515. this.layoutStatus_pending = true;
  516. const old_layoutStatus = this._layoutStatus;
  517.  
  518. layoutStatusMutex.lockWith(unlock => {
  519.  
  520. this.layoutStatus_pending = false;
  521. const new_layoutStatus = this._layoutStatus;
  522. layoutStatusChanged(old_layoutStatus, new_layoutStatus);
  523.  
  524. setTimeout(unlock, 40)
  525.  
  526.  
  527. })
  528. }
  529.  
  530. this._layoutStatus = nv;
  531. }
  532. };
  533.  
  534.  
  535.  
  536.  
  537. const svgElm = (w, h, vw, vh, p) => `<svg width="${w}" height="${h}" viewBox="0 0 ${vw} ${vh}" preserveAspectRatio="xMidYMid meet">${p}</svg>`
  538.  
  539. let settings = {
  540. defaultTab: "#tab-videos"
  541. };
  542.  
  543.  
  544. let mtoInterval = mtoInterval1;
  545.  
  546. function isVideoPlaying(video) {
  547. return video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  548. }
  549.  
  550. function wAttr(elm, attr, kv) {
  551. 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) }
  552. }
  553.  
  554. function hideTabBtn(tabBtn) {
  555. var isActiveBefore = tabBtn.classList.contains('active');
  556. tabBtn.classList.add("tab-btn-hidden");
  557. if (isActiveBefore) {
  558. setToActiveTab();
  559. }
  560. }
  561.  
  562. function hasAttribute(obj, key) {
  563. return obj && obj.hasAttribute(key);
  564. }
  565.  
  566. function isTheater() {
  567. const cssElm = kRef(ytdFlexy);
  568. return (cssElm && cssElm.hasAttribute('theater'))
  569. }
  570.  
  571. function isFullScreen() {
  572. const cssElm = kRef(ytdFlexy);
  573. return (cssElm && cssElm.hasAttribute('fullscreen'))
  574. }
  575.  
  576. function isChatExpand() {
  577. const cssElm = kRef(ytdFlexy);
  578. return cssElm && cssElm.hasAttribute('userscript-chatblock') && !cssElm.hasAttribute('userscript-chat-collapsed')
  579. }
  580.  
  581. function isWideScreenWithTwoColumns() {
  582. const cssElm = kRef(ytdFlexy);
  583. return (cssElm && cssElm.hasAttribute('is-two-columns_'))
  584. }
  585.  
  586. function isAnyActiveTab() {
  587. return $('#right-tabs .tab-btn.active').length > 0
  588. }
  589.  
  590. function isEngagementPanelExpanded() {
  591. const cssElm = kRef(ytdFlexy);
  592. return (cssElm && +cssElm.getAttribute('userscript-engagement-panel') > 0)
  593. }
  594.  
  595. function engagement_panels_() {
  596.  
  597. let res = [];
  598.  
  599. let v = 0,
  600. k = 1,
  601. count = 0;
  602. for (const ePanel of document.querySelectorAll('ytd-watch-flexy ytd-engagement-panel-section-list-renderer[tabview-attr-checked]')) {
  603.  
  604. let visibility = ePanel.getAttribute('visibility') //ENGAGEMENT_PANEL_VISIBILITY_EXPANDED //ENGAGEMENT_PANEL_VISIBILITY_HIDDEN
  605.  
  606. switch (visibility) {
  607. case 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED':
  608. v |= k;
  609. count++;
  610. res.push({ ePanel, k, visible: true });
  611. break;
  612. case 'ENGAGEMENT_PANEL_VISIBILITY_HIDDEN':
  613. res.push({ ePanel, k, visible: false });
  614. break;
  615. default:
  616. res.push({ ePanel, k, visible: false });
  617. }
  618.  
  619. k = k << 1;
  620.  
  621. }
  622. return { list: res, value: v, count: count };
  623. }
  624.  
  625.  
  626. function ytBtnOpenEngagementPanel(panel_id) {
  627.  
  628. if (typeof panel_id == 'string') {
  629. panel_id = panel_id.replace('#engagement-panel-', '');
  630. panel_id = parseInt(panel_id);
  631. }
  632. if (panel_id >= 0) {} else return false;
  633.  
  634. let panels = engagement_panels_();
  635.  
  636. for (const { ePanel, k, visible } of panels.list) {
  637. if ((panel_id & k) === k) {
  638. if (!visible) ePanel.setAttribute('visibility', "ENGAGEMENT_PANEL_VISIBILITY_EXPANDED");
  639. } else {
  640. if (visible) ytBtnCloseEngagementPanel(ePanel);
  641. }
  642. }
  643.  
  644. }
  645.  
  646. function ytBtnCloseEngagementPanel(s) {
  647. //ePanel.setAttribute('visibility',"ENGAGEMENT_PANEL_VISIBILITY_HIDDEN");
  648. let btn = s.querySelector('ytd-watch-flexy ytd-engagement-panel-title-header-renderer #header>#visibility-button>ytd-button-renderer');
  649. if (btn) {
  650. btn.click();
  651. }
  652. }
  653.  
  654. function ytBtnCloseEngagementPanels() {
  655. if (isEngagementPanelExpanded()) {
  656. for (const s of document.querySelectorAll('ytd-watch-flexy ytd-engagement-panel-section-list-renderer[tabview-attr-checked]')) {
  657. if (s.getAttribute('visibility') == "ENGAGEMENT_PANEL_VISIBILITY_EXPANDED") ytBtnCloseEngagementPanel(s);
  658. }
  659. }
  660. }
  661.  
  662. function ytBtnSetTheater() {
  663. if (!isTheater()) {
  664. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  665. if (sizeBtn) sizeBtn.click();
  666. }
  667. }
  668.  
  669. function ytBtnCancelTheater() {
  670. if (isTheater()) {
  671. const sizeBtn = document.querySelector('ytd-watch-flexy #ytd-player button.ytp-size-button')
  672. if (sizeBtn) sizeBtn.click();
  673. }
  674. }
  675.  
  676. function ytBtnExpandChat() {
  677. let button = document.querySelector('ytd-live-chat-frame#chat[collapsed]>.ytd-live-chat-frame#show-hide-button')
  678. if (button) button.querySelector('ytd-toggle-button-renderer').click();
  679. }
  680.  
  681. function ytBtnCollapseChat() {
  682. let button = document.querySelector('ytd-live-chat-frame#chat:not([collapsed])>.ytd-live-chat-frame#show-hide-button')
  683. if (button) button.querySelector('ytd-toggle-button-renderer').click();
  684. }
  685.  
  686.  
  687. function hackImgShadow(imgShadow) {
  688. // add to #columns and add back after loaded
  689. let img = imgShadow.querySelector('img')
  690. if (!img) return;
  691.  
  692. let p = imgShadow.parentNode
  693. let z = $(imgShadow).clone()[0]; //to occupy the space
  694. p.replaceChild(z, imgShadow)
  695. $(imgShadow).prependTo('#columns'); // refer to css hack
  696.  
  697. function onload(evt) {
  698. if (evt) this.removeEventListener('load', onload, false)
  699. p.replaceChild(imgShadow, z)
  700. p = null;
  701. z = null;
  702. imgShadow = null;
  703. }
  704.  
  705. if (img.complete) onload();
  706. else img.addEventListener('load', onload, false)
  707. }
  708.  
  709.  
  710. const Q = {}
  711. const FOnce = {}
  712.  
  713. const $callOnceAsync = async function(key) {
  714. if (FOnce[key] && FOnce[key]() === false) FOnce[key] = null
  715. }
  716.  
  717.  
  718.  
  719. function chatFrameContentDocument() {
  720. // non-null if iframe exist && contentDocument && readyState = complete
  721.  
  722. let iframe = document.querySelector('ytd-live-chat-frame iframe#chatframe');
  723. if (!iframe) return null; //iframe must be there
  724. let cDoc = null;
  725. try {
  726. cDoc = iframe.contentDocument;
  727. } catch (e) {}
  728. if (!cDoc) return null;
  729. if (cDoc.readyState != 'complete') return null; //we must wait for its completion
  730.  
  731. return cDoc;
  732.  
  733. }
  734.  
  735. function chatFrameElement(cssSelector) {
  736. let cDoc = chatFrameContentDocument();
  737. if (!cDoc) return null;
  738. let elm = null;
  739. try {
  740. elm = cDoc.querySelector(cssSelector)
  741. } catch (e) {
  742. console.log('iframe error', e)
  743. }
  744. return elm;
  745. }
  746.  
  747.  
  748.  
  749.  
  750. function fixTabs() {
  751.  
  752.  
  753. if (!scriptEnable) return;
  754.  
  755.  
  756. let queryElement = document.querySelector('*:not(#tab-videos)>#related:not([non-placeholder-videos]) > ytd-watch-next-secondary-results-renderer')
  757.  
  758. let isRelocated = !!queryElement;
  759.  
  760.  
  761.  
  762. if (isRelocated) {
  763.  
  764. let relocatedRelated = queryElement.parentNode; // NOT NULL
  765.  
  766. let right_tabs = document.querySelector('#right-tabs');
  767. let tab_videos = right_tabs.querySelector("#tab-videos");
  768.  
  769. if (!right_tabs || !tab_videos) return;
  770.  
  771. for (const s of relocatedRelated.querySelectorAll('#related')) {
  772. s.setAttribute('non-placeholder-videos', '')
  773. }
  774.  
  775. let target_container = document.querySelector('ytd-watch-flexy:not([is-two-columns_]) #primary-inner, ytd-watch-flexy[is-two-columns_] #secondary-inner')
  776.  
  777. if (target_container) target_container.append(right_tabs) // last-child
  778.  
  779.  
  780. let videos_related = relocatedRelated; // NOT NULL
  781. $('[placeholder-videos]').removeAttr('placeholder-videos');
  782. $('[placeholder-for-youtube-play-next-queue]').removeAttr('placeholder-for-youtube-play-next-queue');
  783.  
  784. tab_videos.appendChild(videos_related);
  785. let videos_results_renderer = relocatedRelated.querySelector("ytd-watch-next-secondary-results-renderer");
  786. if (videos_results_renderer) videos_results_renderer.setAttribute('data-dom-changed-by-tabview-youtube', scriptVersionForExternal);
  787. videos_related.setAttribute('placeholder-for-youtube-play-next-queue', '')
  788. videos_related.setAttribute('placeholder-videos', '')
  789.  
  790. $('[placeholder-videos]').on("scroll", makeBodyScrollByEvt);
  791.  
  792.  
  793.  
  794.  
  795. }
  796.  
  797.  
  798.  
  799.  
  800. let chatroom = null;
  801. if (chatroom = document.querySelector('*:not([data-positioner="before|#chat"]) + ytd-live-chat-frame#chat, ytd-live-chat-frame#chat:first-child')) {
  802.  
  803. let positioner = document.querySelector('tabview-youtube-positioner[data-positioner="before|#chat"]');
  804. if (positioner) positioner.remove();
  805.  
  806.  
  807. if (document.querySelector('.YouTubeLiveFilledUpView')) {
  808. // no relocation
  809. } else {
  810.  
  811. $(chatroom).insertBefore('#right-tabs')
  812.  
  813. }
  814.  
  815.  
  816. $(positioner ? positioner : document.createElement('tabview-youtube-positioner')).attr('data-positioner', 'before|#chat').insertBefore(chatroom)
  817.  
  818.  
  819. }
  820.  
  821.  
  822. }
  823.  
  824. const injectionScript_fixAutoComplete = function() {
  825.  
  826. // https://cdnjs.cloudflare.com/ajax/libs/JavaScript-autoComplete/1.0.4/auto-complete.min.js
  827.  
  828. for (const s of document.querySelectorAll('[autocomplete="off"]:not([data-autocomplete-results-id])')) {
  829.  
  830.  
  831. let sc = s.sc;
  832. if (sc instanceof HTMLElement) {
  833.  
  834. let id = Date.now();
  835. s.setAttribute('data-autocomplete-results-id', id);
  836. sc.setAttribute('data-autocomplete-input-id', id);
  837.  
  838. if (window.WeakRef) {
  839. s._sc = new WeakRef(sc);
  840. s.sc = null;
  841. delete s.sc;
  842. Object.defineProperty(s, 'sc', {
  843. get: function() { return s._sc.deref() || null; },
  844. enumerable: true,
  845. configurable: true
  846. })
  847. }
  848.  
  849. if (sc.hasAttribute('autocomplete-disable-updatesc') && typeof s.updateSC == 'function') {
  850.  
  851. window.removeEventListener('resize', s.updateSC);
  852. s.updateSC = function() {};
  853.  
  854. }
  855.  
  856. sc.dispatchEvent(new CustomEvent('autocomplete-sc-exist'));
  857.  
  858.  
  859. }
  860.  
  861. }
  862.  
  863. };
  864.  
  865.  
  866. function handlerAutoCompleteExist() {
  867.  
  868.  
  869. let autoComplete = this;
  870.  
  871. autoComplete.removeEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false)
  872.  
  873. let domId = autoComplete.getAttribute('data-autocomplete-input-id')
  874. let searchBox = autoComplete.ownerDocument.querySelector(`[data-autocomplete-results-id="${domId}"]`)
  875.  
  876. if (!domId || !searchBox) return;
  877.  
  878. let positioner = searchBox.nextSibling;
  879. if (positioner && positioner.nodeName.toLowerCase() == "autocomplete-positioner") {} else if (positioner && positioner.nodeName.toLowerCase() != "autocomplete-positioner") {
  880. $(positioner = document.createElement("autocomplete-positioner")).insertAfter(searchBox);
  881. } else {
  882. $(positioner = document.createElement("autocomplete-positioner")).prependTo(searchBox.parentNode);
  883. }
  884. $(autoComplete).prependTo(positioner);
  885.  
  886. positioner.style.setProperty('--sb-margin-bottom', getComputedStyle(searchBox).marginBottom)
  887. positioner.style.setProperty('--height', searchBox.offsetHeight + 'px')
  888.  
  889. }
  890.  
  891. function mtf_fixAutoCompletePosition(elmAutoComplete) {
  892.  
  893. elmAutoComplete.setAttribute('autocomplete-disable-updatesc', '')
  894. elmAutoComplete.addEventListener('autocomplete-sc-exist', handlerAutoCompleteExist, false)
  895.  
  896. if (isMyScriptInChromeRuntime())
  897. addScriptByURL(window.chrome.runtime.getURL('js/injectionScript_fixAutoComplete.js'));
  898. else
  899. addScript(`!!(${injectionScript_fixAutoComplete+''})()`);
  900. // addScriptByURL(`${githubURLBase}/${githubURLCommit}/js/injectionScript_fixAutoComplete.js`);
  901.  
  902. }
  903.  
  904. function mtf_AfterFixTabs() {
  905.  
  906.  
  907. let ytdFlexyElm = kRef(ytdFlexy);
  908. if (!scriptEnable || !ytdFlexyElm) return;
  909.  
  910. const rootElement = Q.mutationTarget || ytdFlexyElm;
  911.  
  912.  
  913.  
  914. const autocomplete = rootElement.querySelector('[placeholder-for-youtube-play-next-queue] input#suggestions-search + autocomplete-positioner > .autocomplete-suggestions[data-autocomplete-input-id]:not([position-fixed-by-tabview-youtube])')
  915.  
  916. if (autocomplete) {
  917.  
  918. const searchBox = document.querySelector('[placeholder-for-youtube-play-next-queue] input#suggestions-search')
  919.  
  920.  
  921. if (searchBox) {
  922.  
  923.  
  924. autocomplete.parentNode.setAttribute('position-fixed-by-tabview-youtube', '');
  925. autocomplete.setAttribute('position-fixed-by-tabview-youtube', '');
  926. autocomplete.setAttribute('userscript-scrollbar-render', '')
  927.  
  928. if (!searchBox.hasAttribute('is-set-click-to-toggle')) {
  929. searchBox.setAttribute('is-set-click-to-toggle', '')
  930. searchBox.addEventListener('click', function() {
  931.  
  932.  
  933. setTimeout(() => {
  934. const autocomplete = document.querySelector(`.autocomplete-suggestions[data-autocomplete-input-id="${ this.getAttribute('data-autocomplete-results-id') }"]`)
  935.  
  936. if (!autocomplete) return;
  937.  
  938. const isNotEmpty = (autocomplete.textContent || '').length > 0 && (this.value || '').length > 0;
  939.  
  940. if (isNotEmpty) {
  941.  
  942. let elmVisible = isDOMVisible(autocomplete)
  943.  
  944. if (elmVisible) $(autocomplete).hide();
  945. else $(autocomplete).show();
  946.  
  947. }
  948.  
  949. }, 20);
  950.  
  951. })
  952.  
  953. let timeoutOnce_searchbox_keyup = new Timeout();
  954. searchBox.addEventListener('keyup', function() {
  955.  
  956. timeoutOnce_searchbox_keyup.set(() => {
  957.  
  958. const autocomplete = document.querySelector(`.autocomplete-suggestions[data-autocomplete-input-id="${ this.getAttribute('data-autocomplete-results-id') }"]`)
  959.  
  960. if (!autocomplete) return;
  961.  
  962.  
  963. const isNotEmpty = (autocomplete.textContent || '').length > 0 && (this.value || '').length > 0
  964.  
  965. if (isNotEmpty) {
  966.  
  967. let elmVisible = isDOMVisible(autocomplete)
  968.  
  969. if (!elmVisible) $(autocomplete).show();
  970.  
  971. }
  972.  
  973. }, 20);
  974.  
  975. })
  976.  
  977. }
  978.  
  979.  
  980.  
  981. }
  982.  
  983. }
  984.  
  985.  
  986.  
  987.  
  988. let currentLastVideo = rootElement.querySelector('[placeholder-videos] #items ytd-compact-video-renderer:last-of-type')
  989. let prevLastVideo = kRef(_cachedLastVideo);
  990.  
  991. if (prevLastVideo !== currentLastVideo && currentLastVideo) {
  992. _cachedLastVideo = mWeakRef(currentLastVideo);
  993. }
  994.  
  995. if (prevLastVideo !== currentLastVideo && currentLastVideo && prevLastVideo) {
  996.  
  997. let isPrevRemoved = !prevLastVideo.parentNode
  998.  
  999.  
  1000. function getVideoListHash() {
  1001.  
  1002. let res = [...document.querySelectorAll('[placeholder-videos] #items ytd-compact-video-renderer')].map(renderer => {
  1003. return renderer.querySelector('a[href*="watch"][href*="v="]').getAttribute('href')
  1004.  
  1005. }).join('|')
  1006. // /watch?v=XXXXX|/watch?v=XXXXXX|/watch?v=XXXXXX
  1007.  
  1008. // alternative - DOM.data.videoId
  1009. // let elms = document.querySelectorAll('[placeholder-videos] #items ytd-compact-video-renderer')
  1010. // let res = [...elms].map(elm=>elm.data.videoId||'').join('|') ;
  1011.  
  1012. if (res.indexOf('||') >= 0) {
  1013. res = '';
  1014. }
  1015.  
  1016. return res ? res : null;
  1017. }
  1018.  
  1019. if (isPrevRemoved) {
  1020.  
  1021. // this is the replacement of videos instead of addition
  1022.  
  1023. const searchBox = document.querySelector('[placeholder-for-youtube-play-next-queue] input#suggestions-search')
  1024.  
  1025. let currentPlayListHash = getVideoListHash() || null;
  1026.  
  1027. if (!currentPlayListHash) {
  1028.  
  1029. } else if (!videoListBeforeSearch && searchBox) {
  1030.  
  1031. videoListBeforeSearch = currentPlayListHash;
  1032. if (videoListBeforeSearch) {
  1033. //console.log('fromSearch', videoListBeforeSearch)
  1034.  
  1035. requestAnimationFrame(function() {
  1036.  
  1037. let renderer = document.querySelector('[placeholder-videos] ytd-watch-next-secondary-results-renderer');
  1038. if (searchBox && searchBox.parentNode) searchBox.blur();
  1039.  
  1040. if (renderer) {
  1041. let scrollParent = renderer.parentNode;
  1042. if (scrollParent.scrollHeight > scrollParent.offsetHeight) {
  1043. let targetTop = renderer.offsetTop;
  1044. if (searchBox && searchBox.parentNode == scrollParent) targetTop -= searchBox.offsetHeight
  1045. scrollParent.scrollTop = targetTop - scrollParent.firstChild.offsetTop;
  1046. }
  1047. }
  1048.  
  1049. });
  1050.  
  1051. }
  1052.  
  1053. } else if (videoListBeforeSearch) {
  1054.  
  1055. if (currentPlayListHash != videoListBeforeSearch) {
  1056.  
  1057. videoListBeforeSearch = null;
  1058. //console.log('fromSearch', videoListBeforeSearch)
  1059.  
  1060.  
  1061. }
  1062.  
  1063. }
  1064.  
  1065.  
  1066. }
  1067.  
  1068.  
  1069. }
  1070.  
  1071.  
  1072.  
  1073.  
  1074. }
  1075.  
  1076. function base_ChatExist() {
  1077.  
  1078. let ytdFlexyElm = kRef(ytdFlexy);
  1079. if (!scriptEnable || !ytdFlexyElm) return null;
  1080.  
  1081. // no mutation triggering if the changes are inside the iframe
  1082.  
  1083. // 1) Detection of #continuations inside iframe
  1084. // iframe ownerDocument is accessible due to same origin
  1085. // if the chatroom is collasped, no determination of live chat or replay (as no #continuations and somehow a blank iframe doc)
  1086.  
  1087. // 2) Detection of meta tag
  1088. // This is fastest but not reliable. It is somehow a bug that the navigation might not update the meta tag content
  1089.  
  1090. // 3) Detection of HTMLElement inside video player for live video
  1091.  
  1092. // (1)+(3) = solution
  1093.  
  1094. let attr_chatblock = null
  1095. let attr_chatcollapsed = null;
  1096.  
  1097. const elmChat = document.querySelector('ytd-live-chat-frame#chat')
  1098. let elmCont = null;
  1099. if (elmChat) {
  1100. elmCont = chatFrameElement('yt-live-chat-renderer #continuations')
  1101.  
  1102. let s = 0;
  1103. if (elmCont) {
  1104. //not found if it is collasped.
  1105. s |= elmCont.querySelector('yt-timed-continuation') ? 1 : 0;
  1106. s |= elmCont.querySelector('yt-live-chat-replay-continuation, yt-player-seek-continuation') ? 2 : 0;
  1107. //s |= elmCont.querySelector('yt-live-chat-restricted-participation-renderer')?4:0;
  1108. if (s == 1) {
  1109. //console.log(7005)
  1110. attr_chatblock = 'chat-live';
  1111. //disableComments_LiveChat();
  1112. }
  1113. if (s == 2) attr_chatblock = 'chat-playback';
  1114. //if(s==5) attr_chatblock='chat-live-paid';
  1115.  
  1116. if (s == 1) $("span#tab3-txt-loader").text('');
  1117.  
  1118. }
  1119. //keep unknown as original
  1120.  
  1121. } else {
  1122. attr_chatblock = false;
  1123. attr_chatcollapsed = false;
  1124.  
  1125. }
  1126.  
  1127. return { attr_chatblock, attr_chatcollapsed }
  1128.  
  1129. }
  1130.  
  1131.  
  1132. function mtf_ChatExist() {
  1133.  
  1134. let ytdFlexyElm = kRef(ytdFlexy);
  1135. if (!scriptEnable || !ytdFlexyElm) return;
  1136.  
  1137. const elmChat = document.querySelector('ytd-live-chat-frame#chat')
  1138. let elmCont = null;
  1139. if (elmChat) {
  1140. elmCont = chatFrameElement('yt-live-chat-renderer #continuations')
  1141. }
  1142.  
  1143. const chatBlockR = (elmChat ? 1 : 0) + (elmCont ? 2 : 0)
  1144. if (Q.mtf_chatBlockQ !== chatBlockR) {
  1145. Q.mtf_chatBlockQ = chatBlockR
  1146. let rChatExist = base_ChatExist();
  1147. if (rChatExist) {
  1148. let { attr_chatblock, attr_chatcollapsed } = rChatExist;
  1149. wAttr(ytdFlexyElm, 'userscript-chatblock', attr_chatblock)
  1150. wAttr(ytdFlexyElm, 'userscript-chat-collapsed', attr_chatcollapsed)
  1151. }
  1152. }
  1153. }
  1154.  
  1155.  
  1156.  
  1157.  
  1158. let lastScrollAt1 = 0;
  1159.  
  1160. function makeBodyScrollByEvt() {
  1161. let ct = Date.now();
  1162. if (ct - lastScrollAt1 < 6) return; // avoid duplicate calling
  1163. lastScrollAt1 = ct;
  1164. window.dispatchEvent(new Event("scroll")); // dispatch Scroll Event to Window for content display
  1165. }
  1166.  
  1167. let lastScrollAt2 = 0;
  1168.  
  1169. function makeBodyScroll() {
  1170. let ct = Date.now();
  1171. if (ct - lastScrollAt2 < 30) return; // avoid over triggering
  1172. lastScrollAt2 = ct;
  1173. requestAnimationFrame(() => {
  1174. window.dispatchEvent(new Event("scroll")); // ask youtube to display content
  1175. })
  1176. }
  1177.  
  1178. let requestingComments = null
  1179. let scrollForComments_lastStart = 0;
  1180.  
  1181. function scrollForComments_TF() {
  1182. let comments = requestingComments;
  1183. if (!comments) return;
  1184. if (comments.hasAttribute('hidden')) {
  1185. window.dispatchEvent(new Event("scroll"));
  1186. } else requestingComments = null;
  1187. }
  1188.  
  1189. function scrollForComments() {
  1190. scrollForComments_TF();
  1191. if (!requestingComments) return;
  1192. requestAnimationFrame(scrollForComments_TF);
  1193. let ct = Date.now();
  1194. if (ct - scrollForComments_lastStart < 60) return;
  1195. scrollForComments_lastStart = ct;
  1196. setTimeout(scrollForComments_TF, 80);
  1197. setTimeout(scrollForComments_TF, 240);
  1198. setTimeout(scrollForComments_TF, 870);
  1199. }
  1200.  
  1201.  
  1202.  
  1203.  
  1204. const mtoCs = { mtoNav: null, mtoBody: null };
  1205.  
  1206.  
  1207. const mtoVs = {}
  1208.  
  1209. const mutation_target_id_list = ['ytp-caption-window-container', 'items', 'button', 'movie_player', 'player-ads', 'hover-overlays', 'replies'];
  1210. const mutation_target_class_list = ['ytp-panel-menu', 'ytp-endscreen-content'];
  1211.  
  1212. function isMtoOverallSkip(dTarget) {
  1213.  
  1214. if (!dTarget || dTarget.nodeType !== 1) return true;
  1215.  
  1216. if (mutation_target_id_list.includes(dTarget.id)) return true;
  1217.  
  1218. let className = dTarget.className.toLowerCase();
  1219. let classNameSplit = className.split(' ');
  1220. for (const c of classNameSplit) {
  1221. if (mutation_target_class_list.includes(c)) return true;
  1222. }
  1223.  
  1224. return false;
  1225. }
  1226.  
  1227.  
  1228. const mutation_div_id_ignorelist = [
  1229. 'metadata-line',
  1230. 'ytp-caption-window-container',
  1231. 'top-level-buttons-computed',
  1232. 'microformat',
  1233. 'visibility-button',
  1234. 'info-strings',
  1235. 'action-menu',
  1236. 'reply-button-end'
  1237. ];
  1238.  
  1239. const mutation_div_class_ignorelist = [
  1240. 'badge', 'tp-yt-paper-tooltip', 'ytp-autonav-endscreen-upnext-header',
  1241. 'ytp-bound-time-left', 'ytp-bound-time-right', 'ytp-share-icon',
  1242. 'ytp-tooltip-title', 'annotation', 'ytp-copylink-icon', 'ytd-thumbnail',
  1243. 'paper-ripple',
  1244. //caption
  1245. 'captions-text', 'caption-visual-line', 'ytp-caption-segment', 'ytp-caption-window-container',
  1246. //menu
  1247. 'ytp-playlist-menu-button-text',
  1248.  
  1249. 'ytp-bezel-icon', 'ytp-bezel-text',
  1250. 'dropdown-content',
  1251. 'tp-yt-paper-menu-button', 'tp-yt-iron-dropdown',
  1252.  
  1253. 'ytd-metadata-row-renderer', // #content.ytd-metadata-row-renderer inside each of ytd-metadata-row-renderer (ytd-expander)
  1254. '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
  1255.  
  1256. 'autocomplete-suggestions' // autocomplete-suggestions
  1257. ];
  1258.  
  1259. const mutation_target_tag_ignorelist = [
  1260. 'ytd-channel-name', 'tp-yt-iron-dropdown', 'tp-yt-paper-tooltip',
  1261. 'tp-yt-paper-listbox', 'yt-img-shadow', 'ytd-thumbnail', 'ytd-video-meta-block',
  1262.  
  1263. 'yt-icon-button', 'tp-yt-paper-button', 'yt-formatted-string', 'yt-icon', 'button', 'paper-ripple',
  1264.  
  1265. 'ytd-player-microformat-renderer',
  1266. 'ytd-engagement-panel-section-list-renderer', 'ytd-engagement-panel-title-header-renderer',
  1267. 'ytd-comment-renderer', 'ytd-menu-renderer', 'ytd-badge-supported-renderer',
  1268. 'ytd-subscribe-button-renderer', 'ytd-subscription-notification-toggle-button-renderer',
  1269. 'ytd-button-renderer', 'ytd-toggle-button-renderer',
  1270. 'yt-pdg-comment-chip-renderer', 'ytd-comment-action-buttons-renderer', 'ytd-comment-thread-renderer',
  1271. 'ytd-compact-radio-renderer', 'ytd-compact-video-renderer',
  1272. 'ytd-video-owner-renderer',
  1273. 'ytd-metadata-row-renderer', //ytd-metadata-row-renderer is part of the #collapsible inside ytd-expander
  1274.  
  1275. 'ytd-moving-thumbnail-renderer',
  1276. 'ytd-thumbnail-overlay-toggle-button-renderer',
  1277. 'ytd-thumbnail-overlay-bottom-panel-renderer', 'ytd-thumbnail-overlay-equalizer',
  1278. 'ytd-thumbnail-overlay-now-playing-renderer', 'ytd-thumbnail-overlay-resume-playback-renderer',
  1279. 'ytd-thumbnail-overlay-side-panel-renderer', 'ytd-thumbnail-overlay-time-status-renderer',
  1280. 'ytd-thumbnail-overlay-hover-text-renderer',
  1281.  
  1282. 'yt-interaction',
  1283. 'tp-yt-paper-spinner-lite', 'tp-yt-paper-spinner',
  1284.  
  1285. 'h1', 'h2', 'h3', 'h4', 'h5', 'span', 'a',
  1286.  
  1287. 'meta', 'br', 'script', 'style', 'link', 'dom-module', 'template'
  1288. ];
  1289.  
  1290. function isMtoTargetSkip(mutation) {
  1291. //skip not important mutation tartget
  1292.  
  1293. if (!mutation) return true;
  1294. let { type, target } = mutation
  1295.  
  1296. if (!target || target.nodeType !== 1 || type != 'childList') return true;
  1297.  
  1298. let tagName = target.nodeName.toLowerCase();
  1299. let className;
  1300. let classNameSplit;
  1301.  
  1302. if (mutation_target_tag_ignorelist.includes(tagName)) return true;
  1303.  
  1304. switch (tagName) {
  1305.  
  1306.  
  1307. case 'ytd-expander':
  1308. if (target.id == 'expander' && Q.comments_section_loaded == 1 && target.classList.contains('ytd-comment-renderer')) return true; // load comments
  1309. return false;
  1310.  
  1311. case 'div':
  1312.  
  1313. if (target.id == 'contents') {
  1314. return false;
  1315. }
  1316. if (mutation_div_id_ignorelist.includes(target.id)) return true;
  1317.  
  1318. className = target.className.toLowerCase();
  1319. classNameSplit = className.split(' ');
  1320. for (const c of classNameSplit) {
  1321. if (mutation_div_class_ignorelist.includes(c)) return true;
  1322. }
  1323.  
  1324. return false;
  1325.  
  1326. }
  1327.  
  1328. return false;
  1329.  
  1330. }
  1331.  
  1332.  
  1333.  
  1334. // continuous check for element relocation
  1335. function mtf_append_comments() {
  1336.  
  1337. let ytdFlexyElm = kRef(ytdFlexy);
  1338. if (!scriptEnable || !ytdFlexyElm) return;
  1339.  
  1340. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1341.  
  1342. let comments = rootElement.querySelector('#primary ytd-watch-metadata ~ ytd-comments#comments');
  1343. if (comments) $(comments).appendTo('#tab-comments').attr('data-dom-changed-by-tabview-youtube', scriptVersionForExternal)
  1344. }
  1345.  
  1346. // continuous check for element relocation
  1347. function mtf_liveChatBtnF() {
  1348. let ytdFlexyElm = kRef(ytdFlexy);
  1349. if (!scriptEnable || !ytdFlexyElm) return;
  1350.  
  1351. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1352.  
  1353. let button = rootElement.querySelector('ytd-live-chat-frame#chat>.ytd-live-chat-frame#show-hide-button:nth-child(n+2)');
  1354. if (button) button.parentNode.insertBefore(button, button.parentNode.firstChild)
  1355. }
  1356.  
  1357.  
  1358.  
  1359. // continuous check for element relocation
  1360. // fired at begining & window resize, etc
  1361. function mtf_append_playlist() {
  1362.  
  1363. let ytdFlexyElm = kRef(ytdFlexy);
  1364. if (!scriptEnable || !ytdFlexyElm) return;
  1365.  
  1366. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1367.  
  1368. let ple1 = rootElement.querySelector("*:not(#ytd-userscript-playlist)>ytd-playlist-panel-renderer#playlist");
  1369. if (ple1) {
  1370. let ct = Date.now();
  1371. let truePlaylist = null;
  1372. let truePlaylist_items = document.querySelector('ytd-playlist-panel-renderer#playlist #items:not(:empty)');
  1373. if (truePlaylist_items) {
  1374.  
  1375. let pElm = truePlaylist_items.parentNode;
  1376. while (pElm && pElm.nodeType === 1) {
  1377. if (pElm.id == 'playlist') {
  1378. pElm.setAttribute('tabview-true-playlist', ct)
  1379. truePlaylist = pElm;
  1380. break;
  1381. }
  1382. pElm = pElm.parentNode;
  1383. }
  1384.  
  1385. }
  1386.  
  1387. if (!truePlaylist) truePlaylist = ple1; // NOT NULL
  1388.  
  1389. for (const s of document.querySelectorAll(`*:not(#ytd-userscript-playlist)>ytd-playlist-panel-renderer#playlist:not([tabview-true-playlist="${ct}"])`))
  1390. s.parentNode.removeChild(s);
  1391.  
  1392. let $wrapper = getWrapper('ytd-userscript-playlist')
  1393. $wrapper.append(truePlaylist).appendTo(document.querySelector("#tab-list"));
  1394. truePlaylist.setAttribute('data-dom-changed-by-tabview-youtube', scriptVersionForExternal)
  1395. setDisplayedPlaylist(); // relocation after re-layout
  1396.  
  1397. requestAnimationFrame(() => {
  1398. let ytdFlexyElm = kRef(ytdFlexy);
  1399. if (!scriptEnable || !ytdFlexyElm) return;
  1400. if (!switchTabActivity_lastTab && (ytdFlexyElm.getAttribute('tabview-selection') + '').indexOf('#tab-') === 0 && /https\:\/\/www\.youtube\.com\/watch.*[\?\&]list=[\w\-\_]+/.test(location.href)) {
  1401. if (setToActiveTab('#tab-list')) switchTabActivity_lastTab = '#tab-list';
  1402. }
  1403. })
  1404.  
  1405. }
  1406. }
  1407.  
  1408.  
  1409. // content fix - info & playlist
  1410. // fired at begining, and keep for in case any change
  1411. function mtf_fix_details() {
  1412.  
  1413. if (!scriptEnable) return;
  1414.  
  1415. if (no_fix_contents_until < Date.now()) {
  1416. const content = document.querySelector('#meta-contents ytd-expander>#content, #tab-info ytd-expander>#content')
  1417. if (content) {
  1418. no_fix_contents_until = Date.now() + 3000;
  1419. setTimeout(function() {
  1420. const expander = content.parentNode;
  1421.  
  1422. if (expander.hasAttribute('collapsed')) wAttr(expander, 'collapsed', false);
  1423. expander.style.setProperty('--ytd-expander-collapsed-height', '');
  1424.  
  1425. let btn1 = expander.querySelector('tp-yt-paper-button#less:not([hidden])');
  1426. let btn2 = expander.querySelector('tp-yt-paper-button#more:not([hidden])');
  1427.  
  1428. if (btn1) wAttr(btn1, 'hidden', true);
  1429. if (btn2) wAttr(btn2, 'hidden', true);
  1430. }, 40);
  1431.  
  1432. }
  1433. }
  1434.  
  1435. if (no_fix_playlist_until < Date.now()) {
  1436. // just in case the playlist is collapsed
  1437. const playlist = document.querySelector('#tab-list ytd-playlist-panel-renderer#playlist')
  1438. if (playlist) {
  1439. no_fix_playlist_until = Date.now() + 3000;
  1440. setTimeout(function() {
  1441. if (playlist.hasAttribute('collapsed')) wAttr(playlist, 'collapsed', false);
  1442. if (playlist.hasAttribute('collapsible')) wAttr(playlist, 'collapsible', false);
  1443. }, 40)
  1444. }
  1445. }
  1446.  
  1447.  
  1448. }
  1449.  
  1450.  
  1451.  
  1452. function status_commentsHidden() {
  1453.  
  1454. var comments = document.querySelector('ytd-comments#comments')
  1455. if (!comments || (comments.childElementCount === 0 && comments.hasAttribute('hidden'))) return 2;
  1456. if (comments.hasAttribute('hidden')) return 1;
  1457. return 0;
  1458.  
  1459. }
  1460.  
  1461.  
  1462. function getFMT(ytdFlexyElm) {
  1463.  
  1464.  
  1465. let fmt = ["ytd-comments#comments #count.ytd-comments-header-renderer", 'ytd-item-section-renderer#sections #header ~ #contents>ytd-message-renderer'].map(s => {
  1466.  
  1467. let elm = ytdFlexyElm.querySelector(s)
  1468. if (!elm) return null;
  1469. return elm.querySelector('yt-formatted-string') || elm.closest('yt-formatted-string') || null
  1470.  
  1471.  
  1472. });
  1473.  
  1474. return fmt
  1475. }
  1476.  
  1477. function toFST(elm) {
  1478.  
  1479. if (!elm) return null;
  1480. return elm.querySelector('yt-formatted-string') || elm.closest('yt-formatted-string') || null
  1481. }
  1482.  
  1483.  
  1484. function innerCommentsLoader() {
  1485.  
  1486.  
  1487. const rootElement = Q.mutationTarget || kRef(ytdFlexy);
  1488. if (!rootElement) return;
  1489.  
  1490. let messageElm, messageStr, commentRenderer;
  1491.  
  1492. if (commentRenderer = rootElement.querySelector("ytd-comments#comments #count.ytd-comments-header-renderer")) {
  1493.  
  1494. return {
  1495. status: 1,
  1496. f: () => {
  1497.  
  1498. let span = document.querySelector("span#tab3-txt-loader")
  1499. Q.fetchedOnce = true;
  1500. let r = '0';
  1501. let txt = commentRenderer.textContent
  1502. if (typeof txt == 'string') {
  1503. let m = txt.match(/[\d\,\s]+/)
  1504. if (m) {
  1505. r = m[0].trim()
  1506.  
  1507.  
  1508. }
  1509. }
  1510. if (span) span.textContent = r;
  1511. mtoInterval = mtoInterval2;
  1512. setCommentSection(1);
  1513. cmItem = mWeakRef(toFST(commentRenderer))
  1514. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents'))
  1515. }
  1516. }
  1517.  
  1518. } else if ((messageElm = rootElement.querySelector('ytd-item-section-renderer#sections #header ~ #contents>ytd-message-renderer')) && (messageStr = (messageElm.textContent || '').trim())) { //ytd-message-renderer
  1519. // it is possible to get the message before the header generation.
  1520. return {
  1521. status: 2,
  1522. f: () => {
  1523. setTimeout(function() {
  1524. if (Q.fetchedOnce) return;
  1525. let span = document.querySelector("span#tab3-txt-loader")
  1526. const mainMsg = messageElm.querySelector('#message, #submessage')
  1527. if (mainMsg && mainMsg.textContent) {
  1528. for (const msg of mainMsg.querySelectorAll('*:not(:empty)')) {
  1529. if (msg.childElementCount === 0 && msg.textContent) {
  1530. messageStr = msg.textContent.trim()
  1531. break
  1532. }
  1533. }
  1534. }
  1535. if (span) span.textContent = messageStr;
  1536. mtoInterval = mtoInterval2;
  1537. setCommentSection(1);
  1538. cmItem = mWeakRef(toFST(messageElm))
  1539. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents'))
  1540. }, 40);
  1541. }
  1542. }
  1543.  
  1544. }
  1545.  
  1546. }
  1547.  
  1548. const FP = {
  1549.  
  1550. mtoNav_delayedF: () => {
  1551.  
  1552. let { addP, removeP, mutationTarget } = Q;
  1553.  
  1554. Q.addP = 0;
  1555. Q.removeP = 0;
  1556.  
  1557. let isInvalidAdding = Q.mutationTarget && !Q.mutationTarget.parentNode
  1558.  
  1559. let promisesForAddition = !scriptEnable ? [] : addP > 0 && !isInvalidAdding ? [
  1560.  
  1561. $callOnceAsync('mtf_checkFlexy'),
  1562. $callOnceAsync('mtf_initalAttr_comments'),
  1563. $callOnceAsync('mtf_initalAttr_playlist'),
  1564. $callOnceAsync('mtf_initalAttr_chatroom'),
  1565. $callOnceAsync('mtf_initalAttr_engagement_panel'),
  1566. $callOnceAsync('mtf_advancedComments'),
  1567. $callOnceAsync('mtf_checkDescriptionLoaded'),
  1568. $callOnceAsync('mtf_fetchCommentsAvailable'),
  1569. $callOnceAsync('mtf_forceCheckLiveVideo'),
  1570.  
  1571. (async () => {
  1572. mtf_append_comments();
  1573. })(),
  1574.  
  1575. (async () => {
  1576. mtf_liveChatBtnF();
  1577. })(),
  1578.  
  1579. (async () => {
  1580. fixTabs();
  1581. mtf_AfterFixTabs();
  1582. })(),
  1583.  
  1584. (async () => {
  1585. mtf_append_playlist();
  1586. })()
  1587. ] : [];
  1588.  
  1589.  
  1590.  
  1591. let promisesForEveryMutation = !scriptEnable ? [] : [
  1592. (async () => {
  1593. mtf_fix_details();
  1594. })(),
  1595. (async () => {
  1596. mtf_ChatExist();
  1597. })()
  1598. ];
  1599.  
  1600.  
  1601. Promise.all([...promisesForAddition, ...promisesForEveryMutation]).then(() => {
  1602. Q.mutationTarget = null;
  1603.  
  1604. Q.mtoNav_requestNo--;
  1605. //console.log('motnav reduced to', mtoNav_requestNo)
  1606. if (Q.mtoNav_requestNo > 0) {
  1607. Q.mtoNav_requestNo = 1;
  1608. setTimeout(FP.mtoNav_delayedF, mtoInterval);
  1609. }
  1610. })
  1611.  
  1612.  
  1613. },
  1614.  
  1615. mtoNavF: (mutations, observer) => {
  1616.  
  1617. if (!scriptEnable) return;
  1618.  
  1619. let ch = false;
  1620.  
  1621. let reg = [];
  1622. let dTarget = null;
  1623.  
  1624. let wAddP = 0,
  1625. wRemoveP = 0;
  1626.  
  1627. let _last_mto_target = null;
  1628. let _last_mto_target_valid = null;
  1629.  
  1630. for (const mutation of mutations) {
  1631. if (!mutation || !mutation.target || !mutation.target.parentNode) continue;
  1632.  
  1633. let elementalMutation = false;
  1634. let tAddP = 0,
  1635. tRemoveP = 0;
  1636.  
  1637. for (const addedNode of mutation.addedNodes) { //theoretically faster: only reading of states
  1638. if (addedNode.nodeType === 1) {
  1639. tAddP++;
  1640. elementalMutation = true;
  1641. }
  1642. }
  1643.  
  1644. for (const removedNode of mutation.removedNodes) { //theoretically faster: only reading of states
  1645. if (removedNode.nodeType === 1) {
  1646. tRemoveP++;
  1647. elementalMutation = true;
  1648. }
  1649. }
  1650.  
  1651. if (elementalMutation) { //skip all addition and removal operations without elemental changes (e.g. textNode modification)
  1652.  
  1653. if (_last_mto_target === mutation.target) {
  1654. // due to addition and removal operations to the same DOM
  1655. if (_last_mto_target_valid) {
  1656. // AddP & RemoveP is still valid
  1657. wAddP += tAddP;
  1658. wRemoveP += tRemoveP;
  1659. }
  1660. continue;
  1661. }
  1662. _last_mto_target = mutation.target;
  1663.  
  1664. if (isMtoTargetSkip(mutation)) {
  1665. _last_mto_target_valid = false;
  1666. continue; //theoretically slower: creation of string variables
  1667. } else {
  1668. _last_mto_target_valid = true;
  1669. wAddP += tAddP;
  1670. wRemoveP += tRemoveP;
  1671. }
  1672.  
  1673.  
  1674.  
  1675. ch = true;
  1676.  
  1677. reg.push(mutation);
  1678.  
  1679. if (dTarget === null) dTarget = mutation.target; //first
  1680. else if (dTarget === true) {} //ytdFlexy
  1681. else if (dTarget.contains(mutation.target)) {} //first node is the container to all subsequential targets
  1682. else { dTarget = true; } //the target is not the child of first node
  1683.  
  1684. }
  1685.  
  1686. }
  1687.  
  1688. if (!ch) return; // dTarget must be true OR HTMLElement
  1689.  
  1690. if (dTarget === true) dTarget = kRef(ytdFlexy); // major mutation occurance
  1691. else if (dTarget === kRef(comments_section_loaded_elm) && wAddP > wRemoveP) return true; // ignore if comments are loaded (adding comments)
  1692. else if (isMtoOverallSkip(dTarget)) return; // allow for multiple mutations at the same time - determinated after looping
  1693.  
  1694.  
  1695.  
  1696. // 4 ~ 16 times per full page loading
  1697.  
  1698. Q.addP += wAddP;
  1699. Q.removeP += wRemoveP;
  1700.  
  1701. if (Q.mutationTarget === null) Q.mutationTarget = dTarget;
  1702. else if (Q.mutationTarget != dTarget) Q.mutationTarget = kRef(ytdFlexy);
  1703.  
  1704. //console.log(prettyElm(dTarget), wAddP , wRemoveP, mtoInterval)
  1705. //console.log(prettyElm(dTarget), reg.map(m=>prettyElm(m.target)))
  1706. //console.log(7015, performance.now())
  1707.  
  1708. Q.mtoNav_requestNo++;
  1709. if (Q.mtoNav_requestNo == 1) setTimeout(FP.mtoNav_delayedF, mtoInterval);
  1710.  
  1711. },
  1712.  
  1713.  
  1714. mtoBodyF: function(mutations, observer) {
  1715. if (!scriptEnable) return;
  1716.  
  1717. for (const mutation of mutations) {
  1718. for (const addedNode of mutation.addedNodes)
  1719. if (addedNode.nodeType === 1) {
  1720. if (addedNode.nodeName == "DIV" && addedNode.className.indexOf('autocomplete-suggestions') >= 0) {
  1721. mtf_fixAutoCompletePosition(addedNode)
  1722. }
  1723. }
  1724. }
  1725.  
  1726. },
  1727.  
  1728. mtf_attrPlaylist: (mutations, observer) => {
  1729.  
  1730. if (!scriptEnable) return;
  1731. let cssElm = kRef(ytdFlexy);
  1732. if (!cssElm) return;
  1733.  
  1734. var playlist = document.querySelector('ytd-playlist-panel-renderer#playlist')
  1735. const tabBtn = document.querySelector('[userscript-tab-content="#tab-list"]');
  1736. if (tabBtn) {
  1737. //console.log('attr playlist changed')
  1738. if (tabBtn.classList.contains('tab-btn-hidden') && !playlist.hasAttribute('hidden')) {
  1739. //console.log('attr playlist changed - no hide')
  1740. tabBtn.classList.remove("tab-btn-hidden");
  1741. } else if (!tabBtn.classList.contains('tab-btn-hidden') && playlist.hasAttribute('hidden')) {
  1742. //console.log('attr playlist changed - add hide')
  1743. hideTabBtn(tabBtn);
  1744. }
  1745. }
  1746. /* visible layout for triggering hidden removal */
  1747. akAttr(cssElm, 'tabview-youtube-playlist', playlist.hasAttribute('hidden'));
  1748. },
  1749. delayed_disableComments: function() {
  1750.  
  1751. let ytdFlexyElm = kRef(ytdFlexy);
  1752. if (!scriptEnable || !ytdFlexyElm) return;
  1753.  
  1754. if (status_commentsHidden() == 2) _disableComments();
  1755.  
  1756. },
  1757. mtf_attrComments: (mutations, observer) => {
  1758.  
  1759. let ytdFlexyElm = kRef(ytdFlexy);
  1760. if (!scriptEnable || !ytdFlexyElm) return;
  1761.  
  1762. var comments = document.querySelector('ytd-comments#comments')
  1763. const tabBtn = document.querySelector('[userscript-tab-content="#tab-comments"]');
  1764. if (!comments || !tabBtn) return;
  1765. let isCommentHidden = comments.hasAttribute('hidden')
  1766. //console.log('attr comments changed')
  1767.  
  1768.  
  1769. timeout_attrComments.clear();
  1770. $('span#tab3-txt-loader').text('');
  1771. mtoInterval = mtoInterval1;
  1772.  
  1773. if (!isCommentHidden) {
  1774.  
  1775. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'K');
  1776.  
  1777. //console.log('attr comments changed - no hide')
  1778. tabBtn.classList.remove("tab-btn-hidden") //if contains
  1779.  
  1780. makeBodyScroll();
  1781. Q.fetchedOnce = false
  1782. FOnce.mtf_fetchCommentsAvailable = FP.mtf_fetchCommentsAvailable;
  1783. if (Q.mutationTarget === null) $callOnceAsync('mtf_fetchCommentsAvailable');
  1784.  
  1785. window.requestAnimationFrame(() => {
  1786. let innerCommentsLoaderRet = innerCommentsLoader();
  1787. if (innerCommentsLoaderRet) innerCommentsLoaderRet.f();
  1788. })
  1789.  
  1790. } else if (isCommentHidden) {
  1791.  
  1792.  
  1793. //console.log('attr comments changed - add hide')
  1794.  
  1795. akAttr(ytdFlexyElm, 'tabview-youtube-comments', true, 'K');
  1796.  
  1797. let t = status_commentsHidden() == 2 ? 1630 : 760;
  1798.  
  1799. timeout_attrComments.set(FP.delayed_disableComments, t);
  1800.  
  1801. }
  1802.  
  1803. requestingComments = comments;
  1804. scrollForComments();
  1805. setTimeout(() => nativeFunc(comments, "loadComments"), 20)
  1806.  
  1807.  
  1808. },
  1809.  
  1810.  
  1811. mtf_attrChatroom: (mutations, observer) => {
  1812. let ytdFlexyElm = kRef(ytdFlexy);
  1813. if (!scriptEnable || !ytdFlexyElm) return;
  1814.  
  1815. layoutStatusMutex.lockWith(unlock => {
  1816.  
  1817. const chatBlock = document.querySelector('ytd-live-chat-frame#chat')
  1818. const cssElm = kRef(ytdFlexy)
  1819.  
  1820. if (!chatBlock || !cssElm) {
  1821. unlock();
  1822. return;
  1823. }
  1824.  
  1825. if (!cssElm.hasAttribute('userscript-chatblock')) wAttr(cssElm, 'userscript-chatblock', true);
  1826. let isCollapsed = !!chatBlock.hasAttribute('collapsed');
  1827. wAttr(cssElm, 'userscript-chat-collapsed', isCollapsed);
  1828.  
  1829. if (cssElm.hasAttribute('userscript-chatblock') && !isCollapsed) lastShowTab = '#chatroom';
  1830.  
  1831. if (!isCollapsed && document.querySelector('#right-tabs .tab-btn.active') && isWideScreenWithTwoColumns() && !isTheater()) {
  1832. switchTabActivity(null);
  1833. setTimeout(unlock, 40);
  1834. } else {
  1835. unlock();
  1836. }
  1837.  
  1838. if (!isCollapsed) {
  1839. runAfterExpandChat();
  1840. } else {
  1841. chatBlock.removeAttribute('yt-userscript-iframe-loaded');
  1842. }
  1843.  
  1844. })
  1845.  
  1846.  
  1847.  
  1848.  
  1849. },
  1850.  
  1851. mtf_attrEngagementPanel: (mutations, observer) => {
  1852. let ytdFlexyElm = kRef(ytdFlexy);
  1853. if (!scriptEnable || !ytdFlexyElm) return;
  1854.  
  1855. //multiple instance
  1856. if (mutations) {
  1857. let cPanels = null;
  1858. for (const mutation of mutations) {
  1859. let ePanel = mutation.target;
  1860. if (ePanel.getAttribute('visibility') == 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED') {
  1861. cPanels = cPanels || engagement_panels_();
  1862. for (const entry of cPanels.list) {
  1863. if (entry.ePanel != ePanel && entry.visible) ytBtnCloseEngagementPanel(entry.ePanel);
  1864. }
  1865. }
  1866. }
  1867. }
  1868.  
  1869. layoutStatusMutex.lockWith(unlock => {
  1870.  
  1871. const ePanel = document.querySelector('ytd-watch-flexy ytd-engagement-panel-section-list-renderer')
  1872. const cssElm = kRef(ytdFlexy)
  1873.  
  1874. if (!ePanel || !cssElm) {
  1875. unlock();
  1876. return;
  1877. }
  1878. let previousValue = +cssElm.getAttribute('userscript-engagement-panel') || 0;
  1879.  
  1880. let { value, count } = engagement_panels_();
  1881. let nextValue = value;
  1882. let nextCount = count;
  1883.  
  1884.  
  1885. if (nextCount == 0 && cssElm.hasAttribute('userscript-engagement-panel')) {
  1886. wAttr(cssElm, 'userscript-engagement-panel', false);
  1887. unlock();
  1888. } else {
  1889.  
  1890. if ((nextCount > 1) || (cssElm.hasAttribute('userscript-engagement-panel') && previousValue === nextValue)) {
  1891. unlock();
  1892. return;
  1893. }
  1894.  
  1895. cssElm.setAttribute('userscript-engagement-panel', nextValue);
  1896.  
  1897. let b = false;
  1898. if (previousValue != nextValue && nextValue > 0) {
  1899. lastShowTab = `#engagement-panel-${nextValue}`;
  1900. b = true;
  1901. }
  1902.  
  1903. if (b && document.querySelector('#right-tabs .tab-btn.active') && isWideScreenWithTwoColumns() && !isTheater()) {
  1904. switchTabActivity(null);
  1905. setTimeout(unlock, 40);
  1906. } else {
  1907. unlock();
  1908. }
  1909. }
  1910.  
  1911. })
  1912.  
  1913.  
  1914.  
  1915.  
  1916. },
  1917.  
  1918. mtf_initalAttr_playlist: () => {
  1919. let ytdFlexyElm = kRef(ytdFlexy);
  1920. if (!scriptEnable || !ytdFlexyElm) return true;
  1921.  
  1922. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1923.  
  1924. var playlist = rootElement.querySelector('ytd-playlist-panel-renderer#playlist')
  1925. if (!playlist) return true;
  1926. initMutationObserver(mtoVs, 'mtoVisibility_Playlist', FP.mtf_attrPlaylist).observe(playlist, {
  1927. attributes: true,
  1928. attributeFilter: ['hidden'],
  1929. attributeOldValue: true
  1930. })
  1931. FP.mtf_attrPlaylist()
  1932. return false;
  1933. },
  1934.  
  1935. mtf_initalAttr_comments: () => {
  1936. let ytdFlexyElm = kRef(ytdFlexy);
  1937. if (!scriptEnable || !ytdFlexyElm) return true;
  1938.  
  1939. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1940.  
  1941. var comments = rootElement.querySelector('ytd-comments#comments')
  1942. if (!comments) return true;
  1943. initMutationObserver(mtoVs, 'mtoVisibility_Comments', FP.mtf_attrComments).observe(comments, {
  1944. attributes: true,
  1945. attributeFilter: ['hidden'],
  1946. attributeOldValue: true
  1947. })
  1948. FP.mtf_attrComments()
  1949. requestingComments = comments;
  1950. //scrollForComments()
  1951. setTimeout(() => nativeFunc(comments, "loadComments"), 20)
  1952. return false;
  1953. },
  1954.  
  1955. mtf_initalAttr_chatroom: () => {
  1956. let ytdFlexyElm = kRef(ytdFlexy);
  1957. if (!scriptEnable || !ytdFlexyElm) return true;
  1958.  
  1959. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1960.  
  1961. var chatroom = rootElement.querySelector('ytd-live-chat-frame#chat')
  1962. if (!chatroom) return true;
  1963. initMutationObserver(mtoVs, 'mtoVisibility_Chatroom', FP.mtf_attrChatroom).observe(chatroom, {
  1964. attributes: true,
  1965. attributeFilter: ['collapsed'],
  1966. attributeOldValue: true
  1967. })
  1968. FP.mtf_attrChatroom()
  1969. return false;
  1970. },
  1971.  
  1972. mtf_initalAttr_engagement_panel: () => {
  1973. let ytdFlexyElm = kRef(ytdFlexy);
  1974. if (!scriptEnable || !ytdFlexyElm) return true;
  1975.  
  1976. const rootElement = Q.mutationTarget || ytdFlexyElm;
  1977.  
  1978. let toCheck = false;
  1979. for (const engagement_panel of rootElement.querySelectorAll('ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([tabview-attr-checked])')) {
  1980.  
  1981. engagement_panel.setAttribute('tabview-attr-checked', '');
  1982. let mto = mtoVs.mtoVisibility_EngagementPanel;
  1983. if (!mto) mto = initMutationObserver(mtoVs, 'mtoVisibility_EngagementPanel', FP.mtf_attrEngagementPanel);
  1984. mto.observe(engagement_panel, {
  1985. attributes: true,
  1986. attributeFilter: ['visibility'],
  1987. attributeOldValue: true
  1988. })
  1989. toCheck = true;
  1990. }
  1991.  
  1992. if (toCheck) FP.mtf_attrEngagementPanel()
  1993.  
  1994. return true;
  1995. },
  1996.  
  1997. mtf_checkDescriptionLoaded: () => {
  1998.  
  1999. let ytdFlexyElm = kRef(ytdFlexy);
  2000. if (!scriptEnable || !ytdFlexyElm) return true;
  2001.  
  2002. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2003.  
  2004. const expander = document.querySelector("#meta-contents ytd-expander");
  2005. if (!expander) return true;
  2006. $(expander).appendTo("#tab-info").attr('data-dom-changed-by-tabview-youtube', scriptVersionForExternal)
  2007.  
  2008. const avatar = document.querySelector('#meta-contents yt-img-shadow#avatar');
  2009. if (avatar) hackImgShadow(avatar)
  2010. return false;
  2011.  
  2012. },
  2013.  
  2014.  
  2015. //live-chat / chat-replay
  2016.  
  2017. fireOnce_forceCheckLiveVideo_tf: () => {
  2018.  
  2019. let ytdFlexyElm = kRef(ytdFlexy);
  2020. if (!scriptEnable || !ytdFlexyElm) return;
  2021.  
  2022. let elm = document.querySelector('#ytd-player .ytp-time-display');
  2023. if (elm && elm.classList.contains('ytp-live')) {
  2024. //console.log(7006)
  2025. ytdFlexyElm.setAttribute('userscript-chatblock', 'chat-live')
  2026. //disableComments_LiveChat();
  2027. }
  2028. },
  2029.  
  2030. mtf_forceCheckLiveVideo: () => {
  2031. let ytdFlexyElm = kRef(ytdFlexy);
  2032. if (!scriptEnable || !ytdFlexyElm) return true;
  2033.  
  2034. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2035. const playerLabel = document.querySelector('#ytd-player .ytp-time-display') && document.querySelector('ytd-live-chat-frame#chat')
  2036. if (!playerLabel) return true;
  2037. setTimeout(FP.fireOnce_forceCheckLiveVideo_tf, 170)
  2038. return false;
  2039. },
  2040.  
  2041. //comments
  2042.  
  2043. mtf_advancedComments: () => {
  2044.  
  2045. let ytdFlexyElm = kRef(ytdFlexy);
  2046. if (!scriptEnable || !ytdFlexyElm) return true;
  2047.  
  2048. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2049. const continuations = document.querySelector("ytd-comments#comments #continuations");
  2050. if (!continuations) return true;
  2051. requestingComments = document.querySelector('ytd-comments#comments');
  2052. scrollForComments();
  2053. return false;
  2054. },
  2055.  
  2056. mtf_fetchCommentsAvailable: () => {
  2057.  
  2058. let ytdFlexyElm = kRef(ytdFlexy);
  2059. if (!scriptEnable || !ytdFlexyElm) return true;
  2060.  
  2061. let innerCommentsLoaderRet = innerCommentsLoader();
  2062. if (!innerCommentsLoaderRet) return true;
  2063.  
  2064. innerCommentsLoaderRet.f();
  2065. fetchCommentsFinished();
  2066. return false;
  2067.  
  2068. }
  2069.  
  2070.  
  2071. }
  2072.  
  2073.  
  2074.  
  2075.  
  2076. function initObserver() {
  2077.  
  2078. Q.addP = 0;
  2079. Q.removeP = 0;
  2080. Q.mutationTarget = null;
  2081.  
  2082. Q.mtoNav_requestNo = 0;
  2083.  
  2084. initMutationObserver(mtoCs, 'mtoNav', FP.mtoNavF).observe(kRef(ytdFlexy), {
  2085. subtree: true,
  2086. childList: true,
  2087. attributes: false
  2088. });
  2089.  
  2090. -
  2091. (async () => {
  2092. Q.addP = 1; //force all checking
  2093. Q.mtoNav_requestNo++;
  2094. if (Q.mtoNav_requestNo == 1) FP.mtoNav_delayedF();
  2095. })();
  2096.  
  2097. // for automcomplete plugin
  2098. initMutationObserver(mtoCs, 'mtoBody', FP.mtoBodyF).observe(document.querySelector('body'), {
  2099. childList: true,
  2100. subtree: false,
  2101. attributes: false
  2102. })
  2103.  
  2104.  
  2105. }
  2106.  
  2107. let displayedPlaylist = null;
  2108. let scrollingVideosList = null;
  2109.  
  2110. let scriptEnable = false;
  2111. let scriptEC = 0;
  2112. let lastShowTab = null;
  2113.  
  2114. let _cachedLastVideo = null;
  2115. let videoListBeforeSearch = null;
  2116. let no_fix_contents_until = 0;
  2117. let no_fix_playlist_until = 0;
  2118. let statusCollasped = 0;
  2119.  
  2120. let ytdFlexy = null;
  2121. let timeout_attrComments = new Timeout();
  2122.  
  2123. function pluginHook() {
  2124.  
  2125. scriptEnable = true;
  2126. scriptEC++;
  2127.  
  2128. no_fix_contents_until = 0;
  2129. no_fix_playlist_until = 0;
  2130.  
  2131. ytdFlexy = mWeakRef(document.querySelector('ytd-watch-flexy'))
  2132.  
  2133. }
  2134.  
  2135. function pluginUnhook() {
  2136.  
  2137. //console.log(8001)
  2138. timeout_attrComments.clear();
  2139.  
  2140. videoListBeforeSearch = null;
  2141. statusCollasped = 0;
  2142. _cachedLastVideo = null;
  2143. lastShowTab = null;
  2144. displayedPlaylist = null;
  2145. scrollingVideosList = null;
  2146. scriptEnable = false;
  2147. scriptEC++;
  2148. if (scriptEC > 788888888) scriptEC = 188888888;
  2149. ytdFlexy = null;
  2150. wls.layoutStatus = null;
  2151.  
  2152. clearMutationObserver(mtoVs, 'mtoVisibility_Playlist')
  2153. clearMutationObserver(mtoVs, 'mtoVisibility_Comments')
  2154. clearMutationObserver(mtoVs, 'mtoVisibility_Chatroom')
  2155. clearMutationObserver(mtoVs, 'mtoFlexyAttr')
  2156.  
  2157. clearMutationObserver(mtoCs, 'mtoBody')
  2158. if (clearMutationObserver(mtoCs, 'mtoNav')) {
  2159. FOnce.mtf_checkFlexy = null;
  2160. FOnce.mtf_initalAttr_comments = null;
  2161. FOnce.mtf_initalAttr_playlist = null;
  2162. FOnce.mtf_initalAttr_chatroom = null;
  2163. FOnce.mtf_initalAttr_engagement_panel = null;
  2164. FOnce.mtf_advancedComments = null;
  2165. FOnce.mtf_checkDescriptionLoaded = null;
  2166. FOnce.mtf_fetchCommentsAvailable = null;
  2167. FOnce.mtf_forceCheckLiveVideo = null;
  2168. Q.mtf_chatBlockQ = null;
  2169. }
  2170.  
  2171. mtoInterval = mtoInterval1;
  2172.  
  2173. }
  2174.  
  2175. let comments_section_loaded_elm = null;
  2176.  
  2177.  
  2178. function initializeForVideoChange() {
  2179.  
  2180.  
  2181.  
  2182. pluginUnhook();
  2183. if (!document.querySelector('script#userscript-tabview-injection-1')) {
  2184.  
  2185. if (isMyScriptInChromeRuntime())
  2186. addScriptByURL(window.chrome.runtime.getURL('js/injection_script_1.js')).id = 'userscript-tabview-injection-1';
  2187. else
  2188. addScript(`!!(${injection_script_1+""})()`).id = 'userscript-tabview-injection-1'
  2189. // addScriptByURL(`${githubURLBase}/${githubURLCommit}/js/injection_script_1.js`).id='userscript-tabview-injection-1';
  2190.  
  2191. }
  2192. var prevComemnts = document.querySelector('ytd-comments#comments');
  2193.  
  2194. if (prevComemnts && prevComemnts.matches('[hidden]')) {
  2195.  
  2196. // assumption: loading comments after executation of this function which removes the attribute [hidden] of #ytd-comments#comments
  2197.  
  2198. var prevCommentsHeader = prevComemnts.querySelector('ytd-comments#comments ytd-comments-header-renderer');
  2199. var prevCommentsMsg = prevComemnts.querySelector('ytd-item-section-renderer#sections #header ~ #contents>ytd-message-renderer');
  2200.  
  2201. //removed any cache of #comments header (i.e. count message)
  2202. if (prevCommentsHeader) prevCommentsHeader.parentNode.removeChild(prevCommentsHeader);
  2203.  
  2204. //removed any cache of #comments message (i.e. 留言功能已停用。)
  2205. if (prevCommentsMsg) prevCommentsMsg.parentNode.removeChild(prevCommentsMsg);
  2206.  
  2207.  
  2208.  
  2209. }
  2210.  
  2211.  
  2212. window.requestAnimationFrame(() => {
  2213.  
  2214. // requestAnimationFrame is required to let youtube coding running first !
  2215.  
  2216. pluginHook();
  2217.  
  2218. _onNavigationEnd();
  2219.  
  2220. setTimeout(() => {
  2221.  
  2222. //ensure comment tab text is updated - no matter there is change of video or not
  2223. let innerCommentsLoaderRet = innerCommentsLoader();
  2224. if (innerCommentsLoaderRet) innerCommentsLoaderRet.f();
  2225.  
  2226. }, 40);
  2227.  
  2228.  
  2229. })
  2230.  
  2231.  
  2232. return true;
  2233.  
  2234. }
  2235.  
  2236. function getTabsHTML() {
  2237.  
  2238. const sTabBtnVideos = `${svgElm(16,16,298,298,svgVideos)}<span>Videos</span>`
  2239. const sTabBtnInfo = `${svgElm(16,16,23.625,23.625,svgInfo)}<span>Info</span>`
  2240. const sTabBtnPlayList = `${svgElm(16,16,426.667,426.667,svgPlayList)}<span>Playlist</span>`
  2241.  
  2242. let str1 = `
  2243. <paper-ripple class="style-scope yt-icon-button">
  2244. <div id="background" class="style-scope paper-ripple" style="opacity:0;"></div>
  2245. <div id="waves" class="style-scope paper-ripple"></div>
  2246. </paper-ripple>
  2247. `;
  2248.  
  2249. const str_tabs = [
  2250. `<a id="tab-btn1" data-name="info" userscript-tab-content="#tab-info" class="tab-btn">${sTabBtnInfo}${str1}</a>`,
  2251. `<a id="tab-btn2" userscript-tab-content="#tab-live" class="tab-btn tab-btn-hidden">Chat${str1}</a>`,
  2252. `<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}</a>`,
  2253. `<a id="tab-btn4" userscript-tab-content="#tab-videos" data-name="videos" class="tab-btn">${sTabBtnVideos}${str1}</a>`,
  2254. `<a id="tab-btn5" userscript-tab-content="#tab-list" class="tab-btn">${sTabBtnPlayList}${str1}</a>`
  2255. ].join('')
  2256.  
  2257. var addHTML = `
  2258. <div id="right-tabs">
  2259. <header>
  2260. <div id="material-tabs">
  2261. ${str_tabs}
  2262. </div>
  2263. </header>
  2264. <div class="tab-content">
  2265. <div id="tab-info" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2266. <div id="tab-live" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2267. <div id="tab-comments" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2268. <div id="tab-videos" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2269. <div id="tab-list" class="tab-content-cld tab-content-hidden" userscript-scrollbar-render></div>
  2270. </div>
  2271. </div>
  2272. `;
  2273.  
  2274. return addHTML
  2275.  
  2276. }
  2277.  
  2278.  
  2279. function injection_script_1() {
  2280.  
  2281. document.addEventListener('userscript-call-dom-func', function(evt) {
  2282.  
  2283. if (!evt || !evt.target || !evt.detail) return;
  2284. let dom = evt.target;
  2285.  
  2286. let { property, args } = evt.detail;
  2287. if (!property) return;
  2288. let f = dom[property];
  2289. if (typeof f != 'function') return;
  2290.  
  2291. if (args && args.length > 0) f.apply(dom, args);
  2292. else f.call(dom);
  2293.  
  2294. }, true)
  2295.  
  2296. }
  2297.  
  2298. function _onNavigationEnd() {
  2299.  
  2300. let timeoutR_findRelated = new Timeout();
  2301. timeoutR_findRelated.set(function() {
  2302. let related = kRef(ytdFlexy).querySelector("#related");
  2303. if (!related) return true;
  2304. foundRelated(related);
  2305. }, 100, 10)
  2306.  
  2307. function foundRelated(related) {
  2308. let promise = Promise.resolve();
  2309. if (!document.querySelector("#right-tabs")) {
  2310. promise = promise.then(() => {
  2311. $(getTabsHTML()).insertBefore(related).attr('data-dom-created-by-tabview-youtube', scriptVersionForExternal);
  2312. })
  2313. }
  2314. promise.then(runAfterTabAppended).then(initObserver)
  2315. }
  2316.  
  2317. setTimeout(() => {
  2318. for (const s of document.querySelectorAll('#right-tabs [userscript-scrollbar-render]')) {
  2319. Promise.resolve(s).then(s => {
  2320. if (s && s.scrollTop > 0) s.scrollTop = 0;
  2321. let child = s.firstElementChild;
  2322. if (child && child.scrollTop > 0) child.scrollTop = 0;
  2323. });
  2324. }
  2325. }, 90)
  2326.  
  2327. }
  2328.  
  2329. function onNavigationEnd(evt) {
  2330.  
  2331. pluginUnhook(); // in case not triggered by popstate - say mini playing
  2332.  
  2333. $('span#tab3-txt-loader').text('');
  2334. setCommentSection(0)
  2335.  
  2336. if (!/^https?\:\/\/(\w+\.)*youtube\.com\/watch\?(\w+\=[^\/\?\&]+\&|\w+\=?\&)*v=[\w\-\_]+/.test(window.location.href)) return;
  2337.  
  2338.  
  2339. let timeout = 4; // max. 4 animation frames
  2340.  
  2341. let tf = () => {
  2342. if (--timeout > 0 && !document.querySelector('#player video')) return requestAnimationFrame(tf);
  2343.  
  2344. initializeForVideoChange();
  2345. pluginHook();
  2346. _onNavigationEnd();
  2347.  
  2348. }
  2349.  
  2350.  
  2351. tf();
  2352.  
  2353.  
  2354.  
  2355.  
  2356. }
  2357.  
  2358. function setToActiveTab(defaultTab) {
  2359. if (isTheater() && isWideScreenWithTwoColumns()) return;
  2360. const jElm = document.querySelector(`a[userscript-tab-content="${switchTabActivity_lastTab}"]:not(.tab-btn-hidden)`) ||
  2361. document.querySelector(`a[userscript-tab-content="${(defaultTab||settings.defaultTab)}"]:not(.tab-btn-hidden)`) ||
  2362. document.querySelector("a[userscript-tab-content]:not(.tab-btn-hidden)") ||
  2363. null;
  2364. switchTabActivity(jElm);
  2365. return !!jElm;
  2366. }
  2367.  
  2368. function getWrapper(wrapperId) {
  2369. let $wrapper = $(`#${wrapperId}`);
  2370. if (!$wrapper[0]) $wrapper = $(`<div id="${wrapperId}"></div>`)
  2371. return $wrapper.first();
  2372. }
  2373.  
  2374. function runAfterTabAppended() {
  2375.  
  2376. document.documentElement.setAttribute('plugin-tabview-youtube', '')
  2377.  
  2378. const cssElm = kRef(ytdFlexy)
  2379. if (cssElm && !cssElm.hasAttribute('tabview-selection')) cssElm.setAttribute('tabview-selection', '')
  2380.  
  2381.  
  2382. // append the next videos
  2383. // it exists as "related" is already here
  2384. fixTabs();
  2385.  
  2386. // just switch to the default tab
  2387. setToActiveTab();
  2388.  
  2389.  
  2390. prepareTabBtn();
  2391.  
  2392.  
  2393. // append the detailed meta contents to the tab-info
  2394. FOnce.mtf_checkDescriptionLoaded = FP.mtf_checkDescriptionLoaded;
  2395. if (Q.mutationTarget === null) $callOnceAsync('mtf_checkDescriptionLoaded');
  2396.  
  2397. // force window scroll when #continuations is first detected and #comments still [hidden]
  2398. FOnce.mtf_advancedComments = FP.mtf_advancedComments;
  2399. if (Q.mutationTarget === null) $callOnceAsync('mtf_advancedComments');
  2400.  
  2401. // use video player's element to detect the live-chat situation (no commenting section)
  2402. // 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
  2403. FOnce.mtf_forceCheckLiveVideo = FP.mtf_forceCheckLiveVideo;
  2404. if (Q.mutationTarget === null) $callOnceAsync('mtf_forceCheckLiveVideo');
  2405.  
  2406.  
  2407. // Attr Mutation Observer - #playlist - hidden
  2408. clearMutationObserver(mtoVs, 'mtoVisibility_Playlist')
  2409. // Attr Mutation Observer callback - #playlist - hidden
  2410.  
  2411. // pending for #playlist and set Attribute Observer
  2412. FOnce.mtf_initalAttr_playlist = FP.mtf_initalAttr_playlist
  2413. if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_playlist');
  2414.  
  2415. // Attr Mutation Observer - ytd-comments#comments - hidden
  2416. clearMutationObserver(mtoVs, 'mtoVisibility_Comments')
  2417. // Attr Mutation Observer callback - ytd-comments#comments - hidden
  2418.  
  2419. // pending for #comments and set Attribute Observer
  2420. FOnce.mtf_initalAttr_comments = FP.mtf_initalAttr_comments;
  2421. if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_comments');
  2422.  
  2423.  
  2424. clearMutationObserver(mtoVs, 'mtoVisibility_Chatroom');
  2425. FOnce.mtf_initalAttr_chatroom = FP.mtf_initalAttr_chatroom
  2426. if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_chatroom');
  2427.  
  2428. clearMutationObserver(mtoVs, 'mtoVisibility_EngagementPanel');
  2429. for (const engagement_panel of document.querySelectorAll('ytd-watch-flexy ytd-engagement-panel-section-list-renderer:not([tabview-attr-checked])')) {
  2430. engagement_panel.removeAttribute('tabview-attr-checked');
  2431. }
  2432. FOnce.mtf_initalAttr_engagement_panel = FP.mtf_initalAttr_engagement_panel
  2433. if (Q.mutationTarget === null) $callOnceAsync('mtf_initalAttr_engagement_panel');
  2434.  
  2435.  
  2436. flexyAttrInit();
  2437.  
  2438. document.querySelector("#right-tabs .tab-content").addEventListener('scroll', makeBodyScrollByEvt, true);
  2439.  
  2440. }
  2441.  
  2442.  
  2443. function fetchCommentsFinished() {
  2444. let ytdFlexyElm = kRef(ytdFlexy);
  2445. if (!scriptEnable || !ytdFlexyElm) return;
  2446. timeout_attrComments.clear();
  2447. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'LS')
  2448. }
  2449.  
  2450. function setCommentSection(value) {
  2451. Q.comments_section_loaded = value;
  2452.  
  2453. if (value === 0) {
  2454. comments_section_loaded_elm = null;
  2455. }
  2456.  
  2457. }
  2458.  
  2459. function _disableComments() {
  2460.  
  2461. if (!scriptEnable) return;
  2462. let cssElm = kRef(ytdFlexy);
  2463. if (!cssElm) return;
  2464.  
  2465. mtoInterval = mtoInterval2;
  2466. setCommentSection(2);
  2467.  
  2468. comments_section_loaded_elm = mWeakRef(document.querySelector('ytd-comments#comments div#contents') || null)
  2469.  
  2470. let tabBtn = document.querySelector('.tab-btn[userscript-tab-content="#tab-comments"]');
  2471. if (tabBtn && !tabBtn.classList.contains('tab-btn-hidden')) {
  2472. hideTabBtn(tabBtn)
  2473. }
  2474.  
  2475. akAttr(cssElm, 'tabview-youtube-comments', true, 'D');
  2476. FOnce.mtf_fetchCommentsAvailable = null;
  2477.  
  2478.  
  2479. }
  2480.  
  2481.  
  2482.  
  2483.  
  2484. let layoutStatusMutex = new Mutex();
  2485.  
  2486. function forceDisplayChatReplay() {
  2487. let items = chatFrameElement('yt-live-chat-item-list-renderer #items');
  2488. if (items && items.childElementCount !== 0) return;
  2489.  
  2490. let ytd_player = document.querySelector('ytd-player#ytd-player');
  2491. if (!ytd_player) return;
  2492. let videoElm = ytd_player.querySelector('video');
  2493. if (!videoElm) return;
  2494.  
  2495. let video = videoElm;
  2496. if (videoElm && video.currentTime > 0 && !video.ended && video.readyState > video.HAVE_CURRENT_DATA) {
  2497. let chat = document.querySelector('ytd-live-chat-frame#chat');
  2498. if (chat) {
  2499. nativeFunc(chat, "postToContentWindow", [{ "yt-player-video-progress": videoElm.currentTime }])
  2500. }
  2501. }
  2502.  
  2503. }
  2504.  
  2505.  
  2506.  
  2507. function runAfterExpandChat() {
  2508.  
  2509.  
  2510.  
  2511. new Promise(resolve => {
  2512.  
  2513.  
  2514. let chatFrame_st = Date.now();
  2515. let cid_chatFrameCheck = 0;
  2516.  
  2517. let sEF = new ScriptEF();
  2518. cid_chatFrameCheck = setInterval(() => {
  2519. if (!sEF.isValid()) return cid_chatFrameCheck = clearInterval(cid_chatFrameCheck);
  2520. let cDoc = chatFrameContentDocument();
  2521. if (cDoc) {
  2522. cid_chatFrameCheck = clearInterval(cid_chatFrameCheck);
  2523. resolve();
  2524. } else if (!scriptEnable || !isChatExpand() || Date.now() - chatFrame_st > 6750) {
  2525. cid_chatFrameCheck = clearInterval(cid_chatFrameCheck);
  2526. }
  2527. }, 60);
  2528.  
  2529.  
  2530. }).then(() => new Promise(resolve => {
  2531.  
  2532.  
  2533.  
  2534.  
  2535. let timeoutR_ChatAppReady = new Timeout();
  2536. timeoutR_ChatAppReady.set(() => {
  2537.  
  2538. if (!scriptEnable || !isChatExpand()) return false;
  2539. let app = chatFrameElement('yt-live-chat-app');
  2540. if (!app) return true;
  2541.  
  2542.  
  2543. setTimeout(() => resolve(app), 40)
  2544.  
  2545.  
  2546. }, 40, 150); //40*150 = 6000ms = 6s;
  2547.  
  2548.  
  2549.  
  2550.  
  2551. })).then(app => {
  2552.  
  2553.  
  2554. let cDoc = app.ownerDocument;
  2555.  
  2556. if (!scriptEnable || !isChatExpand()) return;
  2557. addStyle(`
  2558. body #input-panel.yt-live-chat-renderer::after {
  2559. background: transparent;
  2560. }
  2561. #items.yt-live-chat-item-list-renderer{
  2562. contain: content;
  2563. }
  2564. yt-live-chat-text-message-renderer{
  2565. contain: content;
  2566. }
  2567. #item-offset.yt-live-chat-item-list-renderer{
  2568. contain: content;
  2569. }
  2570. #item-scroller.yt-live-chat-item-list-renderer{
  2571. contain: strict;
  2572. }
  2573. img[width][height]{
  2574. contain: strict;
  2575. }
  2576. #item-list>yt-live-chat-item-list-renderer, #item-list>yt-live-chat-item-list-renderer>#contents{
  2577. contain: strict;
  2578. }
  2579. yt-live-chat-app{
  2580. contain: content;
  2581. }
  2582. `, cDoc.documentElement)
  2583.  
  2584. if (cDoc.querySelector('yt-live-chat-renderer #continuations')) {
  2585. setTimeout(() => mtf_ChatExist(), 40);
  2586. $(document.querySelector('ytd-live-chat-frame#chat')).attr('yt-userscript-iframe-loaded', '')
  2587. }
  2588.  
  2589. forceDisplayChatReplay();
  2590.  
  2591.  
  2592.  
  2593.  
  2594. })
  2595.  
  2596. }
  2597.  
  2598.  
  2599. function flexyAttrInit() {
  2600.  
  2601.  
  2602. clearMutationObserver(mtoVs, 'mtoFlexyAttr')
  2603.  
  2604. function toggleFlag(mFlag, b, flag) {
  2605. if (b) mFlag = mFlag | flag;
  2606. else mFlag = mFlag & ~flag;
  2607. return mFlag;
  2608. }
  2609.  
  2610. function toLayoutStatus(nls, attributeName) {
  2611.  
  2612. let attrElm, b, v;
  2613. switch (attributeName) {
  2614. case 'theater':
  2615. nls = toggleFlag(nls, isTheater(), LAYOUT_THEATER);
  2616. break;
  2617. case 'userscript-chat-collapsed':
  2618. case 'userscript-chatblock':
  2619. attrElm = kRef(ytdFlexy);
  2620. if (hasAttribute(attrElm, 'userscript-chat-collapsed')) {
  2621. nls = toggleFlag(nls, true, LAYOUT_CHATROOM | LAYOUT_CHATROOM_COLLASPED);
  2622. } else {
  2623. nls = toggleFlag(nls, hasAttribute(attrElm, 'userscript-chatblock'), LAYOUT_CHATROOM);
  2624. nls = toggleFlag(nls, false, LAYOUT_CHATROOM_COLLASPED);
  2625. }
  2626. break;
  2627. case 'is-two-columns_':
  2628. nls = toggleFlag(nls, isWideScreenWithTwoColumns(), LAYOUT_TWO_COLUMNS);
  2629. break;
  2630.  
  2631. case 'tabview-selection':
  2632. b = isNonEmptyString(kRef(ytdFlexy).getAttribute('tabview-selection'));
  2633. nls = toggleFlag(nls, b, LAYOUT_TAB_EXPANDED);
  2634. break;
  2635.  
  2636. case 'fullscreen':
  2637. b = isNonEmptyString(kRef(ytdFlexy).getAttribute('fullscreen'));
  2638. nls = toggleFlag(nls, b, LAYOUT_FULLSCREEN);
  2639. break;
  2640.  
  2641. case 'userscript-engagement-panel':
  2642. v = kRef(ytdFlexy).getAttribute('userscript-engagement-panel');
  2643. b = (+v > 0)
  2644. nls = toggleFlag(nls, b, LAYOUT_ENGAGEMENT_PANEL_EXPAND);
  2645. break;
  2646.  
  2647. }
  2648.  
  2649. return nls;
  2650.  
  2651.  
  2652. }
  2653.  
  2654. let mtf_attrFlexy = (mutations, observer) => {
  2655.  
  2656. if (!scriptEnable) return;
  2657.  
  2658.  
  2659. const cssElm = kRef(ytdFlexy)
  2660. if (!cssElm) return;
  2661.  
  2662. if (!mutations) return;
  2663.  
  2664. const old_layoutStatus = wls.layoutStatus
  2665. if (old_layoutStatus === null) return;
  2666. let new_layoutStatus = old_layoutStatus;
  2667.  
  2668. for (const mutation of mutations) {
  2669. new_layoutStatus = toLayoutStatus(new_layoutStatus, mutation.attributeName);
  2670. if (mutation.attributeName == 'userscript-chat-collapsed' || mutation.attributeName == 'userscript-chatblock') {
  2671.  
  2672. if (cssElm.getAttribute('userscript-chatblock') === 'chat-live') {
  2673.  
  2674. requestingComments = null;
  2675. _disableComments();
  2676.  
  2677. }
  2678.  
  2679. if (!cssElm.hasAttribute('userscript-chatblock')) {
  2680. setTimeout(() => {
  2681. if (!scriptEnable) return;
  2682. if (!isAnyActiveTab() && !isChatExpand() && !isTheater() && isWideScreenWithTwoColumns() && !isFullScreen()) {
  2683. setToActiveTab();
  2684. }
  2685. }, 240);
  2686. }
  2687.  
  2688. }
  2689. }
  2690.  
  2691.  
  2692. if (new_layoutStatus !== old_layoutStatus) wls.layoutStatus = new_layoutStatus
  2693.  
  2694.  
  2695.  
  2696.  
  2697. }
  2698.  
  2699.  
  2700. FOnce.mtf_checkFlexy = () => {
  2701. let ytdFlexyElm = kRef(ytdFlexy);
  2702. if (!scriptEnable || !ytdFlexyElm) return true;
  2703.  
  2704. const rootElement = Q.mutationTarget || ytdFlexyElm;
  2705.  
  2706. var flexy = kRef(ytdFlexy)
  2707. if (!flexy) return true;
  2708.  
  2709. wls.layoutStatus = null;
  2710.  
  2711. let rChatExist = base_ChatExist();
  2712. if (rChatExist) {
  2713. let { attr_chatblock, attr_chatcollapsed } = rChatExist;
  2714. if (attr_chatblock === null) {
  2715. //remove attribute if it is unknown
  2716. attr_chatblock = false;
  2717. attr_chatcollapsed = false;
  2718. }
  2719. wAttr(flexy, 'userscript-chatblock', attr_chatblock)
  2720. wAttr(flexy, 'userscript-chat-collapsed', attr_chatcollapsed)
  2721. }
  2722.  
  2723. let rTabSelection = [...flexy.querySelectorAll('.tab-btn[userscript-tab-content]')]
  2724. .map(elm => ({ elm, hidden: elm.classList.contains('tab-btn-hidden') }))
  2725. .filter(entry => entry.hidden === true);
  2726. if (rTabSelection.length === 0) wAttr(flexy, 'tabview-selection', false);
  2727. else if (rTabSelection.length === 1) wAttr(flexy, 'tabview-selection', rTabSelection[0].elm.getAttribute('userscript-tab-content') || '');
  2728.  
  2729. let rEP = engagement_panels_();
  2730. if (rEP && rEP.count > 0) wAttr(flexy, 'userscript-engagement-panel', false);
  2731. else wAttr(flexy, 'userscript-engagement-panel', rEP.value + "");
  2732.  
  2733. let ls = 0;
  2734. ls = toLayoutStatus(ls, 'theater')
  2735. ls = toLayoutStatus(ls, 'userscript-chat-collapsed')
  2736. ls = toLayoutStatus(ls, 'userscript-chatblock')
  2737. ls = toLayoutStatus(ls, 'is-two-columns_')
  2738. ls = toLayoutStatus(ls, 'tabview-selection')
  2739. ls = toLayoutStatus(ls, 'fullscreen')
  2740. ls = toLayoutStatus(ls, 'userscript-engagement-panel')
  2741.  
  2742. wls.layoutStatus = ls
  2743.  
  2744. initMutationObserver(mtoVs, 'mtoFlexyAttr', mtf_attrFlexy).observe(flexy, {
  2745. attributes: true,
  2746. attributeFilter: ['userscript-chat-collapsed', 'userscript-chatblock', 'theater', 'is-two-columns_', 'tabview-selection', 'fullscreen', 'userscript-engagement-panel'],
  2747. attributeOldValue: true
  2748. })
  2749.  
  2750.  
  2751. let columns = document.querySelector('ytd-page-manager#page-manager #columns')
  2752. if (columns) {
  2753. wAttr(columns, 'userscript-scrollbar-render', true);
  2754. }
  2755.  
  2756. return false;
  2757. }
  2758. if (Q.mutationTarget === null) $callOnceAsync('mtf_checkFlexy')
  2759.  
  2760.  
  2761.  
  2762. }
  2763.  
  2764.  
  2765.  
  2766.  
  2767. let switchTabActivity_lastTab = null
  2768.  
  2769. function setDisplayedPlaylist() {
  2770. //override the default youtube coding event prevention
  2771. let cssElm = kRef(ytdFlexy);
  2772. if (!scriptEnable || !cssElm) return;
  2773. displayedPlaylist = mWeakRef(document.querySelector('ytd-watch-flexy #tab-list:not(.tab-content-hidden) ytd-playlist-panel-renderer') || null);
  2774. }
  2775.  
  2776. function fixLineClampFn1(){
  2777. setTimeout(()=>requestAnimationFrame(()=>new Promise(fixLineClampFn2)),1)
  2778. }
  2779. function fixLineClampFn2(){
  2780. let contentElements = document.querySelectorAll('ytd-comments#comments ytd-expander[should-use-number-of-lines] #content')
  2781. for(const elm of contentElements) elm.classList.toggle('tabview-fix-line-clamp');
  2782. contentElements = null;
  2783. }
  2784.  
  2785. function switchTabActivity(activeLink) {
  2786. if (!scriptEnable) return;
  2787.  
  2788. const ytdFlexyElm = kRef(ytdFlexy);
  2789.  
  2790. if (!ytdFlexyElm) return;
  2791.  
  2792. if (activeLink && activeLink.classList.contains('tab-btn-hidden')) return; // not allow to switch to hide tab
  2793.  
  2794. if (isTheater() && isWideScreenWithTwoColumns()) activeLink = null;
  2795.  
  2796.  
  2797. function runAtEnd() {
  2798.  
  2799. if (activeLink) lastShowTab = activeLink.getAttribute('userscript-tab-content')
  2800.  
  2801. displayedPlaylist = null;
  2802. scrollingVideosList = null;
  2803.  
  2804. if (activeLink && lastShowTab == '#tab-list') {
  2805. setDisplayedPlaylist();
  2806. } else if (activeLink && lastShowTab == '#tab-videos') {
  2807. scrollingVideosList = mWeakRef(document.querySelector('ytd-watch-flexy #tab-videos:not(.tab-content-hidden) [placeholder-videos]'));
  2808. }
  2809.  
  2810.  
  2811. ytdFlexyElm.setAttribute('tabview-selection', activeLink ? lastShowTab : '')
  2812.  
  2813. if (lastShowTab == '#tab-comments' && (ytdFlexyElm.getAttribute('tabview-youtube-comments') || '').lastIndexOf('S') >= 0) {
  2814.  
  2815. akAttr(ytdFlexyElm, 'tabview-youtube-comments', false, 'L');
  2816.  
  2817. requestAnimationFrame(() => {
  2818. let comments_tab = document.querySelector('#tab-comments');
  2819. if (comments_tab && comments_tab.scrollTop > 0) comments_tab.scrollTop = 0;
  2820. });
  2821.  
  2822. }
  2823. if(lastShowTab=='#tab-comments'){
  2824. fixLineClampFn1();
  2825. }
  2826.  
  2827. }
  2828.  
  2829. const links = document.querySelectorAll('#material-tabs a[userscript-tab-content]');
  2830.  
  2831.  
  2832. for (const link of links) {
  2833. let content = document.querySelector(link.getAttribute('userscript-tab-content'));
  2834. if (link && content) {
  2835. if (link !== activeLink) {
  2836. link.classList.remove("active");
  2837. content.classList.add("tab-content-hidden");
  2838. } else {
  2839. link.classList.add("active");
  2840. content.classList.remove("tab-content-hidden");
  2841. //setTimeout(()=>content.focus(),400);
  2842.  
  2843. }
  2844. }
  2845. }
  2846.  
  2847. runAtEnd();
  2848.  
  2849.  
  2850. }
  2851.  
  2852. let tabsUiScript_setclick = false;
  2853.  
  2854. function prepareTabBtn() {
  2855.  
  2856. const materialTab = document.querySelector("#material-tabs")
  2857. if (!materialTab) return;
  2858.  
  2859. let noActiveTab = !!document.querySelector('ytd-watch-flexy[userscript-chatblock]:not([userscript-chat-collapsed])')
  2860.  
  2861. const activeLink = materialTab.querySelector('a[userscript-tab-content].active:not(.tab-btn-hidden)')
  2862. if (activeLink) switchTabActivity(noActiveTab ? null : activeLink)
  2863.  
  2864. if (!tabsUiScript_setclick) {
  2865. tabsUiScript_setclick = true;
  2866. $(materialTab).on("click", "a", function(evt) {
  2867.  
  2868. let ytdFlexyElm = kRef(ytdFlexy);
  2869. if (!scriptEnable || !ytdFlexyElm) return null;
  2870.  
  2871. if (!this.hasAttribute('userscript-tab-content')) return;
  2872.  
  2873.  
  2874. evt.preventDefault();
  2875.  
  2876.  
  2877. if (this.getAttribute('userscript-tab-content') == '#tab-comments' && parseInt(ytdFlexyElm.getAttribute('tabview-youtube-comments') || '') < 0) {
  2878. return;
  2879. }
  2880.  
  2881. new Promise(requestAnimationFrame).then(() => {
  2882.  
  2883.  
  2884. layoutStatusMutex.lockWith(unlock => {
  2885.  
  2886. switchTabActivity_lastTab = this.getAttribute('userscript-tab-content');
  2887.  
  2888. let isActiveAndVisible = this.classList.contains('tab-btn') && this.classList.contains('active') && !this.classList.contains('tab-btn-hidden')
  2889.  
  2890. if (isWideScreenWithTwoColumns() && !isTheater() && isActiveAndVisible) {
  2891. //optional
  2892. setTimeout(unlock, 80);
  2893. switchTabActivity(null);
  2894. ytBtnSetTheater();
  2895. } else if (isActiveAndVisible) {
  2896. setTimeout(unlock, 80);
  2897. switchTabActivity(null);
  2898. } else {
  2899. let pInterval = 60;
  2900. if (isChatExpand() && isWideScreenWithTwoColumns()) {
  2901. ytBtnCollapseChat();
  2902. } else if (isEngagementPanelExpanded() && isWideScreenWithTwoColumns()) {
  2903. ytBtnCloseEngagementPanels();
  2904. } else if (isWideScreenWithTwoColumns() && isTheater() && !isFullScreen()) {
  2905. ytBtnCancelTheater();
  2906. } else {
  2907. pInterval = 20;
  2908. }
  2909. setTimeout(() => {
  2910. setTimeout(makeBodyScroll, 20); // this is to make the image render
  2911.  
  2912. setTimeout(() => {
  2913. let rightTabs = document.querySelector('#right-tabs');
  2914. if (!isWideScreenWithTwoColumns() && rightTabs && rightTabs.offsetTop > 0 && this.classList.contains('active')) {
  2915. let tabButtonBar = document.querySelector('#material-tabs');
  2916. let tabButtonBarHeight = tabButtonBar ? tabButtonBar.offsetHeight : 0;
  2917. window.scrollTo(0, rightTabs.offsetTop - tabButtonBarHeight);
  2918. }
  2919. }, 60)
  2920.  
  2921. setTimeout(unlock, 80)
  2922. switchTabActivity(this)
  2923.  
  2924. }, pInterval);
  2925. }
  2926.  
  2927.  
  2928. })
  2929.  
  2930. })
  2931.  
  2932.  
  2933.  
  2934.  
  2935. });
  2936.  
  2937. }
  2938.  
  2939. }
  2940.  
  2941.  
  2942. // ---------------------------------------------------------------------------------------------
  2943. window.addEventListener("yt-navigate-finish", onNavigationEnd)
  2944.  
  2945. document.addEventListener("loadstart", (evt) => {
  2946. if (!evt || !evt.target || evt.target.nodeName !== "VIDEO") return;
  2947. let elm = evt.target;
  2948. if (!elm.matches('#player video, #movie_player video, video[tabview-mainvideo]')) return;
  2949.  
  2950. let src = elm.src;
  2951. if (src !== lastVideoURL) {
  2952. lastVideoURL = elm.src;
  2953.  
  2954. elm.setAttribute('tabview-mainvideo', ''); // mainly for mini playing
  2955.  
  2956.  
  2957. }
  2958.  
  2959. }, true)
  2960.  
  2961. // ---------------------------------------------------------------------------------------------
  2962.  
  2963. var scrolling_lastD = 0;
  2964.  
  2965. const singleColumnScrolling = function(scrolling_lastF) {
  2966. let pageY = pageYOffset;
  2967. if (pageY < 10 && scrolling_lastD === 0 && !scrolling_lastF) return;
  2968.  
  2969. let targetElm, header, navElm;
  2970.  
  2971. Promise.resolve().then(() => {
  2972.  
  2973. targetElm = document.querySelector("#right-tabs");
  2974. if (!targetElm) return;
  2975. header = targetElm.querySelector("header");
  2976. if (!header) return;
  2977. navElm = document.querySelector('#masthead-container, #masthead')
  2978. if (!navElm) return;
  2979. let navHeight = navElm ? navElm.offsetHeight : 0
  2980.  
  2981. let elmY = targetElm.offsetTop
  2982.  
  2983. let xyz = [elmY + navHeight, pageY, elmY - navHeight]
  2984.  
  2985. let xyStatus = 0
  2986. if (xyz[1] < xyz[2] && xyz[2] < xyz[0]) {
  2987. // 1
  2988. xyStatus = 1
  2989. }
  2990.  
  2991. if (xyz[0] > xyz[1] && xyz[1] > xyz[2]) {
  2992.  
  2993. //2
  2994. xyStatus = 2
  2995.  
  2996. }
  2997.  
  2998. if (xyz[2] < xyz[0] && xyz[0] < xyz[1]) {
  2999. // 3
  3000.  
  3001. xyStatus = 3
  3002.  
  3003.  
  3004. }
  3005.  
  3006. return xyStatus;
  3007.  
  3008. }).then((xyStatus) => {
  3009.  
  3010. if ((xyStatus == 2 || xyStatus == 3) && (scrolling_lastD === 0 || scrolling_lastF)) {
  3011. scrolling_lastD = 1;
  3012. let {
  3013. offsetHeight
  3014. } = header
  3015. let {
  3016. offsetWidth
  3017. } = targetElm
  3018.  
  3019. targetElm.style.setProperty("--userscript-sticky-width", offsetWidth + 'px')
  3020. targetElm.style.setProperty("--userscript-sticky", offsetHeight + 'px')
  3021.  
  3022. wAttr(targetElm, 'userscript-sticky', true);
  3023.  
  3024. } else if ((xyStatus == 1) && (scrolling_lastD === 1 || scrolling_lastF)) {
  3025. scrolling_lastD = 0;
  3026.  
  3027. wAttr(targetElm, 'userscript-sticky', false);
  3028. }
  3029.  
  3030.  
  3031. targetElm = null;
  3032. header = null;
  3033. navElm = null;
  3034.  
  3035. });
  3036.  
  3037. };
  3038.  
  3039. window.addEventListener("scroll", function() {
  3040. if (!scriptEnable) return;
  3041. singleColumnScrolling(false)
  3042. }, {
  3043. capture: false,
  3044. passive: true
  3045. })
  3046.  
  3047. var lastResizeAt = 0;
  3048. window.addEventListener('resize', function() {
  3049. if (!scriptEnable) return;
  3050. lastResizeAt = Date.now();
  3051.  
  3052. requestAnimationFrame(() => {
  3053. if (!scriptEnable) return;
  3054. singleColumnScrolling(true)
  3055. })
  3056.  
  3057. }, {
  3058. capture: false,
  3059. passive: true
  3060. })
  3061.  
  3062. window.addEventListener('beforeunload', function() {
  3063. if (!scriptEnable) return;
  3064. console.log('beforeunload')
  3065. pluginUnhook();
  3066. //let video=document.querySelector('video');
  3067. //if(video && !video.paused) video.pause();
  3068. }, { capture: true })
  3069.  
  3070. window.addEventListener('hashchange', function() {
  3071. if (!scriptEnable) return;
  3072. console.log('hashchange')
  3073. pluginUnhook();
  3074. }, { capture: true })
  3075.  
  3076. window.addEventListener('popstate', function() {
  3077. if (!scriptEnable) return;
  3078. console.log('popstate')
  3079. pluginUnhook();
  3080. }, { capture: true })
  3081.  
  3082.  
  3083. function clearMutationObserver(o, key) {
  3084. if (o[key]) {
  3085. o[key].takeRecords();
  3086. o[key].disconnect();
  3087. o[key] = null;
  3088. return true;
  3089. }
  3090. }
  3091.  
  3092. function initMutationObserver(o, key, callback) {
  3093. clearMutationObserver(o, key);
  3094. const mto = new MutationObserver(callback);
  3095. o[key] = mto;
  3096. return mto;
  3097. }
  3098.  
  3099. document.addEventListener('wheel', function(evt) {
  3100.  
  3101. if (!scriptEnable) return;
  3102. const displayedPlaylist_element = kRef(displayedPlaylist);
  3103. if (displayedPlaylist_element && displayedPlaylist_element.contains(evt.target)) {
  3104. evt.stopPropagation();
  3105. evt.stopImmediatePropagation();
  3106. }
  3107. }, { capture: true, passive: true });
  3108.  
  3109.  
  3110. function setVideosTwoColumns(flag, bool) {
  3111.  
  3112. //two columns to one column
  3113.  
  3114. /*
  3115. [placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy
  3116.  
  3117. is-two-columns ="" => no is-two-columns
  3118. [placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer
  3119. no hidden => hidden =""
  3120. [placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer
  3121. hidden ="" => no hidden
  3122.  
  3123. */
  3124.  
  3125. let cssSelector1 = '[placeholder-videos] ytd-watch-next-secondary-results-renderer.style-scope.ytd-watch-flexy'
  3126.  
  3127. let cssSelector2 = '[placeholder-videos] tp-yt-paper-spinner#spinner.style-scope.ytd-continuation-item-renderer'
  3128.  
  3129. let cssSelector3 = '[placeholder-videos] div#button.style-scope.ytd-continuation-item-renderer'
  3130.  
  3131. let res = {}
  3132. if (flag & 1) {
  3133. res.m1 = document.querySelector(cssSelector1)
  3134. if (res.m1) wAttr(res.m1, 'is-two-columns', bool ? '' : false);
  3135. }
  3136.  
  3137. if (flag & 2) {
  3138. res.m2 = document.querySelector(cssSelector2)
  3139. if (res.m2) wAttr(res.m2, 'hidden', bool ? false : '');
  3140. }
  3141.  
  3142. if (flag & 4) {
  3143. res.m3 = document.querySelector(cssSelector3)
  3144. if (res.m3) wAttr(res.m3, 'hidden', bool ? '' : false);
  3145. }
  3146.  
  3147.  
  3148. return res
  3149.  
  3150.  
  3151.  
  3152.  
  3153. }
  3154.  
  3155. let lastScrollFetch = 0;
  3156. // function isScrolledToEnd(){
  3157. // return (window.innerHeight + window.pageYOffset) >= document.scrollingElement.scrollHeight - 2;
  3158. // }
  3159. let lastOffsetTop = 0;
  3160. window.addEventListener('scroll', function(evt) {
  3161.  
  3162. //console.log(evt.target)
  3163.  
  3164. if (!scriptEnable) return;
  3165.  
  3166.  
  3167. if (!kRef(scrollingVideosList)) return;
  3168. if (videoListBeforeSearch) return;
  3169.  
  3170.  
  3171.  
  3172. let visibleHeight = document.scrollingElement.clientHeight;
  3173. let totalHeight = document.scrollingElement.scrollHeight;
  3174.  
  3175. if (totalHeight < visibleHeight * 1.5) return; // filter out two column view;
  3176.  
  3177. let z = window.pageYOffset + visibleHeight;
  3178. let h_advanced = totalHeight - (visibleHeight > 5 * 40 ? visibleHeight * 0.5 : 40);
  3179.  
  3180.  
  3181.  
  3182. if (z > h_advanced && !isWideScreenWithTwoColumns()) {
  3183.  
  3184. let ct = Date.now();
  3185. if (ct - lastScrollFetch < 500) return; //prevent continuous calling
  3186.  
  3187. lastScrollFetch = ct;
  3188.  
  3189. let res = setVideosTwoColumns(2 | 4, true)
  3190. if (res.m3 && res.m2) {
  3191.  
  3192. //wait for DOM change, just in case
  3193. requestAnimationFrame(() => {
  3194. let { offsetTop } = res.m2 // as visibility of m2 & m3 switched.
  3195.  
  3196. if (offsetTop - lastOffsetTop < 40) return; // in case bug, or repeating calling. // the next button shall below the this button
  3197. lastOffsetTop = offsetTop
  3198.  
  3199. res.m2.parentNode.dispatchEvent(new Event('yt-service-request-sent-button-renderer'))
  3200.  
  3201. res = null
  3202. })
  3203.  
  3204. } else {
  3205.  
  3206. res = null
  3207. }
  3208.  
  3209.  
  3210. }
  3211.  
  3212.  
  3213.  
  3214.  
  3215. }, { passive: true })
  3216.  
  3217.  
  3218.  
  3219.  
  3220. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  3221.  
  3222. /*
  3223. fix bug for comment section - version 1.8.7
  3224. This issue is the bug in browser's rendering
  3225. I guess, this is due to the lines clamp with display:-webkit-box
  3226. use stupid coding to let it re-render when its content become visible
  3227. /*
  3228.  
  3229. ytd-expander[should-use-number-of-lines][collapsed] > #content.ytd-expander {
  3230. color: var(--yt-spec-text-primary);
  3231. display: -webkit-box;
  3232. overflow: hidden;
  3233. max-height: none;
  3234. -webkit-box-orient: vertical;
  3235. -webkit-line-clamp: var(--ytd-expander-max-lines, 4);
  3236. }
  3237.  
  3238. // v1.8.36 imposed a effective solution for fixing this bug
  3239.  
  3240. */
  3241.  
  3242. /* --------------------------- browser's bug in -webkit-box ----------------------------------------- */
  3243.  
  3244.  
  3245.  
  3246.  
  3247. })();
  3248.  
  3249.  
  3250.  
  3251.  
  3252.  
  3253.  
  3254.  
  3255.  
  3256.  
  3257.  
  3258.  
  3259.  
  3260.  
  3261.  
  3262.  
  3263.  
  3264.  
  3265.  
  3266.  
  3267.  
  3268.  
  3269.  
  3270.  
  3271.  
  3272.  
  3273.  
  3274.  
  3275.  
  3276.  
  3277.  
  3278.  
  3279.  
  3280.  
  3281.  
  3282.  
  3283.  
  3284.  
  3285.  
  3286.  
  3287.  
  3288.  
  3289.  
  3290. // https://github.com/cyfung1031/Tabview-Youtube/raw/main/js/content.js
  3291.  
  3292. }
  3293.  
  3294.  
  3295. ;!(function $$() {
  3296. 'use strict';
  3297.  
  3298. if(document.documentElement==null) return window.requestAnimationFrame($$)
  3299.  
  3300. const cssTxt = GM_getResourceText("contentCSS");
  3301.  
  3302. function addStyle (styleText) {
  3303. const styleNode = document.createElement('style');
  3304. styleNode.type = 'text/css';
  3305. styleNode.textContent = styleText;
  3306. document.documentElement.appendChild(styleNode);
  3307. return styleNode;
  3308. }
  3309.  
  3310. addStyle (cssTxt);
  3311.  
  3312. main(window.$);
  3313.  
  3314.  
  3315. // Your code here...
  3316. })();