YouTube 超快聊天

让您的 YouTube 直播聊天即时滚动,不经过平滑转换 CSS。

当前为 2023-07-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Super Fast Chat
  3. // @version 0.5.20
  4. // @license MIT
  5. // @name:ja YouTube スーパーファーストチャット
  6. // @name:zh-TW YouTube 超快聊天
  7. // @name:zh-CN YouTube 超快聊天
  8. // @namespace UserScript
  9. // @match https://www.youtube.com/live_chat*
  10. // @author CY Fung
  11. // @require https://greasyfork.org/scripts/465819-api-for-customelements-in-youtube/code/API%20for%20CustomElements%20in%20YouTube.js?version=1215280
  12. // @run-at document-start
  13. // @grant none
  14. // @unwrap
  15. // @allFrames true
  16. // @inject-into page
  17. //
  18. // @description To make your YouTube Live Chat scroll instantly without smoothing transform CSS
  19. // @description:ja YouTubeライブチャットをスムーズな変形CSSなしで瞬時にスクロールさせるために。
  20. // @description:zh-TW 讓您的 YouTube 直播聊天即時滾動,不經過平滑轉換 CSS。
  21. // @description:zh-CN 让您的 YouTube 直播聊天即时滚动,不经过平滑转换 CSS。
  22. //
  23. // ==/UserScript==
  24.  
  25. ((__CONTEXT__) => {
  26.  
  27. // const ACTIVE_DEFERRED_APPEND = false; // somehow buggy
  28.  
  29. // const ACTIVE_CONTENT_VISIBILITY = true;
  30. // const ACTIVE_CONTAIN_SIZE = true;
  31.  
  32. const addCss = () => document.head.appendChild(document.createElement('style')).textContent = `
  33.  
  34.  
  35. @supports (contain:layout paint style) and (content-visibility:auto) and (contain-intrinsic-size:auto var(--wsr94)) {
  36.  
  37. [wSr93="hidden"]:nth-last-child(n+4) {
  38. --wsr93-content-visibility: auto;
  39. contain-intrinsic-size: auto var(--wsr94);
  40. }
  41.  
  42. }
  43.  
  44. @supports (contain:layout paint style) {
  45.  
  46. [wSr93] {
  47. --wsr93-contain: layout style;
  48. contain: var(--wsr93-contain, unset) !important;
  49. box-sizing: border-box !important;
  50. content-visibility: var(--wsr93-content-visibility, visible);
  51. }
  52. [wSr93="hidden"] { /* initial->[wSr93]->[wSr93="visible"]->[wSr93="hidden"] => reliable rendered height */
  53. --wsr93-contain: size layout style;
  54. height: var(--wsr94);
  55. }
  56.  
  57.  
  58. /* ------------------------------------------------------------------------------------------------------------- */
  59.  
  60. yt-live-chat-author-chip #chat-badges.yt-live-chat-author-chip, yt-live-chat-author-chip #chat-badges.yt-live-chat-author-chip yt-live-chat-author-badge-renderer, yt-live-chat-author-chip #chat-badges.yt-live-chat-author-chip yt-live-chat-author-badge-renderer #image, yt-live-chat-author-chip #chat-badges.yt-live-chat-author-chip yt-live-chat-author-badge-renderer #image img {
  61. contain: layout style;
  62. }
  63.  
  64. body yt-live-chat-app {
  65. contain: size layout paint style;
  66. overflow: hidden;
  67. }
  68.  
  69. #items.style-scope.yt-live-chat-item-list-renderer {
  70. contain: layout paint style;
  71. }
  72.  
  73. #item-offset.style-scope.yt-live-chat-item-list-renderer {
  74. contain: style;
  75. }
  76.  
  77. #item-scroller.style-scope.yt-live-chat-item-list-renderer {
  78. contain: size style;
  79. }
  80.  
  81. #contents.style-scope.yt-live-chat-item-list-renderer, #chat.style-scope.yt-live-chat-renderer, img.style-scope.yt-img-shadow[width][height] {
  82. contain: size layout paint style;
  83. }
  84.  
  85. .style-scope.yt-live-chat-ticker-renderer[role="button"][aria-label], .style-scope.yt-live-chat-ticker-renderer[role="button"][aria-label] > #container {
  86. contain: layout paint style;
  87. }
  88.  
  89. yt-live-chat-text-message-renderer.style-scope.yt-live-chat-item-list-renderer, yt-live-chat-membership-item-renderer.style-scope.yt-live-chat-item-list-renderer, yt-live-chat-paid-message-renderer.style-scope.yt-live-chat-item-list-renderer, yt-live-chat-banner-manager.style-scope.yt-live-chat-item-list-renderer {
  90. contain: layout style;
  91. }
  92.  
  93. tp-yt-paper-tooltip[style*="inset"][role="tooltip"] {
  94. contain: layout paint style;
  95. }
  96.  
  97. /* ------------------------------------------------------------------------------------------------------------- */
  98.  
  99. }
  100.  
  101. @supports (color: var(--general)) {
  102.  
  103. #item-offset.style-scope.yt-live-chat-item-list-renderer > #items.style-scope.yt-live-chat-item-list-renderer {
  104. position: static !important;
  105. }
  106.  
  107. .ytp-contextmenu[class],
  108. .toggle-button.tp-yt-paper-toggle-button[class],
  109. .yt-spec-touch-feedback-shape__fill[class],
  110. .fill.yt-interaction[class],
  111. .ytp-videowall-still-info-content[class],
  112. .ytp-suggestion-image[class] {
  113. will-change: unset !important;
  114. }
  115.  
  116. yt-img-shadow[height][width] {
  117. content-visibility: visible !important;
  118. }
  119.  
  120. yt-live-chat-item-list-renderer:not([allow-scroll]) #item-scroller.yt-live-chat-item-list-renderer {
  121. overflow-y: scroll;
  122. padding-right: 0;
  123. }
  124.  
  125.  
  126. /* optional */
  127. #item-offset.style-scope.yt-live-chat-item-list-renderer {
  128. height: auto !important;
  129. min-height: unset !important;
  130. }
  131.  
  132. #items.style-scope.yt-live-chat-item-list-renderer {
  133. transform: translateY(0px) !important;
  134. }
  135.  
  136. /* optional */
  137. yt-icon[icon="down_arrow"] > *, yt-icon-button#show-more > * {
  138. pointer-events: none !important;
  139. }
  140.  
  141. #continuations, #continuations * {
  142. contain: strict;
  143. position: fixed;
  144. top: 2px;
  145. height: 1px;
  146. width: 2px;
  147. height: 1px;
  148. visibility: collapse;
  149. }
  150.  
  151. yt-live-chat-renderer[has-action-panel-renderer] #show-more.yt-live-chat-item-list-renderer{
  152. top: 4px;
  153. transition-property: top;
  154. bottom: unset;
  155. }
  156.  
  157. yt-live-chat-renderer[has-action-panel-renderer] #show-more.yt-live-chat-item-list-renderer[disabled]{
  158. top: -42px;
  159. }
  160.  
  161. html #panel-pages.yt-live-chat-renderer > #input-panel.yt-live-chat-renderer:not(:empty) {
  162. --yt-live-chat-action-panel-top-border: none;
  163. }
  164.  
  165. html #panel-pages.yt-live-chat-renderer > #input-panel.yt-live-chat-renderer.iron-selected > *:first-child {
  166. border-top: 1px solid var(--yt-live-chat-panel-pages-border-color);
  167. }
  168.  
  169. html #panel-pages.yt-live-chat-renderer {
  170. border-top: 0;
  171. border-bottom: 0;
  172. }
  173.  
  174. #input-panel #picker-buttons yt-live-chat-icon-toggle-button-renderer#product-picker {
  175. overflow: hidden;
  176. contain: layout paint style;
  177. }
  178.  
  179. }
  180.  
  181. `;
  182.  
  183. const { Promise, requestAnimationFrame, IntersectionObserver } = __CONTEXT__;
  184.  
  185.  
  186. const isContainSupport = CSS.supports('contain', 'layout paint style');
  187. if (!isContainSupport) {
  188. console.warn("Your browser does not support css property 'contain'.\nPlease upgrade to the latest version.".trim());
  189. }
  190.  
  191. // const APPLY_delayAppendChild = false;
  192.  
  193. // let activeDeferredAppendChild = false; // deprecated
  194.  
  195. // let delayedAppendParentWS = new WeakSet();
  196. // let delayedAppendOperations = [];
  197. // let commonAppendParentStackSet = new Set();
  198.  
  199. // let firstVisibleItemDetected = false; // deprecated
  200.  
  201. const sp7 = Symbol();
  202.  
  203.  
  204. let dt0 = Date.now() - 2000;
  205. const dateNow = () => Date.now() - dt0;
  206. // let lastScroll = 0;
  207. // let lastLShow = 0;
  208. let lastWheel = 0;
  209.  
  210. const proxyHelperFn = (dummy) => ({
  211.  
  212. get(target, prop) {
  213. return (prop in dummy) ? dummy[prop] : prop === sp7 ? target : target[prop];
  214. },
  215. set(target, prop, value) {
  216. if (!(prop in dummy)) {
  217. target[prop] = value;
  218. }
  219. return true;
  220. },
  221. has(target, prop) {
  222. return (prop in target)
  223. },
  224. deleteProperty(target, prop) {
  225. return true;
  226. },
  227. ownKeys(target) {
  228. return Object.keys(target);
  229. },
  230. defineProperty(target, key, descriptor) {
  231. return Object.defineProperty(target, key, descriptor);
  232. },
  233. getOwnPropertyDescriptor(target, key) {
  234. return Object.getOwnPropertyDescriptor(target, key);
  235. },
  236.  
  237. });
  238.  
  239. const tickerContainerSetAttribute = function (attrName, attrValue) { // ensure '14.30000001%'.toFixed(1)
  240.  
  241. let yd = (this.__dataHost || (this.inst || 0).__dataHost).__data;
  242.  
  243. if (arguments.length === 2 && attrName === 'style' && yd && attrValue) {
  244.  
  245. // let v = yd.containerStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;
  246. let v = `${attrValue}`;
  247. // conside a ticker is 101px width
  248. // 1% = 1.01px
  249. // 0.2% = 0.202px
  250.  
  251.  
  252. const ratio1 = (yd.ratio * 100);
  253. if (ratio1 > -1) { // avoid NaN
  254.  
  255. // countdownDurationMs
  256. // 600000 - 0.2% <1% = 6s> <0.2% = 1.2s>
  257. // 300000 - 0.5% <1% = 3s> <0.5% = 1.5s>
  258. // 150000 - 1% <1% = 1.5s>
  259. // 75000 - 2% <1% =0.75s > <2% = 1.5s>
  260. // 30000 - 5% <1% =0.3s > <5% = 1.5s>
  261.  
  262. // 99px * 5% = 4.95px
  263.  
  264. // 15000 - 10% <1% =0.15s > <10% = 1.5s>
  265.  
  266.  
  267.  
  268.  
  269. // 1% Duration
  270.  
  271. let ratio2 = ratio1;
  272.  
  273. const ydd = yd.data;
  274. const d1 = ydd.durationSec;
  275. const d2 = ydd.fullDurationSec;
  276.  
  277. if (d1 === d2 && d1 > 1) {
  278.  
  279. if (d1 > 400) ratio2 = Math.round(ratio2 * 5) / 5; // 0.2%
  280. else if (d1 > 200) ratio2 = Math.round(ratio2 * 2) / 2; // 0.5%
  281. else if (d1 > 100) ratio2 = Math.round(ratio2 * 1) / 1; // 1%
  282. else if (d1 > 50) ratio2 = Math.round(ratio2 * 0.5) / 0.5; // 2%
  283. else if (d1 > 25) ratio2 = Math.round(ratio2 * 0.2) / 0.2; // 5% (max => 99px * 5% = 4.95px)
  284. else ratio2 = Math.round(ratio2 * 0.2) / 0.2;
  285.  
  286. } else {
  287. ratio2 = Math.round(ratio2 * 5) / 5; // 0.2% (min)
  288. }
  289.  
  290. // ratio2 = Math.round(ratio2 * 5) / 5;
  291. ratio2 = ratio2.toFixed(1)
  292. v = v.replace(`${ratio1}%`, `${ratio2}%`).replace(`${ratio1}%`, `${ratio2}%`)
  293.  
  294. if (yd.__style_last__ === v) return;
  295. yd.__style_last__ = v;
  296. // do not consider any delay here.
  297. // it shall be inside the looping for all properties changes. all the css background ops are in the same microtask.
  298.  
  299. }
  300.  
  301. HTMLElement.prototype.setAttribute.call(this, attrName, v);
  302.  
  303.  
  304. } else {
  305. HTMLElement.prototype.setAttribute.apply(this, arguments);
  306. }
  307.  
  308. };
  309.  
  310. const fxOperator = (proto, propertyName) => {
  311. let propertyDescriptorGetter = null;
  312. try {
  313. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  314. } catch (e) { }
  315. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  316. };
  317.  
  318. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  319. // const nFirstElem = fxOperator(HTMLElement.prototype, 'firstElementChild');
  320. const nPrevElem = fxOperator(HTMLElement.prototype, 'previousElementSibling');
  321. const nNextElem = fxOperator(HTMLElement.prototype, 'nextElementSibling');
  322. const nLastElem = fxOperator(HTMLElement.prototype, 'lastElementChild');
  323.  
  324.  
  325. /* globals WeakRef:false */
  326.  
  327. /** @type {(o: Object | null) => WeakRef | null} */
  328. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  329.  
  330. /** @type {(wr: Object | null) => Object | null} */
  331. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  332.  
  333. const watchUserCSS = () => {
  334.  
  335. // if (!CSS.supports('contain-intrinsic-size', 'auto var(--wsr94)')) return;
  336.  
  337. const getElemFromWR = (nr) => {
  338. const n = kRef(nr);
  339. if (n && n.isConnected) return n;
  340. return null;
  341. }
  342.  
  343. const clearContentVisibilitySizing = () => {
  344. Promise.resolve().then(() => {
  345.  
  346. let btnShowMoreWR = mWeakRef(document.querySelector('#show-more[disabled]'));
  347.  
  348. let lastVisibleItemWR = null;
  349. for (const elm of document.querySelectorAll('[wSr93]')) {
  350. if (elm.getAttribute('wSr93') === 'visible') lastVisibleItemWR = mWeakRef(elm);
  351. elm.setAttribute('wSr93', '');
  352. // custom CSS property --wsr94 not working when attribute wSr93 removed
  353. }
  354. requestAnimationFrame(() => {
  355. const btnShowMore = getElemFromWR(btnShowMoreWR); btnShowMoreWR = null;
  356. if (btnShowMore) btnShowMore.click();
  357. else {
  358. // would not work if switch it frequently
  359. const lastVisibleItem = getElemFromWR(lastVisibleItemWR); lastVisibleItemWR = null;
  360. if (lastVisibleItem) {
  361.  
  362. Promise.resolve()
  363. .then(() => lastVisibleItem.scrollIntoView())
  364. .then(() => lastVisibleItem.scrollIntoView(false))
  365. .then(() => lastVisibleItem.scrollIntoView({ behavior: "instant", block: "end", inline: "nearest" }))
  366. .catch(e => { }) // break the chain when method not callable
  367.  
  368. }
  369. }
  370. })
  371.  
  372. })
  373.  
  374. }
  375.  
  376. const mutObserver = new MutationObserver((mutations) => {
  377. for (const mutation of mutations) {
  378. if ((mutation.addedNodes || 0).length >= 1) {
  379. for (const addedNode of mutation.addedNodes) {
  380. if (addedNode.nodeName === 'STYLE') {
  381. clearContentVisibilitySizing();
  382. return;
  383. }
  384. }
  385. }
  386. if ((mutation.removedNodes || 0).length >= 1) {
  387. for (const removedNode of mutation.removedNodes) {
  388. if (removedNode.nodeName === 'STYLE') {
  389. clearContentVisibilitySizing();
  390. return;
  391. }
  392. }
  393. }
  394. }
  395. });
  396.  
  397. mutObserver.observe(document.documentElement, {
  398. childList: true,
  399. subtree: false
  400. })
  401.  
  402. mutObserver.observe(document.head, {
  403. childList: true,
  404. subtree: false
  405. })
  406. mutObserver.observe(document.body, {
  407. childList: true,
  408. subtree: false
  409. });
  410.  
  411. }
  412.  
  413. const setupStyle = (m1, m2) => {
  414.  
  415. const dummy1v = {
  416. transform: '',
  417. height: '',
  418. minHeight: '',
  419. paddingBottom: '',
  420. paddingTop: ''
  421. };
  422. for (const k of ['toString', 'getPropertyPriority', 'getPropertyValue', 'item', 'removeProperty', 'setProperty']) {
  423. dummy1v[k] = ((k) => (function () { const style = this[sp7]; return style[k](...arguments); }))(k)
  424. }
  425.  
  426. const dummy1p = proxyHelperFn(dummy1v);
  427. const sp1v = new Proxy(m1.style, dummy1p);
  428. const sp2v = new Proxy(m2.style, dummy1p);
  429. Object.defineProperty(m1, 'style', { get() { return sp1v }, set() { }, enumerable: true, configurable: true });
  430. Object.defineProperty(m2, 'style', { get() { return sp2v }, set() { }, enumerable: true, configurable: true });
  431. m1.removeAttribute("style");
  432. m2.removeAttribute("style");
  433.  
  434. }
  435.  
  436.  
  437. class WillChangeController {
  438. constructor(itemScroller, willChangeValue) {
  439. this.element = itemScroller;
  440. this.counter = 0;
  441. this.active = false;
  442. this.willChangeValue = willChangeValue;
  443. }
  444.  
  445. beforeOper() {
  446. if (!this.active) {
  447. this.active = true;
  448. this.element.style.willChange = this.willChangeValue;
  449. }
  450. this.counter++;
  451. }
  452.  
  453. afterOper() {
  454. const c = this.counter;
  455. requestAnimationFrame(() => {
  456. if (c === this.counter) {
  457. this.active = false;
  458. this.element.style.willChange = '';
  459. }
  460. })
  461. }
  462.  
  463. release() {
  464. const element = this.element;
  465. this.element = null;
  466. this.counter = 1e16;
  467. this.active = false;
  468. try {
  469. element.style.willChange = '';
  470. } catch (e) { }
  471. }
  472.  
  473. }
  474.  
  475.  
  476. customYtElements.onRegistryReady(() => {
  477.  
  478. let scrollWillChangeController = null;
  479. let contensWillChangeController = null;
  480.  
  481. // as it links to event handling, it has to be injected using immediateCallback
  482. customYtElements.whenRegistered('yt-live-chat-item-list-renderer', (cProto) => {
  483.  
  484. const mclp = cProto;
  485. console.assert(typeof mclp.scrollToBottom_ === 'function')
  486. console.assert(typeof mclp.scrollToBottom66_ !== 'function')
  487. console.assert(typeof mclp.flushActiveItems_ === 'function')
  488. console.assert(typeof mclp.flushActiveItems66_ !== 'function')
  489.  
  490.  
  491. mclp.__intermediate_delay__ = null;
  492.  
  493. mclp.scrollToBottom66_ = mclp.scrollToBottom_;
  494. mclp.scrollToBottom_ = function () {
  495. const cnt = this;
  496. const itemScroller = cnt.itemScroller;
  497. if (scrollWillChangeController && scrollWillChangeController.element !== itemScroller) {
  498. scrollWillChangeController.release();
  499. scrollWillChangeController = null;
  500. }
  501. if (!scrollWillChangeController) scrollWillChangeController = new WillChangeController(itemScroller, 'scroll-position');
  502. const wcController = scrollWillChangeController;
  503. wcController.beforeOper();
  504. cnt.__intermediate_delay__ = new Promise(resolve => {
  505. Promise.resolve().then(() => {
  506. cnt.scrollToBottom66_();
  507. }).then(() => {
  508. wcController.afterOper();
  509. resolve();
  510. });
  511. });
  512. }
  513.  
  514. mclp.flushActiveItems77_ = async function () {
  515. try {
  516.  
  517. const cnt = this;
  518. if (lastFlushActiveItemsCalled > 1e9) lastFlushActiveItemsCalled = 9;
  519. let tid = ++lastFlushActiveItemsCalled;
  520. if (tid !== lastFlushActiveItemsCalled || cnt.isAttached === false || (cnt.hostElement || cnt).isConnected === false) return;
  521. if (!cnt.activeItems_ || cnt.activeItems_.length === 0) return;
  522. if (cnt.canScrollToBottom_()) {
  523. let immd = cnt.__intermediate_delay__;
  524. await new Promise(requestAnimationFrame);
  525. if (tid !== lastFlushActiveItemsCalled || cnt.isAttached === false || (cnt.hostElement || cnt).isConnected === false) return;
  526. if (!cnt.activeItems_ || cnt.activeItems_.length === 0) return;
  527.  
  528. const items = (cnt.$ || 0).items;
  529. if (contensWillChangeController && contensWillChangeController.element !== items) {
  530. contensWillChangeController.release();
  531. contensWillChangeController = null;
  532. }
  533. if (!contensWillChangeController) contensWillChangeController = new WillChangeController(items, 'contents');
  534. const wcController = contensWillChangeController;
  535. cnt.__intermediate_delay__ = Promise.all([cnt.__intermediate_delay__ || null, immd || null]);
  536. wcController.beforeOper();
  537. await Promise.resolve();
  538. const len1 = cnt.activeItems_.length;
  539. cnt.flushActiveItems66_();
  540. const len2 = cnt.activeItems_.length;
  541. let bAsync = len1 !== len2;
  542. await Promise.resolve();
  543. if (bAsync) {
  544. cnt.async(() => {
  545. wcController.afterOper();
  546. });
  547. } else {
  548. wcController.afterOper();
  549. }
  550. } else {
  551. cnt.flushActiveItems66_();
  552. }
  553. } catch (e) {
  554. console.warn(e);
  555. }
  556. }
  557.  
  558. mclp.flushActiveItems66_ = mclp.flushActiveItems_;
  559. let lastFlushActiveItemsCalled = 0;
  560. mclp.flushActiveItems_ = function () {
  561. const cnt = this;
  562.  
  563. if (arguments.length !== 0 || !cnt.activeItems_ || !cnt.canScrollToBottom_) return cnt.flushActiveItems66_.apply(this, arguments);
  564.  
  565. if (cnt.activeItems_.length === 0) {
  566. cnt.__intermediate_delay__ = null;
  567. return;
  568. }
  569.  
  570. const cntData = ((cnt || 0).data || 0);
  571. if (cntData.maxItemsToDisplay > 90) cntData.maxItemsToDisplay = 90;
  572.  
  573. // ignore previous __intermediate_delay__ and create a new one
  574. cnt.__intermediate_delay__ = new Promise(resolve => {
  575. cnt.flushActiveItems77_().then(() => {
  576. if ((cnt.activeItems_ || 0).length === 0) resolve();
  577. else resolve(-1);
  578. });
  579. });
  580.  
  581. }
  582.  
  583. mclp.async66 = mclp.async;
  584. mclp.async = function () {
  585. // ensure the previous operation is done
  586. // .async is usually after the time consuming functions like flushActiveItems_ and scrollToBottom_
  587.  
  588. const stack = new Error().stack;
  589. (this.__intermediate_delay__ || Promise.resolve()).then(rk => {
  590. if (rk < 0) {
  591. if (stack.indexOf('flushActiveItems_') >= 0) return;
  592. }
  593. this.async66.apply(this, arguments);
  594. });
  595.  
  596. }
  597.  
  598. })
  599.  
  600. });
  601.  
  602. const getProto = (element) => {
  603. let proto = null;
  604. if (element) {
  605. if (element.inst) proto = element.inst.constructor.prototype;
  606. else proto = element.constructor.prototype;
  607. }
  608. return proto || null;
  609. }
  610.  
  611. let done = 0;
  612. let main = async (q) => {
  613.  
  614. if (done) return;
  615.  
  616. if (!q) return;
  617. let m1 = nodeParent(q);
  618. let m2 = q;
  619. if (!(m1 && m1.id === 'item-offset' && m2 && m2.id === 'items')) return;
  620.  
  621. done = 1;
  622.  
  623. Promise.resolve().then(watchUserCSS);
  624.  
  625. addCss();
  626.  
  627. setupStyle(m1, m2);
  628.  
  629. let lcRendererWR = null;
  630.  
  631. const lcRendererElm = () => {
  632. let lcRenderer = kRef(lcRendererWR);
  633. if (!lcRenderer || !lcRenderer.isConnected) {
  634. lcRenderer = document.querySelector('yt-live-chat-item-list-renderer.yt-live-chat-renderer');
  635. lcRendererWR = lcRenderer ? mWeakRef(lcRenderer) : null;
  636. }
  637. return lcRenderer
  638. };
  639.  
  640. let hasFirstShowMore = false;
  641.  
  642. const visObserverFn = (entry) => {
  643.  
  644. const target = entry.target;
  645. if (!target) return;
  646. let isVisible = entry.isIntersecting === true && entry.intersectionRatio > 0.5;
  647. const h = entry.boundingClientRect.height;
  648. if (h < 16) { // wrong: 8 (padding/margin); standard: 32; test: 16 or 20
  649. // e.g. under fullscreen. the element created but not rendered.
  650. target.setAttribute('wSr93', '');
  651. return;
  652. }
  653. if (isVisible) {
  654. target.style.setProperty('--wsr94', h + 'px');
  655. target.setAttribute('wSr93', 'visible');
  656. if (nNextElem(target) === null) {
  657. // firstVisibleItemDetected = true;
  658. /*
  659. if (dateNow() - lastScroll < 80) {
  660. lastLShow = 0;
  661. lastScroll = 0;
  662. Promise.resolve().then(clickShowMore);
  663. } else {
  664. lastLShow = dateNow();
  665. }
  666. */
  667. // lastLShow = dateNow();
  668. } else if (!hasFirstShowMore) { // should more than one item being visible
  669. // implement inside visObserver to ensure there is sufficient delay
  670. hasFirstShowMore = true;
  671. requestAnimationFrame(() => {
  672. // foreground page
  673. // activeDeferredAppendChild = true;
  674. // page visibly ready -> load the latest comments at initial loading
  675. const lcRenderer = lcRendererElm();
  676. if (lcRenderer) {
  677. (lcRenderer.inst || lcRenderer).scrollToBottom_();
  678. }
  679. });
  680. }
  681. }
  682. else if (target.getAttribute('wSr93') === 'visible') { // ignore target.getAttribute('wSr93') === '' to avoid wrong sizing
  683.  
  684. target.style.setProperty('--wsr94', h + 'px');
  685. target.setAttribute('wSr93', 'hidden');
  686. } // note: might consider 0 < entry.intersectionRatio < 0.5 and target.getAttribute('wSr93') === '' <new last item>
  687.  
  688. }
  689.  
  690. const visObserver = new IntersectionObserver((entries) => {
  691.  
  692. for (const entry of entries) {
  693.  
  694. Promise.resolve(entry).then(visObserverFn);
  695.  
  696. }
  697.  
  698. }, {
  699. /*
  700. root: items,
  701. rootMargin: "0px",
  702. threshold: 1.0,
  703. */
  704. // root: HTMLElement.prototype.closest.call(m2, '#item-scroller.yt-live-chat-item-list-renderer'), // nullable
  705. rootMargin: "0px",
  706. threshold: [0.05, 0.95],
  707. });
  708.  
  709. //m2.style.visibility='';
  710.  
  711. const mutFn = (items) => {
  712. for (let node = nLastElem(items); node !== null; node = nPrevElem(node)) {
  713. if (node.hasAttribute('wSr93')) break;
  714. node.setAttribute('wSr93', '');
  715. visObserver.observe(node);
  716. }
  717. }
  718.  
  719. const mutObserver = new MutationObserver((mutations) => {
  720. const items = (mutations[0] || 0).target;
  721. if (!items) return;
  722. mutFn(items);
  723. });
  724.  
  725. const setupMutObserver = (m2) => {
  726. mutObserver.disconnect();
  727. mutObserver.takeRecords();
  728. if (m2) {
  729. mutObserver.observe(m2, {
  730. childList: true,
  731. subtree: false
  732. });
  733. mutFn(m2);
  734. }
  735. }
  736.  
  737. setupMutObserver(m2);
  738.  
  739. const mclp = getProto(document.querySelector('yt-live-chat-item-list-renderer'));
  740. if (mclp && mclp.attached) {
  741.  
  742. mclp.attached66 = mclp.attached;
  743. mclp.attached = function () {
  744. let m2 = document.querySelector('#item-offset.style-scope.yt-live-chat-item-list-renderer > #items.style-scope.yt-live-chat-item-list-renderer');
  745. let m1 = nodeParent(m2);
  746. setupStyle(m1, m2);
  747. setupMutObserver(m2);
  748. return this.attached66();
  749. }
  750.  
  751. mclp.detached66 = mclp.detached;
  752. mclp.detached = function () {
  753. setupMutObserver();
  754. return this.detached66();
  755. }
  756.  
  757. mclp.canScrollToBottom_ = function () {
  758. return this.atBottom && this.allowScroll && !(dateNow() - lastWheel < 80)
  759. }
  760.  
  761. mclp.isSmoothScrollEnabled_ = function () {
  762. return false;
  763. }
  764.  
  765. } else {
  766. console.warn(`proto.attached for yt-live-chat-item-list-renderer is unavailable.`)
  767. }
  768.  
  769.  
  770. let scrollCount = 0;
  771. document.addEventListener('scroll', (evt) => {
  772. if (!evt || !evt.isTrusted) return;
  773. // lastScroll = dateNow();
  774. if (++scrollCount > 1e9) scrollCount = 9;
  775. }, { passive: true, capture: true }) // support contain => support passive
  776.  
  777. // document.addEventListener('scroll', (evt) => {
  778.  
  779. // if (!evt || !evt.isTrusted) return;
  780. // if (!firstVisibleItemDetected) return;
  781. // const isUserAction = dateNow() - lastWheel < 80; // continuous wheel -> continuous scroll -> continuous wheel -> continuous scroll
  782. // if (!isUserAction) return;
  783. // // lastScroll = dateNow();
  784.  
  785. // }, { passive: true, capture: true }) // support contain => support passive
  786.  
  787.  
  788. let lastScrollCount = -1;
  789. document.addEventListener('wheel', (evt) => {
  790.  
  791. if (!evt || !evt.isTrusted) return;
  792. if (lastScrollCount === scrollCount) return;
  793. lastScrollCount = scrollCount;
  794. lastWheel = dateNow();
  795.  
  796. }, { passive: true, capture: true }) // support contain => support passive
  797.  
  798.  
  799. const fp = (renderer) => {
  800. const cnt = renderer.inst || renderer;
  801. const container = (cnt.$ || 0).container;
  802. if (container) {
  803. container.setAttribute = tickerContainerSetAttribute;
  804. }
  805. }
  806. const tags = ["yt-live-chat-ticker-paid-message-item-renderer", "yt-live-chat-ticker-paid-sticker-item-renderer",
  807. "yt-live-chat-ticker-renderer", "yt-live-chat-ticker-sponsor-item-renderer"];
  808. for (const tag of tags) {
  809. const dummy = document.createElement(tag);
  810.  
  811. const cProto = getProto(dummy);
  812. if (!cProto || !cProto.attached) {
  813. console.warn(`proto.attached for ${tag} is unavailable.`)
  814. continue;
  815. }
  816.  
  817. const __updateTimeout__ = cProto.updateTimeout;
  818.  
  819. const canDoUpdateTimeoutReplacement = (() => {
  820.  
  821. if (dummy.countdownMs < 1 && dummy.lastCountdownTimeMs < 1 && dummy.countdownMs < 1 && dummy.countdownDurationMs < 1) {
  822. return typeof dummy.setContainerWidth === 'function' && typeof dummy.slideDown === 'function';
  823. }
  824. return false;
  825.  
  826. })(dummy.inst || dummy) && ((__updateTimeout__ + "").indexOf("window.requestAnimationFrame(this.updateTimeout.bind(this))") > 0);
  827.  
  828.  
  829.  
  830. if (canDoUpdateTimeoutReplacement) {
  831.  
  832. const killTicker = (cnt) => {
  833. if ("auto" === cnt.hostElement.style.width) cnt.setContainerWidth();
  834. cnt.slideDown()
  835. };
  836.  
  837. cProto.__ratio__ = null;
  838. cProto._updateTimeout21_ = function (a) {
  839.  
  840. /*
  841. let pRatio = this.countdownMs / this.countdownDurationMs;
  842. this.countdownMs -= (a - (this.lastCountdownTimeMs || 0));
  843. let noMoreCountDown = this.countdownMs < 1e-6;
  844. let qRatio = this.countdownMs / this.countdownDurationMs;
  845. if(noMoreCountDown){
  846. this.countdownMs = 0;
  847. this.ratio = 0;
  848. } else if( pRatio - qRatio < 0.001 && qRatio < pRatio){
  849.  
  850. }else{
  851. this.ratio = qRatio;
  852. }
  853. */
  854.  
  855. this.countdownMs -= (a - (this.lastCountdownTimeMs || 0));
  856.  
  857. let currentRatio = this.__ratio__;
  858. let tdv = this.countdownMs / this.countdownDurationMs;
  859. let nextRatio = Math.round(tdv * 500) / 500; // might generate 0.143000000001
  860.  
  861. const validCountDown = nextRatio > 0;
  862. const isAttached = this.isAttached;
  863.  
  864. if (!validCountDown) {
  865.  
  866. this.lastCountdownTimeMs = null;
  867.  
  868. this.countdownMs = 0;
  869. this.__ratio__ = null;
  870. this.ratio = 0;
  871.  
  872. if (isAttached) Promise.resolve(this).then(killTicker);
  873.  
  874. } else if (!isAttached) {
  875.  
  876. this.lastCountdownTimeMs = null;
  877.  
  878. } else {
  879.  
  880. this.lastCountdownTimeMs = a;
  881.  
  882. const ratioDiff = currentRatio - nextRatio; // 0.144 - 0.142 = 0.002
  883. if (ratioDiff < 0.001 && ratioDiff > -1e-6) {
  884. // ratioDiff = 0
  885.  
  886. } else {
  887. // ratioDiff = 0.002 / 0.004 ....
  888. // OR ratioDiff < 0
  889.  
  890. this.__ratio__ = nextRatio;
  891.  
  892. this.ratio = nextRatio;
  893. }
  894.  
  895. return true;
  896. }
  897.  
  898. };
  899.  
  900. cProto._updateTimeout21_ = function (a) {
  901. this.countdownMs = Math.max(0, this.countdownMs - (a - (this.lastCountdownTimeMs || 0)));
  902. this.ratio = this.countdownMs / this.countdownDurationMs;
  903. if (this.isAttached && this.countdownMs) {
  904. this.lastCountdownTimeMs = a;
  905. return true;
  906. } else {
  907. this.lastCountdownTimeMs = null;
  908. if (this.isAttached) {
  909. ("auto" === this.hostElement.style.width && this.setContainerWidth(), this.slideDown())
  910. }
  911. }
  912. }
  913.  
  914.  
  915. // temporarily removed; buggy for playback
  916. /*
  917. cProto.updateTimeout = async function (a) {
  918.  
  919. let ret = this._updateTimeout21_(a);
  920. while (ret) {
  921. let a = await new Promise(resolve => {
  922. this.rafId = requestAnimationFrame(resolve)
  923. }); // could be never resolve
  924. ret = this._updateTimeout21_(a);
  925. }
  926.  
  927. };
  928. */
  929.  
  930.  
  931. }
  932.  
  933. cProto.attached77 = cProto.attached
  934.  
  935. cProto.attached = function () {
  936. fp(this.hostElement || this);
  937. return this.attached77();
  938. }
  939.  
  940. for (const elm of document.getElementsByTagName(tag)) {
  941. fp(elm);
  942. }
  943.  
  944.  
  945. }
  946.  
  947. };
  948.  
  949.  
  950. function onReady() {
  951. let tmObserver = new MutationObserver(() => {
  952.  
  953. let p = document.getElementById('items'); // fast
  954. if (!p) return;
  955. let q = document.querySelector('#item-offset.style-scope.yt-live-chat-item-list-renderer > #items.style-scope.yt-live-chat-item-list-renderer'); // check
  956.  
  957. if (q) {
  958. tmObserver.disconnect();
  959. tmObserver.takeRecords();
  960. tmObserver = null;
  961. Promise.resolve(q).then((q) => {
  962. // confirm Promis.resolve() is resolveable
  963. // execute main without direct blocking
  964. main(q);
  965. })
  966. }
  967.  
  968. });
  969.  
  970. tmObserver.observe(document.body || document.documentElement, {
  971. childList: true,
  972. subtree: true
  973. });
  974.  
  975. }
  976.  
  977. Promise.resolve().then(() => {
  978.  
  979. if (document.readyState !== 'loading') {
  980. onReady();
  981. } else {
  982. window.addEventListener("DOMContentLoaded", onReady, false);
  983. }
  984.  
  985. });
  986.  
  987. })({ Promise, requestAnimationFrame, IntersectionObserver });