YouTube 超快聊天

YouTube直播聊天的终极性能提升

当前为 2023-12-20 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Super Fast Chat
  3. // @version 0.60.33
  4. // @license MIT
  5. // @name:ja YouTube スーパーファーストチャット
  6. // @name:zh-TW YouTube 超快聊天
  7. // @name:zh-CN YouTube 超快聊天
  8. // @icon https://github.com/cyfung1031/userscript-supports/raw/main/icons/super-fast-chat.png
  9. // @namespace UserScript
  10. // @match https://www.youtube.com/live_chat*
  11. // @match https://www.youtube.com/live_chat_replay*
  12. // @author CY Fung
  13. // @run-at document-start
  14. // @grant none
  15. // @unwrap
  16. // @allFrames true
  17. // @inject-into page
  18. // @require https://greasyfork.org/scripts/475632-ytconfighacks/code/ytConfigHacks.js?version=1252732
  19. //
  20. // @compatible firefox Violentmonkey
  21. // @compatible firefox Tampermonkey
  22. // @compatible firefox FireMonkey
  23. // @compatible chrome Violentmonkey
  24. // @compatible chrome Tampermonkey
  25. // @compatible opera Violentmonkey
  26. // @compatible opera Tampermonkey
  27. // @compatible safari Stay
  28. // @compatible edge Violentmonkey
  29. // @compatible edge Tampermonkey
  30. // @compatible brave Violentmonkey
  31. // @compatible brave Tampermonkey
  32. //
  33. // @description Ultimate Performance Boost for YouTube Live Chats
  34. // @description:ja YouTubeのライブチャットの究極のパフォーマンスブースト
  35. // @description:zh-TW YouTube直播聊天的終極性能提升
  36. // @description:zh-CN YouTube直播聊天的终极性能提升
  37. //
  38. // ==/UserScript==
  39.  
  40. ((__CONTEXT__) => {
  41. 'use strict';
  42.  
  43. const ENABLE_REDUCED_MAXITEMS_FOR_FLUSH = true; // TRUE to enable trimming down to MAX_ITEMS_FOR_FULL_FLUSH (25) messages when there are too many unrendered messages
  44. const MAX_ITEMS_FOR_TOTAL_DISPLAY = 90; // By default, 250 latest messages will be displayed, but displaying MAX_ITEMS_FOR_TOTAL_DISPLAY (90) messages is already sufficient.
  45. const MAX_ITEMS_FOR_FULL_FLUSH = 25; // If there are too many new (stacked) messages not yet rendered, clean all and flush MAX_ITEMS_FOR_FULL_FLUSH (25) latest messages then incrementally added back to MAX_ITEMS_FOR_TOTAL_DISPLAY (90) messages
  46.  
  47. const ENABLE_NO_SMOOTH_TRANSFORM = true; // Depends on whether you want the animation effect for new chat messages
  48. const USE_OPTIMIZED_ON_SCROLL_ITEMS = true; // TRUE for the majority
  49. const USE_WILL_CHANGE_CONTROLLER = false; // FALSE for the majority
  50. const ENABLE_DELAYED_CHAT_OCCURRENCE_PREFERRED = true; // In Chrome, the rendering of new chat messages could be too fast for no smooth transform. 80ms delay of displaying new messages should be sufficient for element rendering.
  51. const ENABLE_OVERFLOW_ANCHOR_PREFERRED = true; // Enable `overflow-anchor: auto` to lock the scroll list at the bottom for no smooth transform.
  52.  
  53. const FIX_SHOW_MORE_BUTTON_LOCATION = true; // When there are voting options (bottom panel), move the "show more" button to the top.
  54. const FIX_INPUT_PANEL_OVERFLOW_ISSUE = true; // When the super chat button is flicking with color, the scrollbar might come out.
  55. const FIX_INPUT_PANEL_BORDER_ISSUE = true; // No border should be allowed if there is an empty input panel.
  56. const SET_CONTAIN_FOR_CHATROOM = true; // Rendering hacks (`contain`) for chatroom elements. [ General ]
  57.  
  58. const FORCE_CONTENT_VISIBILITY_UNSET = true; // Content-visibility should be always VISIBLE for high performance and great rendering.
  59. const FORCE_WILL_CHANGE_UNSET = true; // Will-change should be always UNSET (auto) for high performance and low energy impact.
  60.  
  61. // Replace requestAnimationFrame timers with custom implementation
  62. const ENABLE_RAF_HACK_TICKERS = true; // When there is a ticker
  63. const ENABLE_RAF_HACK_DOCKED_MESSAGE = true; // To be confirmed
  64. const ENABLE_RAF_HACK_INPUT_RENDERER = true; // To be confirmed
  65. const ENABLE_RAF_HACK_EMOJI_PICKER = true; // When changing the page of the emoji picker
  66.  
  67. // Force rendering all the character subsets of the designated font(s) before messages come (Pre-Rendering of Text)
  68. const ENABLE_FONT_PRE_RENDERING_PREFERRED = 1 | 2 | 4 | 8 | 16;
  69.  
  70. // Backdrop `filter: blur(4px)` inside the iframe can extend to the whole page, causing a negative visual impact on the video you are watching.
  71. const NO_BACKDROP_FILTER_WHEN_MENU_SHOWN = true;
  72.  
  73. // Data Manipulation for Participants (Participant List)
  74. // << if DO_PARTICIPANT_LIST_HACKS >>
  75. const DO_PARTICIPANT_LIST_HACKS = true; // TRUE for the majority
  76. const SHOW_PARTICIPANT_CHANGES_IN_CONSOLE = false; // Just too annoying to show them all in popular chat
  77. const CHECK_CHANGE_TO_PARTICIPANT_RENDERER_CONTENT = true; // Only consider changes in renderable content (not concerned with the last chat message of the participants)
  78. const PARTICIPANT_UPDATE_ONLY_ONLY_IF_MODIFICATION_DETECTED = true;
  79. // << end >>
  80.  
  81. // show more button
  82. const ENABLE_SHOW_MORE_BLINKER = true; // BLINK WHEN NEW MESSAGES COME
  83.  
  84. // faster stampDomArray_ for participants list creation
  85. const ENABLE_FLAGS_MAINTAIN_STABLE_LIST_VAL = 1; // 0 - OFF; 1 - ON; 2 - ON(PARTICIPANTS_LIST ONLY)
  86. const USE_MAINTAIN_STABLE_LIST_ONLY_WHEN_KS_FLAG_IS_SET = false;
  87.  
  88. // reuse yt components
  89. const ENABLE_FLAGS_REUSE_COMPONENTS = true;
  90.  
  91. // images <Group#I01>
  92. const AUTHOR_PHOTO_SINGLE_THUMBNAIL = 1; // 0 - disable; 1- smallest; 2- largest
  93. const EMOJI_IMAGE_SINGLE_THUMBNAIL = 1; // 0 - disable; 1- smallest; 2- largest
  94. const LEAST_IMAGE_SIZE = 48; // minium size = 48px
  95.  
  96. const DO_LINK_PREFETCH = true; // DO NOT CHANGE
  97. // << if DO_LINK_PREFETCH >>
  98. const ENABLE_BASE_PREFETCHING = true; // (SUB-)DOMAIN | dns-prefetch & preconnect
  99. const ENABLE_PRELOAD_THUMBNAIL = true; // subresource (prefetch) [LINK for Images]
  100. const PREFETCH_LIMITED_SIZE_EMOJI = 512; // DO NOT CHANGE THIS
  101. const PREFETCH_LIMITED_SIZE_AUTHOR_PHOTO = 68; // DO NOT CHANGE THIS
  102. // << end >>
  103.  
  104. const FIX_SETSRC_AND_THUMBNAILCHANGE_ = true; // Function Replacement for yt-img-shadow....
  105. const FIX_THUMBNAIL_DATACHANGED = true; // Function Replacement for yt-live-chat-author-badge-renderer..dataChanged
  106. // const REMOVE_PRELOADAVATARFORADDACTION = false; // Function Replacement for yt-live-chat-renderer..preloadAvatarForAddAction
  107.  
  108. const FIX_THUMBNAIL_SIZE_ON_ITEM_ADDITION = true; // important [depends on <Group#I01>]
  109. const FIX_THUMBNAIL_SIZE_ON_ITEM_REPLACEMENT = true; // [depends on <Group#I01>]
  110.  
  111. const ATTEMPT_ANIMATED_TICKER_BACKGROUND = 'steps' // false OR '' for disabled, 'linear', 'steps' for easing-function
  112. // << if ATTEMPT_ANIMATED_TICKER_BACKGROUND >>
  113. // BROWSER SUPPORT: Chrome 75+, Edge 79+, Safari 13.1+, Firefox 63+, Opera 62+
  114. const TICKER_MAX_STEPS_LIMIT = 500; // NOT LESS THAN 5 STEPS!!
  115. // [limiting 500 max steps] is recommended for "confortable visual change"
  116. // min. step increment 0.2% => max steps: 500 => 800ms per each update
  117. // min. step increment 0.5% => max steps: 200 => 1000ms per each update
  118. // min. step increment 1.0% => max steps: 100 => 1000ms per each update
  119. // min. step increment 2.5% => max steps: 40 => 1000ms per each update
  120. // min. step increment 5.0% => max steps: 20 => 1250ms per each update
  121. const ENABLE_VIDEO_PLAYBACK_PROGRESS_STATE_FIX = true; // for video playback's ticker issue. [ Playback Replay - Pause at Middle - Backwards Seeking ]
  122. // << end >>
  123.  
  124. const FIX_TOOLTIP_DISPLAY = true;
  125. const USE_VANILLA_DEREF = true;
  126. const FIX_DROPDOWN_DERAF = true; // DONT CHANGE
  127.  
  128.  
  129. const CACHE_SHOW_CONTEXT_MENU_FOR_REOPEN = true; // cache the menu data and used for the next reopen
  130. const ADVANCED_NOT_ALLOW_SCROLL_FOR_SHOW_CONTEXT_MENU = true; // pause auto scroll faster when the context menu is about to show
  131. const ENABLE_MUTEX_FOR_SHOW_CONTEXT_MENU = true; // avoid multiple requests on the same time
  132.  
  133. const BOOST_MENU_OPENCHANGED_RENDERING = true;
  134. const FIX_CLICKING_MESSAGE_MENU_DISPLAY_ON_MOUSE_CLICK = true; // click again = close
  135. const NO_ITEM_TAP_FOR_NON_STATIONARY_TAP = true; // dont open the menu (e.g. text message) if cursor is moved or long press
  136. const TAP_ACTION_DURATION = 280; // exceeding 280ms would not consider as a tap action
  137. const PREREQUEST_CONTEXT_MENU_ON_MOUSE_DOWN = true; // require CACHE_SHOW_CONTEXT_MENU_FOR_REOPEN = true
  138. // const FIX_MENU_CAPTURE_SCROLL = true;
  139. const CHAT_MENU_REFIT_ALONG_SCROLLING = 0; // 0 for locking / default; 1 for unlocking only; 2 for unlocking and refit
  140.  
  141. const RAF_FIX_keepScrollClamped = true;
  142. const RAF_FIX_scrollIncrementally = 2; // 0: no action; 1: basic fix; 2: also fix scroll position
  143.  
  144. // << if BOOST_MENU_OPENCHANGED_RENDERING >>
  145. const FIX_MENU_POSITION_N_SIZING_ON_SHOWN = 1; // correct size and position when the menu dropdown opens
  146.  
  147. const CHECK_JSONPRUNE = true; // This is a bug in Brave
  148. // << end >>
  149.  
  150. // const LIVE_CHAT_FLUSH_ON_FOREGROUND_ONLY = false;
  151.  
  152. const CHANGE_DATA_FLUSH_ASYNC = false;
  153. // CHANGE_DATA_FLUSH_ASYNC is disabled due to bug report: https://greasyfork.org/scripts/469878-youtube-super-fast-chat/discussions/199479
  154. // to be further investigated
  155.  
  156. const CHANGE_MANAGER_UNSUBSCRIBE = true;
  157.  
  158. const INTERACTIVITY_BACKGROUND_ANIMATION = 1; // mostly for pinned message
  159. // 0 = default Yt animation background [= no fix];
  160. // 1 = disable default animation background [= keep special animation];
  161. // 2 = disable all animation backgrounds [= no animation backbround]
  162.  
  163. const CLOSE_TICKER_PINNED_MESSAGE_WHEN_HEADER_CLICKED = true;
  164.  
  165. const MAX_TOOLTIP_NO_WRAP_WIDTH = '72vw'; // '' for disable; accept values like '60px', '25vw'
  166.  
  167. const AMEND_TICKER_handleLiveChatAction = true; // to fix ticker duplication and unresponsively fast ticker generation
  168.  
  169. const ATTEMPT_TICKER_ANIMATION_START_TIME_DETECTION = true;
  170. const ADJUST_TICKER_DURATION_ALIGN_RENDER_TIME = true;
  171. const FIX_BATCH_TICKER_ORDER = true;
  172.  
  173. const DISABLE_Translation_By_Google = true;
  174.  
  175. const FASTER_ICON_RENDERING = true;
  176.  
  177. // ========= EXPLANTION FOR 0.2% @ step timing [min. 0.2%] ===========
  178. /*
  179.  
  180. ### Time Approach
  181.  
  182. // all below values can make the time interval > 250ms
  183. // 250ms (practical value) refers to the minimum frequency for timeupdate in most browsers (typically, shorter timeupdate interval in modern browsers)
  184. if (totalDuration > 400000) stepInterval = 0.2; // 400000ms with 0.2% increment => 800ms
  185. else if (totalDuration > 200000) stepInterval = 0.5; // 200000ms with 0.5% increment => 1000ms
  186. else if (totalDuration > 100000) stepInterval = 1; // 100000ms with 1% increment => 1000ms
  187. else if (totalDuration > 50000) stepInterval = 2; // 50000ms with 2% increment => 1000ms
  188. else if (totalDuration > 25000) stepInterval = 5; // 25000ms with 5% increment => 1250ms
  189.  
  190. ### Pixel Check
  191. // Target Max Pixel Increment < 5px for Short Period Ticker (Rapid Background Change)
  192. // Assume total width <= 99px for short period ticker, like small donation & member welcome
  193. 99px * 5% = 4.95px < 5px [Condition Fulfilled]
  194.  
  195. ### Example - totalDuration = 280000
  196. totalDuration 280000
  197. stepInterval 0.5
  198. numOfSteps = Math.round(100 / stepInterval) = 200
  199. time interval = 280000 / 200 = 1400ms <acceptable>
  200.  
  201. ### Example - totalDuration = 18000
  202. totalDuration 18000
  203. stepInterval 5
  204. numOfSteps = Math.round(100 / stepInterval) = 20
  205. time interval = 18000 / 20 = 900ms <acceptable>
  206.  
  207. ### Example - totalDuration = 5000
  208. totalDuration 5000
  209. stepInterval 5
  210. numOfSteps = Math.round(100 / stepInterval) = 20
  211. time interval = 5000 / 20 = 250ms <threshold value>
  212.  
  213. ### Example - totalDuration = 3600
  214. totalDuration 3600
  215. stepInterval 5
  216. numOfSteps = Math.round(100 / stepInterval) = 20
  217. time interval = 3600 / 20 = 180ms <reasonable for 3600ms ticker>
  218.  
  219. */
  220.  
  221. // =======================================================================================================
  222.  
  223. // AUTOMAICALLY DETERMINED
  224. const ENABLE_FLAGS_MAINTAIN_STABLE_LIST = ENABLE_FLAGS_MAINTAIN_STABLE_LIST_VAL === 1;
  225. const ENABLE_FLAGS_MAINTAIN_STABLE_LIST_FOR_PARTICIPANTS_LIST = ENABLE_FLAGS_MAINTAIN_STABLE_LIST_VAL >= 1;
  226. const CHAT_MENU_SCROLL_UNLOCKING = CHAT_MENU_REFIT_ALONG_SCROLLING >= 1;
  227. let runTickerClassName = 'run-ticker';
  228.  
  229. const dummyImgURL = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  230. /*
  231. WebP: data:image/webp;base64,UklGRjAB
  232. PNG: data:image/png;base64,iVBORw0KGg==
  233. JPEG: data:image/jpeg;base64,/9j/4AA=
  234. GIF: data:image/gif;base64,R0lGODlhAQABAIA=
  235. BMP: data:image/bmp;base64,Qk1oAAAA
  236. SVG: data:image/svg+xml;base64,PHN2Zy8+Cg==
  237.  
  238. WebP: data:image/webp;base64,AAAAAAA=
  239. PNG: data:image/png;base64,AAAAAAA=
  240. JPEG: data:image/jpeg;base64,AAAAAAA=
  241. GIF: data:image/gif;base64,AAAAAAA=
  242. BMP: data:image/bmp;base64,AAAAAAA=
  243.  
  244. data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
  245.  
  246.  
  247. */
  248.  
  249. // image sizing code
  250. // (d = (d = KC(a.customThumbnail.thumbnails, 16)) ? lc(oc(d)) : null)
  251.  
  252.  
  253. // function KC(a, b, c, d) {
  254. // d = void 0 === d ? "width" : d;
  255. // if (!a || !a.length)
  256. // return null;
  257. // if (z("kevlar_tuner_should_always_use_device_pixel_ratio")) {
  258. // var e = window.devicePixelRatio;
  259. // z("kevlar_tuner_should_clamp_device_pixel_ratio") ? e = Math.min(e, zl("kevlar_tuner_clamp_device_pixel_ratio")) : z("kevlar_tuner_should_use_thumbnail_factor") && (e = zl("kevlar_tuner_thumbnail_factor"));
  260. // HC = e
  261. // } else
  262. // HC || (HC = window.devicePixelRatio);
  263. // e = HC;
  264. // z("kevlar_tuner_should_always_use_device_pixel_ratio") ? b *= e : 1 < e && (b *= e);
  265. // if (z("kevlar_tuner_min_thumbnail_quality"))
  266. // return a[0].url || null;
  267. // e = a.length;
  268. // if (z("kevlar_tuner_max_thumbnail_quality"))
  269. // return a[e - 1].url || null;
  270. // if (c)
  271. // for (var h = 0; h < e; h++)
  272. // if (0 <= a[h].url.indexOf(c))
  273. // return a[h].url || null;
  274. // for (c = 0; c < e; c++)
  275. // if (a[c][d] >= b)
  276. // return a[c].url || null;
  277. // for (b = e - 1; 0 < b; b--)
  278. // if (a[b][d])
  279. // return a[b].url || null;
  280. // return a[0].url || null
  281. // }
  282.  
  283. const { IntersectionObserver } = __CONTEXT__;
  284.  
  285. /** @type {globalThis.PromiseConstructor} */
  286. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  287.  
  288. // let jsonParseFix = null;
  289.  
  290. if (!IntersectionObserver) return console.warn("Your browser does not support IntersectionObserver.\nPlease upgrade to the latest version.");
  291. if (typeof WebAssembly !== 'object') return console.warn("Your browser is too old.\nPlease upgrade to the latest version."); // for passive and once
  292.  
  293. // necessity of cssText3_smooth_transform_position to be checked.
  294. const cssText3_smooth_transform_position = ENABLE_NO_SMOOTH_TRANSFORM ? `
  295.  
  296. #item-offset.style-scope.yt-live-chat-item-list-renderer > #items.style-scope.yt-live-chat-item-list-renderer {
  297. position: static !important;
  298. }
  299.  
  300. `: '';
  301.  
  302. // fallback if dummy style fn fails
  303. const cssText4_smooth_transform_forced_props = ENABLE_NO_SMOOTH_TRANSFORM ? `
  304.  
  305. /* optional */
  306. #item-offset.style-scope.yt-live-chat-item-list-renderer {
  307. height: auto !important;
  308. min-height: unset !important;
  309. }
  310.  
  311. #items.style-scope.yt-live-chat-item-list-renderer {
  312. transform: translateY(0px) !important;
  313. }
  314.  
  315. /* optional */
  316.  
  317. `: '';
  318.  
  319. const cssText5 = SET_CONTAIN_FOR_CHATROOM ? `
  320.  
  321. /* ------------------------------------------------------------------------------------------------------------- */
  322.  
  323. 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 {
  324. contain: layout style;
  325. }
  326.  
  327. #items.style-scope.yt-live-chat-item-list-renderer {
  328. contain: layout paint style;
  329. }
  330.  
  331. #item-offset.style-scope.yt-live-chat-item-list-renderer {
  332. contain: style;
  333. }
  334.  
  335. #item-scroller.style-scope.yt-live-chat-item-list-renderer {
  336. contain: size style;
  337. }
  338.  
  339. #contents.style-scope.yt-live-chat-item-list-renderer, #chat.style-scope.yt-live-chat-renderer, img.style-scope.yt-img-shadow[width][height] {
  340. contain: size layout paint style;
  341. }
  342.  
  343. .style-scope.yt-live-chat-ticker-renderer[role="button"][aria-label], .style-scope.yt-live-chat-ticker-renderer[role="button"][aria-label] > #container {
  344. contain: layout paint style;
  345. }
  346.  
  347. 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 {
  348. contain: layout style;
  349. }
  350.  
  351. tp-yt-paper-tooltip[style*="inset"][role="tooltip"] {
  352. contain: layout paint style;
  353. }
  354.  
  355. /* ------------------------------------------------------------------------------------------------------------- */
  356.  
  357. ` : '';
  358.  
  359. const cssText6b_show_more_button = FIX_SHOW_MORE_BUTTON_LOCATION ? `
  360.  
  361. yt-live-chat-renderer[has-action-panel-renderer] #show-more.yt-live-chat-item-list-renderer{
  362. top: 4px;
  363. transition-property: top;
  364. bottom: unset;
  365. }
  366.  
  367. yt-live-chat-renderer[has-action-panel-renderer] #show-more.yt-live-chat-item-list-renderer[disabled]{
  368. top: -42px;
  369. }
  370.  
  371. `: '';
  372.  
  373. const cssText6c_input_panel_overflow = FIX_INPUT_PANEL_OVERFLOW_ISSUE ? `
  374.  
  375. #input-panel #picker-buttons yt-live-chat-icon-toggle-button-renderer#product-picker {
  376. contain: layout style;
  377. }
  378.  
  379. #chat.yt-live-chat-renderer ~ #panel-pages.yt-live-chat-renderer {
  380. overflow: visible;
  381. }
  382.  
  383. `: '';
  384.  
  385. const cssText6d_input_panel_border = FIX_INPUT_PANEL_BORDER_ISSUE ? `
  386.  
  387. html #panel-pages.yt-live-chat-renderer > #input-panel.yt-live-chat-renderer:not(:empty) {
  388. --yt-live-chat-action-panel-top-border: none;
  389. }
  390.  
  391. html #panel-pages.yt-live-chat-renderer > #input-panel.yt-live-chat-renderer.iron-selected > *:first-child {
  392. border-top: 1px solid var(--yt-live-chat-panel-pages-border-color);
  393. }
  394.  
  395. html #panel-pages.yt-live-chat-renderer {
  396. border-top: 0;
  397. border-bottom: 0;
  398. }
  399.  
  400. `: '';
  401.  
  402. const cssText7b_content_visibility_unset = FORCE_CONTENT_VISIBILITY_UNSET ? `
  403.  
  404. img,
  405. yt-img-shadow[height][width],
  406. yt-img-shadow {
  407. content-visibility: visible !important;
  408. }
  409.  
  410. ` : '';
  411.  
  412. const cssText7c_will_change_unset = FORCE_WILL_CHANGE_UNSET ? `
  413.  
  414. /* remove YouTube constant will-change */
  415. /* constant value will slow down the performance; default auto */
  416.  
  417. /* www-player.css */
  418. html .ytp-contextmenu,
  419. html .ytp-settings-menu {
  420. will-change: unset;
  421. }
  422.  
  423. /* frequently matched elements */
  424. html .fill.yt-interaction,
  425. html .stroke.yt-interaction,
  426. html .yt-spec-touch-feedback-shape__fill,
  427. html .yt-spec-touch-feedback-shape__stroke {
  428. will-change: unset;
  429. }
  430.  
  431. /* live_chat_polymer.js */
  432. /*
  433. html .toggle-button.tp-yt-paper-toggle-button,
  434. html #primaryProgress.tp-yt-paper-progress,
  435. html #secondaryProgress.tp-yt-paper-progress,
  436. html #onRadio.tp-yt-paper-radio-button,
  437. html .fill.yt-interaction,
  438. html .stroke.yt-interaction,
  439. html .yt-spec-touch-feedback-shape__fill,
  440. html .yt-spec-touch-feedback-shape__stroke {
  441. will-change: unset;
  442. }
  443. */
  444.  
  445. /* desktop_polymer_enable_wil_icons.js */
  446. /* html .fill.yt-interaction,
  447. html .stroke.yt-interaction, */
  448. html tp-yt-app-header::before,
  449. html tp-yt-iron-list,
  450. html #items.tp-yt-iron-list > *,
  451. html #onRadio.tp-yt-paper-radio-button,
  452. html .toggle-button.tp-yt-paper-toggle-button,
  453. html ytd-thumbnail-overlay-toggle-button-renderer[use-expandable-tooltip] #label.ytd-thumbnail-overlay-toggle-button-renderer,
  454. html #items.ytd-post-multi-image-renderer,
  455. html #items.ytd-horizontal-card-list-renderer,
  456. html #items.yt-horizontal-list-renderer,
  457. html #left-arrow.yt-horizontal-list-renderer,
  458. html #right-arrow.yt-horizontal-list-renderer,
  459. html #items.ytd-video-description-infocards-section-renderer,
  460. html #items.ytd-video-description-music-section-renderer,
  461. html #chips.ytd-feed-filter-chip-bar-renderer,
  462. html #chips.yt-chip-cloud-renderer,
  463. html #items.ytd-merch-shelf-renderer,
  464. html #items.ytd-product-details-image-carousel-renderer,
  465. html ytd-video-preview,
  466. html #player-container.ytd-video-preview,
  467. html #primaryProgress.tp-yt-paper-progress,
  468. html #secondaryProgress.tp-yt-paper-progress,
  469. html ytd-miniplayer[enabled] /* ,
  470. html .yt-spec-touch-feedback-shape__fill,
  471. html .yt-spec-touch-feedback-shape__stroke */ {
  472. will-change: unset;
  473. }
  474.  
  475. /* other */
  476. .ytp-videowall-still-info-content[class],
  477. .ytp-suggestion-image[class] {
  478. will-change: unset !important;
  479. }
  480.  
  481. ` : '';
  482.  
  483. const ENABLE_FONT_PRE_RENDERING = typeof HTMLElement.prototype.append === 'function' ? (ENABLE_FONT_PRE_RENDERING_PREFERRED || 0) : 0;
  484. const cssText8_fonts_pre_render = ENABLE_FONT_PRE_RENDERING ? `
  485.  
  486. elzm-fonts {
  487. visibility: collapse;
  488. position: fixed;
  489. top: -10px;
  490. left: -10px;
  491. font-size: 10pt;
  492. line-height: 100%;
  493. width: 100px;
  494. height: 100px;
  495. transform: scale(0.1);
  496. transform: scale(0.01);
  497. transform: scale(0.001);
  498. transform-origin: 0 0;
  499. contain: strict;
  500. display: block;
  501.  
  502. pointer-events: none !important;
  503. user-select: none !important;
  504. }
  505.  
  506. elzm-fonts[id]#elzm-fonts-yk75g {
  507. user-select: none !important;
  508. pointer-events: none !important;
  509. }
  510.  
  511. elzm-font {
  512. visibility: collapse;
  513. position: absolute;
  514. line-height: 100%;
  515. width: 100px;
  516. height: 100px;
  517. contain: strict;
  518. display: block;
  519.  
  520. user-select: none !important;
  521. pointer-events: none !important;
  522. }
  523.  
  524. elzm-font::before {
  525. visibility: collapse;
  526. position: absolute;
  527. line-height: 100%;
  528. width: 100px;
  529. height: 100px;
  530. contain: strict;
  531. display: block;
  532.  
  533. content: '0aZ!@#$~^&*()_-+[]{}|;:><?\\0460\\0301\\0900\\1F00\\0370\\0102\\0100\\28EB2\\28189\\26DA0\\25A9C\\249BB\\23F61\\22E8B\\21927\\21076\\2048E\\1F6F5\\FF37\\F94F\\F0B2\\9F27\\9D9A\\9BEA\\9A6B\\98EC\\9798\\9602\\949D\\9370\\926B\\913A\\8FA9\\8E39\\8CC1\\8B26\\8983\\8804\\8696\\8511\\83BC\\828D\\8115\\7F9A\\7E5B\\7D07\\7B91\\7A2C\\78D2\\776C\\7601\\74AA\\73B9\\7265\\70FE\\6FBC\\6E88\\6D64\\6C3F\\6A9C\\6957\\67FE\\66B3\\6535\\63F2\\628E\\612F\\5FE7\\5E6C\\5CEE\\5B6D\\5A33\\58BC\\575B\\5611\\54BF\\536E\\51D0\\505D\\4F22\\4AD1\\41DB\\3B95\\3572\\2F3F\\26FD\\25A1\\2477\\208D\\1D0A\\1FB\\A1\\A3\\B4\\2CB\\60\\10C\\E22\\A5\\4E08\\B0\\627\\2500\\5E\\201C\\3C\\B7\\23\\26\\3E\\D\\20\\25EE8\\1F235\\FFD7\\FA10\\F92D\\9E8B\\9C3E\\9AE5\\98EB\\971D\\944A\\92BC\\9143\\8F52\\8DC0\\8B2D\\8973\\87E2\\8655\\84B4\\82E8\\814A\\7F77\\7D57\\7BC8\\7A17\\7851\\768C\\7511\\736C\\7166\\6F58\\6D7C\\6B85\\69DD\\6855\\667E\\64D2\\62CF\\6117\\5F6C\\5D9B\\5BBC\\598B\\57B3\\5616\\543F\\528D\\50DD\\4F57\\4093\\3395\\32B5\\31C8\\3028\\2F14\\25E4\\24D1\\2105\\2227\\A8\\2D9\\2CA\\2467\\B1\\2020\\2466\\251C\\266B\\AF\\4E91\\221E\\2464\\2266\\2207\\4E32\\25B3\\2463\\2010\\2103\\3014\\25C7\\24\\25BD\\4E18\\2460\\21D2\\2015\\2193\\4E03\\7E\\25CB\\2191\\25BC\\3D\\500D\\4E01\\25\\30F6\\2605\\266A\\40\\2B\\4E16\\7C\\A9\\4E\\21\\1F1E9\\FEE3\\F0A7\\9F3D\\9DFA\\9C3B\\9A5F\\98C8\\972A\\95B9\\94E7\\9410\\92B7\\914C\\8FE2\\8E2D\\8CAF\\8B5E\\8A02\\8869\\86E4\\8532\\83B4\\82A9\\814D\\7FFA\\7ED7\\7DC4\\7CCC\\7BC3\\7ACA\\797C\\783E\\770F\\760A\\74EF\\73E7\\72DD\\719C\\7005\\6ED8\\6DC3\\6CB2\\6A01\\68E1\\6792\\663A\\64F8\\63BC\\623B\\60FA\\5FD1\\5EA3\\5D32\\5BF5\\5AB2\\5981\\5831\\570A\\5605\\5519\\53FB\\52A2\\5110\\4FE3\\4EB8\\3127\\279C\\2650\\254B\\23E9\\207B\\1D34\\2AE\\176\\221A\\161\\200B\\300C\\4E4C\\1F921\\FF78\\FA0A\\F78A\\9EB9\\9D34\\9BD3\\9A6F\\9912\\97C6\\964E\\950C\\93E4\\92E5\\91F0\\90BB\\8F68\\8E18\\8B6C\\89F6\\889B\\874C\\8602\\84B1\\8378\\826E\\8113\\7FB1\\7EAF\\7D89\\7C20\\7AFB\\7988\\7840\\7705\\75CC\\749A\\73B3\\727F\\7113\\6FE8\\6ED6\\6DD3\\6CDA\\6BBB\\6A31\\6900\\67D9\\66A7\\655D\\6427\\630D\\61C6\\60AC\\5F78\\5E34\\5CE0\\5B80\\5A51\\590B\\57A1\\566F\\5551\\543D\\52DB\\518F\\5032\\3A17\\305C\\2749\\264A\\2567\\2476\\2139\\1EC0\\11AF\\2C8\\1AF\\E17\\2190\\2022\\2502\\2312\\2025\\50';
  534.  
  535. user-select: none !important;
  536. pointer-events: none !important;
  537. }
  538.  
  539. `: '';
  540.  
  541. const cssText9_no_backdrop_filter_when_menu_shown = NO_BACKDROP_FILTER_WHEN_MENU_SHOWN ? `
  542. tp-yt-iron-dropdown.yt-live-chat-app ytd-menu-popup-renderer {
  543. -webkit-backdrop-filter: none;
  544. backdrop-filter: none;
  545. }
  546. `: '';
  547.  
  548. const cssText10_show_more_blinker = ENABLE_SHOW_MORE_BLINKER ? `
  549.  
  550. @keyframes blinker-miuzp {
  551. 0%, 60%, 100% {
  552. opacity: 1;
  553. }
  554. 30% {
  555. opacity: 0.6;
  556. }
  557. }
  558.  
  559. yt-icon-button#show-more.has-new-messages-miuzp {
  560. animation: blinker-miuzp 1.74s linear infinite;
  561. }
  562.  
  563. `: '';
  564.  
  565. const cssText11_entire_message_clickable = FIX_CLICKING_MESSAGE_MENU_DISPLAY_ON_MOUSE_CLICK ? `
  566.  
  567. yt-live-chat-paid-message-renderer.yt-live-chat-item-list-renderer[whole-message-clickable] #menu.style-scope[class] {
  568. pointer-events: none !important;
  569. }
  570.  
  571. yt-live-chat-membership-item-renderer.yt-live-chat-item-list-renderer[whole-message-clickable] #menu.style-scope[class] {
  572. pointer-events: none !important;
  573. }
  574.  
  575. yt-live-chat-paid-sticker-renderer.yt-live-chat-item-list-renderer[whole-message-clickable] #menu.style-scope[class] {
  576. pointer-events: none !important;
  577. }
  578.  
  579. yt-live-chat-text-message-renderer.yt-live-chat-item-list-renderer[whole-message-clickable] #menu.style-scope[class] {
  580. pointer-events: none !important; /* TO_BE_REVIEWED */
  581. }
  582.  
  583. yt-live-chat-auto-mod-message-renderer.yt-live-chat-item-list-renderer[whole-message-clickable] #menu.style-scope[class] {
  584. pointer-events: none !important;
  585. }
  586.  
  587. `: '';
  588.  
  589. const cssText12_nowrap_tooltip = MAX_TOOLTIP_NO_WRAP_WIDTH && typeof MAX_TOOLTIP_NO_WRAP_WIDTH === 'string' ? `
  590.  
  591.  
  592. tp-yt-paper-tooltip[role="tooltip"] {
  593. box-sizing: content-box !important;
  594. margin: 0px !important;
  595. padding: 0px !important;
  596. contain: none !important;
  597. }
  598.  
  599. tp-yt-paper-tooltip[role="tooltip"] #tooltip[style-target="tooltip"] {
  600. box-sizing: content-box !important;
  601. display: inline-block;
  602. contain: none !important;
  603. }
  604.  
  605.  
  606. tp-yt-paper-tooltip[role="tooltip"] #tooltip[style-target="tooltip"]{
  607. max-width: ${MAX_TOOLTIP_NO_WRAP_WIDTH};
  608. width: max-content;
  609. text-overflow: ellipsis;
  610. overflow: hidden;
  611. white-space: nowrap;
  612. }
  613.  
  614.  
  615. `: '';
  616.  
  617.  
  618. const cssText13_no_text_select_when_menu_visible = `
  619. [menu-visible] {
  620. --sfc47-text-select: none;
  621. }
  622. [menu-visible] #header[id][class],
  623. [menu-visible] #content[id][class],
  624. [menu-visible] #header[id][class] *,
  625. [menu-visible] #content[id][class] * {
  626. user-select: var(--sfc47-text-select) !important;
  627. }
  628. [menu-visible] #menu {
  629. --sfc47-text-select: inherit;
  630. }
  631. `
  632.  
  633.  
  634. const addCss = () => `
  635.  
  636. @property --ticker-rtime {
  637. syntax: "<percentage>";
  638. inherits: false;
  639. initial-value: 0%;
  640. }
  641.  
  642. /*
  643. .run-ticker {
  644. background:linear-gradient(90deg, var(--ticker-c1),var(--ticker-c1) var(--ticker-rtime),var(--ticker-c2) var(--ticker-rtime),var(--ticker-c2));
  645. }
  646.  
  647. .run-ticker-test {
  648. background: #00000001;
  649. }
  650.  
  651. .run-ticker-forced,
  652. yt-live-chat-ticker-renderer #items > * > #container.run-ticker-forced,
  653. yt-live-chat-ticker-renderer[class] #items[class] > *[class] > #container.run-ticker-forced[class]
  654. {
  655. background:linear-gradient(90deg, var(--ticker-c1),var(--ticker-c1) var(--ticker-rtime),var(--ticker-c2) var(--ticker-rtime),var(--ticker-c2)) !important;
  656. }
  657. */
  658.  
  659. .run-ticker {
  660. --ticker-bg:linear-gradient(90deg, var(--ticker-c1),var(--ticker-c1) var(--ticker-rtime),var(--ticker-c2) var(--ticker-rtime),var(--ticker-c2));
  661. }
  662.  
  663. .run-ticker,
  664. yt-live-chat-ticker-renderer #items > * > #container.run-ticker,
  665. yt-live-chat-ticker-renderer[class] #items[class] > *[class] > #container.run-ticker[class]
  666. {
  667. background: var(--ticker-bg) !important;
  668. }
  669.  
  670. yt-live-chat-ticker-dummy777-item-renderer {
  671. background: #00000001;
  672. }
  673.  
  674. yt-live-chat-ticker-dummy777-item-renderer[dummy777] {
  675. position: fixed !important;
  676. top: -1000px !important;
  677. left: -1000px !important;
  678. font-size: 1px !important;
  679. color: transparent !important;
  680. pointer-events: none !important;
  681. z-index: -1 !important;
  682. contain: strict !important;
  683. box-sizing: border-box !important;
  684. pointer-events: none !important;
  685. user-select: none !important;
  686. max-width: 1px !important;
  687. max-height: 1px !important;
  688. overflow: hidden !important;
  689. visibility: collapse !important;
  690. display: none !important;
  691. }
  692.  
  693. yt-live-chat-ticker-dummy777-item-renderer #container {
  694. background: inherit;
  695. }
  696.  
  697.  
  698. ${cssText8_fonts_pre_render}
  699.  
  700. ${cssText9_no_backdrop_filter_when_menu_shown}
  701.  
  702. @supports (contain: layout paint style) {
  703.  
  704. ${cssText5}
  705.  
  706. }
  707.  
  708. @supports (color: var(--general)) {
  709.  
  710. html {
  711. --yt-live-chat-item-list-renderer-padding: 0px 0px;
  712. }
  713.  
  714. ${cssText3_smooth_transform_position}
  715.  
  716. ${cssText7c_will_change_unset}
  717.  
  718. ${cssText7b_content_visibility_unset}
  719.  
  720. yt-live-chat-item-list-renderer:not([allow-scroll]) #item-scroller.yt-live-chat-item-list-renderer {
  721. overflow-y: scroll;
  722. padding-right: 0;
  723. }
  724.  
  725. ${cssText4_smooth_transform_forced_props}
  726.  
  727. yt-icon[icon="down_arrow"] > *, yt-icon-button#show-more > * {
  728. pointer-events: none !important;
  729. }
  730.  
  731. #continuations, #continuations * {
  732. contain: strict;
  733. position: fixed;
  734. top: 2px;
  735. height: 1px;
  736. width: 2px;
  737. height: 1px;
  738. visibility: collapse;
  739. }
  740.  
  741. ${cssText6b_show_more_button}
  742.  
  743. ${cssText6d_input_panel_border}
  744.  
  745. ${cssText6c_input_panel_overflow}
  746.  
  747. }
  748.  
  749.  
  750. @supports (overflow-anchor: auto) {
  751.  
  752. .no-anchor * {
  753. overflow-anchor: none;
  754. }
  755. .no-anchor > item-anchor {
  756. overflow-anchor: auto;
  757. }
  758.  
  759. item-anchor {
  760.  
  761. height:1px;
  762. width: 100%;
  763. transform: scaleY(0.00001);
  764. transform-origin:0 0;
  765. contain: strict;
  766. opacity:0;
  767. display:flex;
  768. position:relative;
  769. flex-shrink:0;
  770. flex-grow:0;
  771. margin-bottom:0;
  772. overflow:hidden;
  773. box-sizing:border-box;
  774. visibility: visible;
  775. content-visibility: visible;
  776. contain-intrinsic-size: auto 1px;
  777. pointer-events:none !important;
  778.  
  779. }
  780.  
  781. #item-scroller.style-scope.yt-live-chat-item-list-renderer[class] {
  782. overflow-anchor: initial !important; /* whenever ENABLE_OVERFLOW_ANCHOR or not */
  783. }
  784.  
  785. html item-anchor {
  786.  
  787. height: 1px;
  788. width: 1px;
  789. top: auto;
  790. left: auto;
  791. right: auto;
  792. bottom: auto;
  793. transform: translateY(-1px);
  794. position: absolute;
  795. z-index: -1;
  796.  
  797. }
  798.  
  799. }
  800.  
  801. @supports (color: var(--pre-rendering)) {
  802.  
  803. @keyframes dontRenderAnimation {
  804. 0% {
  805. background-position-x: 3px;
  806. }
  807. 100% {
  808. background-position-x: 4px;
  809. }
  810. }
  811.  
  812. .dont-render[class] {
  813. /* visibility: collapse !important; */
  814. /* visibility: collapse will make innerText become "" which conflicts with BetterStreamChat; see https://greasyfork.org/scripts/469878/discussions/197267 */
  815.  
  816. transform: scale(0.01) !important;
  817. transform: scale(0.00001) !important;
  818. transform: scale(0.0000001) !important;
  819. transform-origin: 0 0 !important;
  820. z-index: -1 !important;
  821. contain: strict !important;
  822. box-sizing: border-box !important;
  823.  
  824. height: 1px !important;
  825. height: 0.1px !important;
  826. height: 0.01px !important;
  827. height: 0.0001px !important;
  828. height: 0.000001px !important;
  829.  
  830. animation: dontRenderAnimation 1ms linear 80ms 1 normal forwards !important;
  831.  
  832. pointer-events: none !important;
  833. user-select: none !important;
  834.  
  835. }
  836.  
  837. #sk35z {
  838. display: block !important;
  839.  
  840. visibility: collapse !important;
  841.  
  842. transform: scale(0.01) !important;
  843. transform: scale(0.00001) !important;
  844. transform: scale(0.0000001) !important;
  845. transform-origin: 0 0 !important;
  846. z-index: -1 !important;
  847. contain: strict !important;
  848. box-sizing: border-box !important;
  849.  
  850. height: 1px !important;
  851. height: 0.1px !important;
  852. height: 0.01px !important;
  853. height: 0.0001px !important;
  854. height: 0.000001px !important;
  855.  
  856. position: absolute !important;
  857. top: -1000px !important;
  858. left: -1000px !important;
  859.  
  860. }
  861.  
  862. }
  863.  
  864. [rNgzQ] {
  865. opacity: 0 !important;
  866. pointer-events: none !important;
  867. }
  868.  
  869.  
  870. ${cssText10_show_more_blinker}
  871.  
  872. ${cssText11_entire_message_clickable}
  873.  
  874. ${cssText12_nowrap_tooltip}
  875.  
  876. ${cssText13_no_text_select_when_menu_visible}
  877.  
  878. `;
  879.  
  880. const win = typeof unsafeWindow !== 'undefined' ? unsafeWindow : (this instanceof Window ? this : window);
  881.  
  882. // Create a unique key for the script and check if it is already running
  883. const hkey_script = 'mchbwnoasqph';
  884. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  885. win[hkey_script] = true;
  886.  
  887. if (!!ATTEMPT_ANIMATED_TICKER_BACKGROUND) {
  888.  
  889. let te4 = setTimeout(() => { }); // dummy; skip timerId only;
  890. if (te4 < 3) {
  891. setTimeout(() => { });
  892. setTimeout(() => { });
  893. }
  894.  
  895. }
  896.  
  897. const firstKey = (obj) => {
  898. for (const key in obj) {
  899. if (obj.hasOwnProperty(key)) return key;
  900. }
  901. return null;
  902. }
  903.  
  904. const firstObjectKey = (obj) => {
  905. for (const key in obj) {
  906. if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key;
  907. }
  908. return null;
  909. }
  910.  
  911. function removeElementFromArray(arr, index) {
  912. if (index >= 0 && index < arr.length) {
  913. arr.splice(index, 1);
  914. }
  915. }
  916.  
  917. function getRandomInt(a, b) {
  918. // Ensure that 'a' and 'b' are integers
  919. a = Math.ceil(a);
  920. b = Math.floor(b);
  921.  
  922. // Generate a random integer in the range [a, b]
  923. return Math.floor(Math.random() * (b - a + 1)) + a;
  924. }
  925.  
  926. function deepCopy(obj, skipKeys) {
  927. skipKeys = skipKeys || [];
  928. if (!obj || typeof obj !== 'object') return obj;
  929. if (Array.isArray(obj)) {
  930. return obj.map(item => deepCopy(item, skipKeys));
  931. }
  932. const copy = {};
  933. for (let key in obj) {
  934. if (!skipKeys.includes(key)) {
  935. copy[key] = deepCopy(obj[key], skipKeys);
  936. }
  937. }
  938. return copy;
  939. }
  940.  
  941. class Mutex {
  942.  
  943. constructor() {
  944. this.p = Promise.resolve()
  945. }
  946.  
  947. /**
  948. * @param {(lockResolve: () => void)} f
  949. */
  950. lockWith(f) {
  951. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  952. }
  953.  
  954. }
  955.  
  956. const PromiseExternal = ((resolve_, reject_) => {
  957. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  958. return class PromiseExternal extends Promise {
  959. constructor(cb = h) {
  960. super(cb);
  961. if (cb === h) {
  962. /** @type {(value: any) => void} */
  963. this.resolve = resolve_;
  964. /** @type {(reason?: any) => void} */
  965. this.reject = reject_;
  966. }
  967. }
  968. };
  969. })();
  970.  
  971. /** @type {typeof PromiseExternal.prototype | null} */
  972. let relayPromise = null;
  973.  
  974.  
  975. /** @type {typeof PromiseExternal.prototype | null} */
  976. let onPlayStateChangePromise = null;
  977.  
  978.  
  979.  
  980. let playEventsStack = Promise.resolve();
  981.  
  982.  
  983. let playerProgressChangedArg1 = null;
  984. let playerProgressChangedArg2 = null;
  985. let playerProgressChangedArg3 = null;
  986.  
  987.  
  988. function dr(s) {
  989. // reserved for future use
  990. return s;
  991. // return window.deWeakJS ? window.deWeakJS(s) : s;
  992. }
  993.  
  994. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  995. const indr = o => insp(o).$ || o.$ || 0;
  996.  
  997. const getProto = (element) => {
  998. if (element) {
  999. const cnt = insp(element);
  1000. return cnt.constructor.prototype || null;
  1001. }
  1002. return null;
  1003. }
  1004.  
  1005. const assertor = (f) => f() || console.assert(false, f + "");
  1006.  
  1007. const fnIntegrity = (f, d) => {
  1008. if (!f || typeof f !== 'function') {
  1009. console.warn('f is not a function', f);
  1010. return;
  1011. }
  1012. let p = f + "", s = 0, j = -1, w = 0;
  1013. for (let i = 0, l = p.length; i < l; i++) {
  1014. const t = p[i];
  1015. if (((t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z'))) {
  1016. if (j < i - 1) w++;
  1017. j = i;
  1018. } else {
  1019. s++;
  1020. }
  1021. }
  1022. let itz = `${f.length}.${s}.${w}`;
  1023. if (!d) {
  1024. return itz;
  1025. } else if (itz !== d) {
  1026. console.warn('fnIntegrity=false', itz);
  1027. return false;
  1028. } else {
  1029. return true;
  1030. }
  1031. }
  1032.  
  1033.  
  1034. const px2cm = (px) => px * window.devicePixelRatio * 0.026458333;
  1035. const px2mm = (px) => px * window.devicePixelRatio * 0.26458333;
  1036.  
  1037.  
  1038. ; (ENABLE_FLAGS_MAINTAIN_STABLE_LIST || ENABLE_FLAGS_REUSE_COMPONENTS) && (() => {
  1039.  
  1040. const _config_ = () => {
  1041. try {
  1042. return ytcfg.data_;
  1043. } catch (e) { }
  1044. return null;
  1045. };
  1046.  
  1047. const flagsFn = (EXPERIMENT_FLAGS) => {
  1048.  
  1049. // console.log(700)
  1050.  
  1051. if (!EXPERIMENT_FLAGS) return;
  1052.  
  1053. if (ENABLE_FLAGS_MAINTAIN_STABLE_LIST) {
  1054. if (USE_MAINTAIN_STABLE_LIST_ONLY_WHEN_KS_FLAG_IS_SET ? EXPERIMENT_FLAGS.kevlar_should_maintain_stable_list === true : true) {
  1055. EXPERIMENT_FLAGS.kevlar_tuner_should_test_maintain_stable_list = true;
  1056. EXPERIMENT_FLAGS.kevlar_should_maintain_stable_list = true;
  1057. // console.log(701)
  1058. }
  1059. }
  1060.  
  1061. if (ENABLE_FLAGS_REUSE_COMPONENTS) {
  1062. EXPERIMENT_FLAGS.kevlar_tuner_should_test_reuse_components = true;
  1063. EXPERIMENT_FLAGS.kevlar_tuner_should_reuse_components = true;
  1064. // console.log(702);
  1065. }
  1066.  
  1067. };
  1068.  
  1069. const uf = (config_) => {
  1070. config_ = config_ || _config_();
  1071. if (config_) {
  1072. const { EXPERIMENT_FLAGS, EXPERIMENTS_FORCED_FLAGS } = config_;
  1073. if (EXPERIMENT_FLAGS) {
  1074. flagsFn(EXPERIMENT_FLAGS);
  1075. if (EXPERIMENTS_FORCED_FLAGS) flagsFn(EXPERIMENTS_FORCED_FLAGS);
  1076. }
  1077. }
  1078. }
  1079.  
  1080. window._ytConfigHacks.add((config_) => {
  1081. uf(config_);
  1082. });
  1083.  
  1084. uf();
  1085.  
  1086. })();
  1087.  
  1088. if (DISABLE_Translation_By_Google) {
  1089.  
  1090. let mo = new MutationObserver(() => {
  1091.  
  1092. if (!mo) return;
  1093. let h = document.head;
  1094. if (!h) return;
  1095. mo.disconnect();
  1096. mo.takeRecords();
  1097. mo = null;
  1098.  
  1099. let meta = document.createElement('meta');
  1100. meta.setAttribute('name', 'google');
  1101. meta.setAttribute('content', 'notranslate');
  1102. h.appendChild(meta);
  1103.  
  1104.  
  1105. });
  1106. mo.observe(document, { subtree: true, childList: true });
  1107. }
  1108.  
  1109.  
  1110. console.assert(MAX_ITEMS_FOR_TOTAL_DISPLAY > 0 && MAX_ITEMS_FOR_FULL_FLUSH > 0 && MAX_ITEMS_FOR_TOTAL_DISPLAY > MAX_ITEMS_FOR_FULL_FLUSH)
  1111.  
  1112. let ENABLE_DELAYED_CHAT_OCCURRENCE_CAPABLE = false;
  1113. const isContainSupport = CSS.supports('contain', 'layout paint style');
  1114. if (!isContainSupport) {
  1115. console.warn("Your browser does not support css property 'contain'.\nPlease upgrade to the latest version.".trim());
  1116. } else {
  1117. ENABLE_DELAYED_CHAT_OCCURRENCE_CAPABLE = true;
  1118. }
  1119.  
  1120. let ENABLE_OVERFLOW_ANCHOR_CAPABLE = false;
  1121. const isOverflowAnchorSupport = CSS.supports('overflow-anchor', 'auto');
  1122. if (!isOverflowAnchorSupport) {
  1123. console.warn("Your browser does not support css property 'overflow-anchor'.\nPlease upgrade to the latest version.".trim());
  1124. } else {
  1125. ENABLE_OVERFLOW_ANCHOR_CAPABLE = true;
  1126. }
  1127.  
  1128. const NOT_FIREFOX = !CSS.supports('-moz-appearance', 'none'); // 1. Firefox does not have the flicking issue; 2. Firefox's OVERFLOW_ANCHOR is less effective than Chromium's.
  1129.  
  1130. const ENABLE_OVERFLOW_ANCHOR = ENABLE_OVERFLOW_ANCHOR_PREFERRED && ENABLE_OVERFLOW_ANCHOR_CAPABLE && ENABLE_NO_SMOOTH_TRANSFORM;
  1131. const ENABLE_DELAYED_CHAT_OCCURRENCE = ENABLE_DELAYED_CHAT_OCCURRENCE_PREFERRED && ENABLE_DELAYED_CHAT_OCCURRENCE_CAPABLE && ENABLE_OVERFLOW_ANCHOR && ENABLE_NO_SMOOTH_TRANSFORM && NOT_FIREFOX;
  1132.  
  1133. let hasTimerModified = null;
  1134. const DO_CHECK_TICKER_BACKGROUND_OVERRIDED = !!ATTEMPT_ANIMATED_TICKER_BACKGROUND || ENABLE_RAF_HACK_TICKERS;
  1135.  
  1136. const fxOperator = (proto, propertyName) => {
  1137. let propertyDescriptorGetter = null;
  1138. try {
  1139. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  1140. } catch (e) { }
  1141. return typeof propertyDescriptorGetter === 'function' ? (e) => {
  1142. try {
  1143.  
  1144. return propertyDescriptorGetter.call(dr(e));
  1145. } catch (e) { }
  1146. return e[propertyName];
  1147. } : (e) => e[propertyName];
  1148. };
  1149.  
  1150. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  1151. // const nFirstElem = fxOperator(HTMLElement.prototype, 'firstElementChild');
  1152. const nPrevElem = fxOperator(HTMLElement.prototype, 'previousElementSibling');
  1153. const nNextElem = fxOperator(HTMLElement.prototype, 'nextElementSibling');
  1154. const nLastElem = fxOperator(HTMLElement.prototype, 'lastElementChild');
  1155.  
  1156. const groupCollapsed = (text1, text2) => {
  1157.  
  1158. console.groupCollapsed(`%c${text1}%c${text2}`,
  1159. "background-color: #010502; color: #6acafe; font-weight: 700; padding: 2px;",
  1160. "background-color: #010502; color: #6ad9fe; font-weight: 300; padding: 2px;"
  1161. );
  1162. }
  1163.  
  1164. // const microNow = () => performance.now() + (performance.timeOrigin || performance.timing.navigationStart);
  1165.  
  1166.  
  1167. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  1168. const onRegistryReady = (callback) => {
  1169. if (typeof customElements === 'undefined') {
  1170. if (!('__CE_registry' in document)) {
  1171. // https://github.com/webcomponents/polyfills/
  1172. Object.defineProperty(document, '__CE_registry', {
  1173. get() {
  1174. // return undefined
  1175. },
  1176. set(nv) {
  1177. if (typeof nv == 'object') {
  1178. delete this.__CE_registry;
  1179. this.__CE_registry = nv;
  1180. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  1181. }
  1182. return true;
  1183. },
  1184. enumerable: false,
  1185. configurable: true
  1186. })
  1187. }
  1188. let eventHandler = (evt) => {
  1189. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  1190. const f = callback;
  1191. callback = null;
  1192. eventHandler = null;
  1193. f();
  1194. };
  1195. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  1196. } else {
  1197. callback();
  1198. }
  1199. };
  1200.  
  1201. const promiseForCustomYtElementsReady = new Promise(onRegistryReady);
  1202.  
  1203. const renderReadyPn = typeof ResizeObserver !== 'undefined' ? (sizingTarget) => {
  1204.  
  1205. return new Promise(resolve => {
  1206.  
  1207. let ro = new ResizeObserver(entries => {
  1208. if (entries && entries.length >= 1) {
  1209. resolve();
  1210. ro.disconnect();
  1211. ro = null;
  1212. }
  1213. });
  1214. ro.observe(sizingTarget);
  1215.  
  1216.  
  1217.  
  1218. });
  1219.  
  1220. } : (sizingTarget) => {
  1221.  
  1222.  
  1223. return new Promise(resolve => {
  1224.  
  1225. let io = new IntersectionObserver(entries => {
  1226. if (entries && entries.length >= 1) {
  1227. resolve();
  1228. io.disconnect();
  1229. io = null;
  1230. }
  1231. });
  1232. io.observe(sizingTarget);
  1233.  
  1234.  
  1235.  
  1236. });
  1237.  
  1238. };
  1239.  
  1240. /* globals WeakRef:false */
  1241.  
  1242. /** @type {(o: Object | null) => WeakRef | null} */
  1243. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  1244.  
  1245. /** @type {(wr: Object | null) => Object | null} */
  1246. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1247.  
  1248. const getLCRDummy = () => {
  1249. // direct createElement or createComponent_ will make the emoji rendering crashed. reason TBC
  1250.  
  1251. return Promise.all([customElements.whenDefined('yt-live-chat-app'), customElements.whenDefined('yt-live-chat-renderer')]).then(async () => {
  1252.  
  1253. const tag = "yt-live-chat-renderer"
  1254. let dummy = document.querySelector(tag);
  1255. if (!dummy) {
  1256.  
  1257. let mo = null;
  1258.  
  1259. const ytLiveChatApp = document.querySelector('yt-live-chat-app') || document.createElement('yt-live-chat-app');
  1260.  
  1261. const lcaProto = getProto(ytLiveChatApp);
  1262.  
  1263. dummy = await new Promise(resolve => {
  1264.  
  1265. if (typeof lcaProto.createComponent_ === 'function' && !lcaProto.createComponent99_) {
  1266.  
  1267. lcaProto.createComponent99_ = lcaProto.createComponent_;
  1268. lcaProto.createComponent98_ = function (a, b, c) {
  1269. // (3) ['yt-live-chat-renderer', {…}, true]
  1270. const r = this.createComponent99_.apply(this, arguments);
  1271. if (a === 'yt-live-chat-renderer') {
  1272. resolve(r);
  1273. }
  1274. return r;
  1275. };
  1276. lcaProto.createComponent_ = lcaProto.createComponent98_;
  1277.  
  1278. } else {
  1279.  
  1280. mo = new MutationObserver(() => {
  1281. const t = document.querySelector(tag);
  1282. if (t) {
  1283. resolve(t);
  1284. }
  1285. });
  1286. mo.observe(document, { subtree: true, childList: true })
  1287. }
  1288.  
  1289. });
  1290.  
  1291. if (mo) {
  1292. mo.disconnect();
  1293. mo.takeRecords();
  1294. mo = null;
  1295. }
  1296.  
  1297. if (lcaProto.createComponent99_ && lcaProto.createComponent_ && lcaProto.createComponent98_ === lcaProto.createComponent_) {
  1298. lcaProto.createComponent_ = lcaProto.createComponent99_;
  1299. lcaProto.createComponent99_ = null;
  1300. lcaProto.createComponent98_ = null;
  1301. }
  1302.  
  1303. }
  1304. return dummy;
  1305.  
  1306. });
  1307. }
  1308.  
  1309. const { addCssManaged } = (() => {
  1310.  
  1311. const addFontPreRendering = () => {
  1312.  
  1313. groupCollapsed("YouTube Super Fast Chat", " | Fonts Pre-Rendering");
  1314.  
  1315. let efsContainer = document.createElement('elzm-fonts');
  1316. efsContainer.id = 'elzm-fonts-yk75g'
  1317.  
  1318. const arr = [];
  1319. let p = document.createElement('elzm-font');
  1320. arr.push(p);
  1321.  
  1322. if (ENABLE_FONT_PRE_RENDERING & 1) {
  1323. for (const size of [100, 200, 300, 400, 500, 600, 700, 800, 900]) {
  1324.  
  1325. p = document.createElement('elzm-font');
  1326. p.style.fontWeight = size;
  1327. arr.push(p);
  1328. }
  1329. }
  1330.  
  1331. if (ENABLE_FONT_PRE_RENDERING & 2) {
  1332. for (const size of [100, 200, 300, 400, 500, 600, 700, 800, 900]) {
  1333.  
  1334. p = document.createElement('elzm-font');
  1335. p.style.fontFamily = 'Roboto';
  1336. p.style.fontWeight = size;
  1337. arr.push(p);
  1338. }
  1339. }
  1340.  
  1341. if (ENABLE_FONT_PRE_RENDERING & 4) {
  1342. for (const size of [100, 200, 300, 400, 500, 600, 700, 800, 900]) {
  1343.  
  1344. p = document.createElement('elzm-font');
  1345. p.style.fontFamily = '"YouTube Noto",Roboto,Arial,Helvetica,sans-serif';
  1346. p.style.fontWeight = size;
  1347. arr.push(p);
  1348. }
  1349. }
  1350.  
  1351.  
  1352. if (ENABLE_FONT_PRE_RENDERING & 8) {
  1353. for (const size of [100, 200, 300, 400, 500, 600, 700, 800, 900]) {
  1354.  
  1355. p = document.createElement('elzm-font');
  1356. p.style.fontFamily = '"Noto",Roboto,Arial,Helvetica,sans-serif';
  1357. p.style.fontWeight = size;
  1358. arr.push(p);
  1359. }
  1360. }
  1361.  
  1362.  
  1363. if (ENABLE_FONT_PRE_RENDERING & 16) {
  1364. for (const size of [100, 200, 300, 400, 500, 600, 700, 800, 900]) {
  1365.  
  1366. p = document.createElement('elzm-font');
  1367. p.style.fontFamily = 'sans-serif';
  1368. p.style.fontWeight = size;
  1369. arr.push(p);
  1370. }
  1371. }
  1372.  
  1373. console.log('number of elzm-font elements', arr.length);
  1374.  
  1375. HTMLElement.prototype.append.apply(efsContainer, arr);
  1376.  
  1377. (document.body || document.documentElement).appendChild(efsContainer);
  1378.  
  1379.  
  1380. console.log('elzm-font elements have been added to the page for rendering.');
  1381.  
  1382. console.groupEnd();
  1383.  
  1384. }
  1385.  
  1386. let isCssAdded = false;
  1387.  
  1388. function addCssElement() {
  1389. let s = document.createElement('style');
  1390. s.id = 'ewRvC';
  1391. return s;
  1392. }
  1393.  
  1394. const addCssManaged = () => {
  1395. if (!isCssAdded && document.documentElement && document.head) {
  1396. isCssAdded = true;
  1397. document.head.appendChild(dr(addCssElement())).textContent = addCss();
  1398. if (ENABLE_FONT_PRE_RENDERING) {
  1399. Promise.resolve().then(addFontPreRendering)
  1400. }
  1401. }
  1402. }
  1403.  
  1404. return { addCssManaged };
  1405. })();
  1406.  
  1407.  
  1408. const { setupStyle } = (() => {
  1409.  
  1410. const sp7 = Symbol();
  1411.  
  1412. const proxyHelperFn = (dummy) => ({
  1413.  
  1414. get(target, prop) {
  1415. return (prop in dummy) ? dummy[prop] : prop === sp7 ? target : target[prop];
  1416. },
  1417. set(target, prop, value) {
  1418. if (!(prop in dummy)) {
  1419. target[prop] = value;
  1420. }
  1421. return true;
  1422. },
  1423. has(target, prop) {
  1424. return (prop in target);
  1425. },
  1426. deleteProperty(target, prop) {
  1427. return true;
  1428. },
  1429. ownKeys(target) {
  1430. return Object.keys(target);
  1431. },
  1432. defineProperty(target, key, descriptor) {
  1433. return Object.defineProperty(target, key, descriptor);
  1434. },
  1435. getOwnPropertyDescriptor(target, key) {
  1436. return Object.getOwnPropertyDescriptor(target, key);
  1437. },
  1438.  
  1439. });
  1440.  
  1441. const setupStyle = (m1, m2) => {
  1442. if (!ENABLE_NO_SMOOTH_TRANSFORM) return;
  1443.  
  1444. const dummy1v = {
  1445. transform: '',
  1446. height: '',
  1447. minHeight: '',
  1448. paddingBottom: '',
  1449. paddingTop: ''
  1450. };
  1451.  
  1452. const dummyStyleFn = (k) => (function () { const style = this[sp7]; return style[k](...arguments); });
  1453. for (const k of ['toString', 'getPropertyPriority', 'getPropertyValue', 'item', 'removeProperty', 'setProperty']) {
  1454. dummy1v[k] = dummyStyleFn(k);
  1455. }
  1456.  
  1457. const dummy1p = proxyHelperFn(dummy1v);
  1458. const sp1v = new Proxy(m1.style, dummy1p);
  1459. const sp2v = new Proxy(m2.style, dummy1p);
  1460. Object.defineProperty(m1, 'style', { get() { return sp1v }, set() { }, enumerable: true, configurable: true });
  1461. Object.defineProperty(m2, 'style', { get() { return sp2v }, set() { }, enumerable: true, configurable: true });
  1462. m1.removeAttribute("style");
  1463. m2.removeAttribute("style");
  1464.  
  1465. }
  1466.  
  1467. return { setupStyle };
  1468.  
  1469. })();
  1470.  
  1471.  
  1472.  
  1473. function setThumbnails(config) {
  1474.  
  1475. const { baseObject, thumbnails, flag0, imageLinks } = config;
  1476.  
  1477. if (flag0 || (ENABLE_PRELOAD_THUMBNAIL && imageLinks)) {
  1478.  
  1479.  
  1480. if (thumbnails && thumbnails.length > 0) {
  1481. if (flag0 > 0 && thumbnails.length > 1) {
  1482. let pSize = 0;
  1483. let newThumbnails = [];
  1484. for (const thumbnail of thumbnails) {
  1485. if (!thumbnail || !thumbnail.url) continue;
  1486. const squarePhoto = thumbnail.width === thumbnail.height && typeof thumbnail.width === 'number';
  1487. const condSize = pSize <= 0 || (flag0 === 1 ? pSize > thumbnail.width : pSize < thumbnail.width);
  1488. const leastSizeFulfilled = squarePhoto ? thumbnail.width >= LEAST_IMAGE_SIZE : true;
  1489. if ((!squarePhoto || condSize) && leastSizeFulfilled) {
  1490. newThumbnails.push(thumbnail);
  1491. if (imageLinks) imageLinks.add(thumbnail.url);
  1492. }
  1493. if (squarePhoto && condSize && leastSizeFulfilled) {
  1494. pSize = thumbnail.width;
  1495. }
  1496. }
  1497. if (thumbnails.length !== newThumbnails.length && thumbnails === baseObject.thumbnails && newThumbnails.length > 0) {
  1498. baseObject.thumbnails = newThumbnails;
  1499. } else {
  1500. newThumbnails.length = 0;
  1501. }
  1502. newThumbnails = null;
  1503. } else {
  1504. for (const thumbnail of thumbnails) {
  1505. if (thumbnail && thumbnail.url) {
  1506. if (imageLinks) imageLinks.add(thumbnail.url);
  1507. }
  1508. }
  1509. }
  1510. }
  1511.  
  1512. }
  1513. }
  1514.  
  1515. function fixLiveChatItem(item, imageLinks) {
  1516. const liveChatTextMessageRenderer = (item || 0).liveChatTextMessageRenderer || 0;
  1517. if (liveChatTextMessageRenderer) {
  1518. const messageRuns = (liveChatTextMessageRenderer.message || 0).runs || 0;
  1519. if (messageRuns && messageRuns.length > 0) {
  1520. for (const run of messageRuns) {
  1521. const emojiImage = (((run || 0).emoji || 0).image || 0);
  1522. setThumbnails({
  1523. baseObject: emojiImage,
  1524. thumbnails: emojiImage.thumbnails,
  1525. flag0: EMOJI_IMAGE_SINGLE_THUMBNAIL,
  1526. imageLinks
  1527. });
  1528. }
  1529. }
  1530. const authorPhoto = liveChatTextMessageRenderer.authorPhoto || 0;
  1531. setThumbnails({
  1532. baseObject: authorPhoto,
  1533. thumbnails: authorPhoto.thumbnails,
  1534. flag0: AUTHOR_PHOTO_SINGLE_THUMBNAIL,
  1535. imageLinks
  1536. });
  1537. }
  1538. }
  1539.  
  1540.  
  1541.  
  1542. let kptPF = null;
  1543. const emojiPrefetched = new Set();
  1544. const authorPhotoPrefetched = new Set();
  1545.  
  1546. function linker(link, rel, href, _as) {
  1547. return new Promise(resolve => {
  1548. if (!link) link = document.createElement('link');
  1549. link.rel = rel;
  1550. if (_as) link.setAttribute('as', _as);
  1551. link.onload = function () {
  1552. resolve({
  1553. link: this,
  1554. success: true
  1555. })
  1556. this.remove();
  1557. };
  1558. link.onerror = function () {
  1559. resolve({
  1560. link: this,
  1561. success: false
  1562. });
  1563. this.remove();
  1564. };
  1565. link.href = href;
  1566. document.head.appendChild(link);
  1567. link = null;
  1568. });
  1569. }
  1570.  
  1571.  
  1572.  
  1573. const cleanContext = async (win) => {
  1574. const waitFn = requestAnimationFrame; // shall have been binded to window
  1575. try {
  1576. let mx = 16; // MAX TRIAL
  1577. const frameId = 'vanillajs-iframe-v1';
  1578. /** @type {HTMLIFrameElement | null} */
  1579. let frame = document.getElementById(frameId);
  1580. let removeIframeFn = null;
  1581. if (!frame) {
  1582. frame = document.createElement('iframe');
  1583. frame.id = frameId;
  1584. const blobURL = typeof webkitCancelAnimationFrame === 'function' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  1585. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  1586. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  1587. n.appendChild(frame);
  1588. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  1589. const root = document.documentElement;
  1590. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  1591. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  1592.  
  1593. removeIframeFn = (setTimeout) => {
  1594. const removeIframeOnDocumentReady = (e) => {
  1595. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  1596. e = n;
  1597. n = win = removeIframeFn = 0;
  1598. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  1599. }
  1600. if (!setTimeout || document.readyState !== 'loading') {
  1601. removeIframeOnDocumentReady();
  1602. } else {
  1603. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  1604. }
  1605. }
  1606. }
  1607. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  1608. const fc = frame.contentWindow;
  1609. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  1610. try {
  1611. const { requestAnimationFrame, setTimeout, cancelAnimationFrame, setInterval, clearInterval, getComputedStyle } = fc;
  1612. const res = { requestAnimationFrame, setTimeout, cancelAnimationFrame, setInterval, clearInterval, getComputedStyle };
  1613. for (let k in res) res[k] = res[k].bind(win); // necessary
  1614. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  1615.  
  1616. /** @type {HTMLElement} */
  1617. const HTMLElementProto = fc.HTMLElement.prototype;
  1618. /** @type {EventTarget} */
  1619. const EventTargetProto = fc.EventTarget.prototype;
  1620. // jsonParseFix = {
  1621. // _JSON: fc.JSON, _parse: fc.JSON.parse
  1622. // }
  1623. return {
  1624. ...res,
  1625. animate: HTMLElementProto.animate,
  1626. addEventListener: EventTargetProto.addEventListener,
  1627. removeEventListener: EventTargetProto.removeEventListener
  1628. };
  1629. } catch (e) {
  1630. if (removeIframeFn) removeIframeFn();
  1631. return null;
  1632. }
  1633. } catch (e) {
  1634. console.warn(e);
  1635. return null;
  1636. }
  1637. };
  1638.  
  1639. cleanContext(win).then(__CONTEXT__ => {
  1640. if (!__CONTEXT__) return null;
  1641.  
  1642. const { requestAnimationFrame, setTimeout, cancelAnimationFrame, setInterval, clearInterval, animate, getComputedStyle, addEventListener, removeEventListener } = __CONTEXT__;
  1643.  
  1644.  
  1645. let foregroundPromise = null;
  1646. const foregroundPromiseFn = () => (foregroundPromise = (foregroundPromise || new Promise(resolve => {
  1647. requestAnimationFrame(() => {
  1648. foregroundPromise = null;
  1649. resolve();
  1650. });
  1651. })));
  1652.  
  1653. let playerState = null;
  1654. let _playerState = null;
  1655. let lastPlayerProgress = null;
  1656. let relayCount = 0;
  1657. let playerEventsByIframeRelay = false;
  1658. let isPlayProgressTriggered = false;
  1659. let waitForInitialDataCompletion = 0;
  1660.  
  1661.  
  1662.  
  1663. let aeConstructor = null;
  1664.  
  1665. // << __openedChanged82 >>
  1666. let currentMenuPivotWR = null;
  1667.  
  1668. // << if DO_PARTICIPANT_LIST_HACKS >>
  1669. const beforeParticipantsMap = new WeakMap();
  1670. // << end >>
  1671.  
  1672.  
  1673.  
  1674. // << if onRegistryReadyForDOMOperations >>
  1675.  
  1676. let dt0 = Date.now() - 2000;
  1677. const dateNow = () => Date.now() - dt0;
  1678. // let lastScroll = 0;
  1679. // let lastLShow = 0;
  1680. let lastWheel = 0;
  1681. let lastMouseDown = 0;
  1682. let lastMouseUp = 0;
  1683. let currentMouseDown = false;
  1684. let lastTouchDown = 0;
  1685. let lastTouchUp = 0;
  1686. let currentTouchDown = false;
  1687. let lastUserInteraction = 0;
  1688.  
  1689. let scrollChatFn = null;
  1690.  
  1691. let skipDontRender = true; // true first; false by flushActiveItems_
  1692. let allowDontRender = null;
  1693.  
  1694. // ---- #items mutation ----
  1695. let sk35zResolveFn = null;
  1696. let firstList = true;
  1697.  
  1698. // << end >>
  1699.  
  1700. class RAFHub {
  1701. constructor() {
  1702. /** @type {number} */
  1703. this.startAt = 8170;
  1704. /** @type {number} */
  1705. this.counter = 0;
  1706. /** @type {number} */
  1707. this.rid = 0;
  1708. /** @type {Map<number, FrameRequestCallback>} */
  1709. this.funcs = new Map();
  1710. const funcs = this.funcs;
  1711. /** @type {FrameRequestCallback} */
  1712. this.bCallback = this.mCallback.bind(this);
  1713. this.pClear = () => funcs.clear();
  1714. this.keepRAF = false;
  1715. }
  1716. /** @param {DOMHighResTimeStamp} highResTime */
  1717. mCallback(highResTime) {
  1718. this.rid = 0;
  1719. Promise.resolve().then(this.pClear);
  1720. this.funcs.forEach(func => Promise.resolve(highResTime).then(func).catch(console.warn));
  1721. }
  1722. /** @param {FrameRequestCallback} f */
  1723. request(f) {
  1724. if (this.counter > 1e9) this.counter = 9;
  1725. let cid = this.startAt + (++this.counter);
  1726. this.funcs.set(cid, f);
  1727. if (this.rid === 0) this.rid = requestAnimationFrame(this.bCallback);
  1728. return cid;
  1729. }
  1730. /** @param {number} cid */
  1731. cancel(cid) {
  1732. cid = +cid;
  1733. if (cid > 0) {
  1734. if (cid <= this.startAt) {
  1735. return cancelAnimationFrame(cid);
  1736. }
  1737. if (this.rid > 0) {
  1738. this.funcs.delete(cid);
  1739. if (this.funcs.size === 0 && !this.keepRAF) {
  1740. cancelAnimationFrame(this.rid);
  1741. this.rid = 0;
  1742. }
  1743. }
  1744. }
  1745. }
  1746. }
  1747.  
  1748. function basePrefetching() {
  1749.  
  1750. new Promise(resolve => {
  1751.  
  1752. if (document.readyState !== 'loading') {
  1753. resolve();
  1754. } else {
  1755. win.addEventListener("DOMContentLoaded", resolve, false);
  1756. }
  1757.  
  1758. }).then(() => {
  1759. const hostL1 = [
  1760. 'https://www.youtube.com', 'https://googlevideo.com',
  1761. 'https://googleapis.com', 'https://accounts.youtube.com',
  1762. 'https://www.gstatic.com', 'https://ggpht.com',
  1763. 'https://yt3.ggpht.com', 'https://yt4.ggpht.com'
  1764. ];
  1765.  
  1766. const hostL2 = [
  1767. 'https://youtube.com',
  1768. 'https://fonts.googleapis.com', 'https://fonts.gstatic.com'
  1769. ];
  1770.  
  1771. let link = null;
  1772.  
  1773. function kn() {
  1774.  
  1775. link = document.createElement('link');
  1776. if (link.relList && link.relList.supports) {
  1777. kptPF = (link.relList.supports('dns-prefetch') ? 1 : 0) + (link.relList.supports('preconnect') ? 2 : 0) + (link.relList.supports('prefetch') ? 4 : 0) + (link.relList.supports('subresource') ? 8 : 0) + (link.relList.supports('preload') ? 16 : 0)
  1778. } else {
  1779. kptPF = 0;
  1780. }
  1781.  
  1782. groupCollapsed("YouTube Super Fast Chat", " | PREFETCH SUPPORTS");
  1783. if (ENABLE_BASE_PREFETCHING) console.log('dns-prefetch', (kptPF & 1) ? 'OK' : 'NG');
  1784. if (ENABLE_BASE_PREFETCHING) console.log('preconnect', (kptPF & 2) ? 'OK' : 'NG');
  1785. if (ENABLE_PRELOAD_THUMBNAIL) console.log('prefetch', (kptPF & 4) ? 'OK' : 'NG');
  1786. // console.log('subresource', (kptPF & 8) ? 'OK' : 'NG');
  1787. if (ENABLE_PRELOAD_THUMBNAIL) console.log('preload', (kptPF & 16) ? 'OK' : 'NG');
  1788. console.groupEnd();
  1789.  
  1790. }
  1791.  
  1792. for (const h of hostL1) {
  1793.  
  1794. if (kptPF === null) kn();
  1795. if (ENABLE_BASE_PREFETCHING) {
  1796. // if (kptPF & 1) {
  1797. // linker(link, 'dns-prefetch', h);
  1798. // link = null;
  1799. // }
  1800. if (kptPF & 2) {
  1801. linker(link, 'preconnect', h);
  1802. link = null;
  1803. }
  1804. }
  1805. }
  1806.  
  1807. for (const h of hostL2) {
  1808. if (kptPF === null) kn();
  1809. if (ENABLE_BASE_PREFETCHING) {
  1810. if (kptPF & 1) {
  1811. linker(link, 'dns-prefetch', h);
  1812. link = null;
  1813. }
  1814. }
  1815. }
  1816.  
  1817. })
  1818.  
  1819.  
  1820. }
  1821.  
  1822. if (DO_LINK_PREFETCH) basePrefetching();
  1823.  
  1824. const { notifyPath7081 } = (() => {
  1825. // DO_PARTICIPANT_LIST_HACKS
  1826.  
  1827. const mutexParticipants = new Mutex();
  1828.  
  1829. let uvid = 0;
  1830. let r95dm = 0;
  1831. let c95dm = -1;
  1832.  
  1833. const foundMap = (base, content) => {
  1834. /*
  1835. let lastSearch = 0;
  1836. let founds = base.map(baseEntry => {
  1837. let search = content.indexOf(baseEntry, lastSearch);
  1838. if (search < 0) return false;
  1839. lastSearch = search + 1;
  1840. return true;
  1841. });
  1842. return founds;
  1843. */
  1844. const contentSet = new Set(content);
  1845. return base.map(baseEntry => contentSet.has(baseEntry));
  1846.  
  1847. }
  1848.  
  1849.  
  1850.  
  1851. const spliceIndicesFunc = (beforeParticipants, participants, idsBefore, idsAfter) => {
  1852.  
  1853. const handler1 = {
  1854. get(target, prop, receiver) {
  1855. if (prop === 'object') {
  1856. return participants; // avoid memory leakage
  1857. }
  1858. if (prop === 'type') {
  1859. return 'splice';
  1860. }
  1861. return target[prop];
  1862. }
  1863. };
  1864. const releaser = () => {
  1865. participants = null;
  1866. }
  1867.  
  1868. let foundsForAfter = foundMap(idsAfter, idsBefore);
  1869. let foundsForBefore = foundMap(idsBefore, idsAfter);
  1870.  
  1871. let indexSplices = [];
  1872. let contentUpdates = [];
  1873. for (let i = 0, j = 0; i < foundsForBefore.length || j < foundsForAfter.length;) {
  1874. if (beforeParticipants[i] === participants[j]) {
  1875. i++; j++;
  1876. } else if (idsBefore[i] === idsAfter[j]) {
  1877. // content changed
  1878. contentUpdates.push({ indexI: i, indexJ: j })
  1879. i++; j++;
  1880. } else {
  1881. let addedCount = 0;
  1882. for (let q = j; q < foundsForAfter.length; q++) {
  1883. if (foundsForAfter[q] === false) addedCount++;
  1884. else break;
  1885. }
  1886. let removedCount = 0;
  1887. for (let q = i; q < foundsForBefore.length; q++) {
  1888. if (foundsForBefore[q] === false) removedCount++;
  1889. else break;
  1890. }
  1891. if (!addedCount && !removedCount) {
  1892. throw 'ERROR(0xFF32): spliceIndicesFunc';
  1893. }
  1894. indexSplices.push(new Proxy({
  1895. index: j,
  1896. addedCount: addedCount,
  1897. removed: removedCount >= 1 ? beforeParticipants.slice(i, i + removedCount) : []
  1898. }, handler1));
  1899. i += removedCount;
  1900. j += addedCount;
  1901. }
  1902. }
  1903. foundsForBefore = null;
  1904. foundsForAfter = null;
  1905. idsBefore = null;
  1906. idsAfter = null;
  1907. beforeParticipants = null;
  1908. return { indexSplices, contentUpdates, releaser };
  1909.  
  1910. }
  1911.  
  1912. /*
  1913.  
  1914. customElements.get("yt-live-chat-participant-renderer").prototype.notifyPath=function(){ console.log(123); console.log(new Error().stack)}
  1915.  
  1916. VM63631:1 Error
  1917. at customElements.get.notifyPath (<anonymous>:1:122)
  1918. at e.forwardRendererStamperChanges_ (live_chat_polymer.js:4453:35)
  1919. at e.rendererStamperApplyChangeRecord_ (live_chat_polymer.js:4451:12)
  1920. at e.rendererStamperObserver_ (live_chat_polymer.js:4448:149)
  1921. at Object.pu [as fn] (live_chat_polymer.js:1692:118)
  1922. at ju (live_chat_polymer.js:1674:217)
  1923. at a._propertiesChanged (live_chat_polymer.js:1726:122)
  1924. at b._flushProperties (live_chat_polymer.js:1597:200)
  1925. at a._invalidateProperties (live_chat_polymer.js:1718:69)
  1926. at a.notifyPath (live_chat_polymer.js:1741:182)
  1927.  
  1928. */
  1929.  
  1930. function convertToIds(participants) {
  1931. return participants.map(participant => {
  1932. if (!participant || typeof participant !== 'object') {
  1933. console.warn('Error(0xFA41): convertToIds', participant);
  1934. return participant; // just in case
  1935. }
  1936. let keys = Object.keys(participant);
  1937. // liveChatTextMessageRenderer
  1938. // liveChatParticipantRenderer - livestream channel owner [no authorExternalChannelId]
  1939. // liveChatPaidMessageRenderer
  1940. /*
  1941.  
  1942. 'yt-live-chat-participant-renderer' utilizes the following:
  1943. authorName.simpleText: string
  1944. authorPhoto.thumbnails: Object{url:string, width:int, height:int} []
  1945. authorBadges[].liveChatAuthorBadgeRenderer.icon.iconType: string
  1946. authorBadges[].liveChatAuthorBadgeRenderer.tooltip: string
  1947. authorBadges[].liveChatAuthorBadgeRenderer.accessibility.accessibilityData: Object{label:string}
  1948.  
  1949. */
  1950. if (keys.length !== 1) {
  1951. console.warn('Error(0xFA42): convertToIds', participant);
  1952. return participant; // just in case
  1953. }
  1954. let key = keys[0];
  1955. let renderer = (participant[key] || 0);
  1956. let authorName = (renderer.authorName || 0);
  1957. let text = `${authorName.simpleText || authorName.text}`
  1958. let res = participant; // fallback if it is not a vaild entry
  1959. if (typeof text !== 'string') {
  1960. console.warn('Error(0xFA53): convertToIds', participant);
  1961. } else {
  1962. text = `${renderer.authorExternalChannelId || 'null'}|${text || ''}`;
  1963. if (text.length > 1) res = text;
  1964. }
  1965. return res;
  1966. // return renderer?`${renderer.id}|${renderer.authorExternalChannelId}`: '';
  1967. // note: renderer.id will be changed if the user typed something to trigger the update of the participants' record.
  1968. });
  1969. }
  1970.  
  1971. const checkChangeToParticipantRendererContent = CHECK_CHANGE_TO_PARTICIPANT_RENDERER_CONTENT ? (p1, p2) => {
  1972. // just update when content is changed.
  1973. if (p1.authorName !== p2.authorName) return true;
  1974. if (p1.authorPhoto !== p2.authorPhoto) return true;
  1975. if (p1.authorBadges !== p2.authorBadges) return true;
  1976. return false;
  1977. } : (p1, p2) => {
  1978. // keep integrity all the time.
  1979. return p1 !== p2; // always true
  1980. }
  1981.  
  1982. function notifyPath7081(path) { // cnt "yt-live-chat-participant-list-renderer"
  1983.  
  1984. if (PARTICIPANT_UPDATE_ONLY_ONLY_IF_MODIFICATION_DETECTED) {
  1985. if (path !== "participantsManager.participants") {
  1986. return this.__notifyPath5036__.apply(this, arguments);
  1987. }
  1988. if (c95dm === r95dm) return;
  1989. } else {
  1990. const stack = new Error().stack;
  1991. if (path !== "participantsManager.participants" || stack.indexOf('.onParticipantsChanged') < 0) {
  1992. return this.__notifyPath5036__.apply(this, arguments);
  1993. }
  1994. }
  1995.  
  1996. if (uvid > 1e8) uvid = uvid % 100;
  1997. let tid = ++uvid;
  1998.  
  1999. const cnt = this; // "yt-live-chat-participant-list-renderer"
  2000. mutexParticipants.lockWith(lockResolve => {
  2001.  
  2002. const participants00 = cnt.participantsManager.participants;
  2003.  
  2004. if (tid !== uvid || typeof (participants00 || 0).splice !== 'function') {
  2005. lockResolve();
  2006. return;
  2007. }
  2008.  
  2009. let doUpdate = false;
  2010.  
  2011. if (PARTICIPANT_UPDATE_ONLY_ONLY_IF_MODIFICATION_DETECTED) {
  2012.  
  2013. if (!participants00.r94dm) {
  2014. participants00.r94dm = 1;
  2015. if (++r95dm > 1e9) r95dm = 9;
  2016. participants00.push = function () {
  2017. if (++r95dm > 1e9) r95dm = 9;
  2018. return Array.prototype.push.apply(this, arguments);
  2019. }
  2020. participants00.pop = function () {
  2021. if (++r95dm > 1e9) r95dm = 9;
  2022. return Array.prototype.pop.apply(this, arguments);
  2023. }
  2024. participants00.shift = function () {
  2025. if (++r95dm > 1e9) r95dm = 9;
  2026. return Array.prototype.shift.apply(this, arguments);
  2027. }
  2028. participants00.unshift = function () {
  2029. if (++r95dm > 1e9) r95dm = 9;
  2030. return Array.prototype.unshift.apply(this, arguments);
  2031. }
  2032. participants00.splice = function () {
  2033. if (++r95dm > 1e9) r95dm = 9;
  2034. return Array.prototype.splice.apply(this, arguments);
  2035. }
  2036. participants00.sort = function () {
  2037. if (++r95dm > 1e9) r95dm = 9;
  2038. return Array.prototype.sort.apply(this, arguments);
  2039. }
  2040. participants00.reverse = function () {
  2041. if (++r95dm > 1e9) r95dm = 9;
  2042. return Array.prototype.reverse.apply(this, arguments);
  2043. }
  2044. }
  2045.  
  2046. if (c95dm !== r95dm) {
  2047. c95dm = r95dm;
  2048. doUpdate = true;
  2049. }
  2050.  
  2051. } else {
  2052. doUpdate = true;
  2053. }
  2054.  
  2055. if (!doUpdate) {
  2056. lockResolve();
  2057. return;
  2058. }
  2059.  
  2060. const participants = participants00.slice(0);
  2061. const beforeParticipants = beforeParticipantsMap.get(cnt) || [];
  2062. beforeParticipantsMap.set(cnt, participants);
  2063.  
  2064. const resPromise = (async () => {
  2065.  
  2066. if (beforeParticipants.length === 0) {
  2067. // not error
  2068. return 0;
  2069. }
  2070.  
  2071. let countOfElements = cnt.__getAllParticipantsDOMRenderedLength__()
  2072.  
  2073. // console.log(participants.length, doms.length) // different if no requestAnimationFrame
  2074. if (beforeParticipants.length !== countOfElements) {
  2075. // there is somewrong for the cache. - sometimes happen
  2076. return 0;
  2077. }
  2078.  
  2079. const idsBefore = convertToIds(beforeParticipants);
  2080. const idsAfter = convertToIds(participants);
  2081.  
  2082. let { indexSplices, contentUpdates, releaser } = spliceIndicesFunc(beforeParticipants, participants, idsBefore, idsAfter);
  2083.  
  2084. let res = 1; // default 1 for no update
  2085.  
  2086. if (indexSplices.length >= 1) {
  2087.  
  2088.  
  2089. // let p2 = participants.slice(indexSplices[0].index, indexSplices[0].index+indexSplices[0].addedCount);
  2090. // let p1 = indexSplices[0].removed;
  2091. // console.log(indexSplices.length, indexSplices ,p1,p2, convertToIds(p1),convertToIds(p2))
  2092.  
  2093. /* folllow
  2094. a.notifyPath(c + ".splices", d);
  2095. a.notifyPath(c + ".length", b.length);
  2096. */
  2097. // stampDomArraySplices_
  2098.  
  2099.  
  2100. await new Promise(resolve => {
  2101. cnt.resolveForDOMRendering781 = resolve;
  2102.  
  2103. cnt.__notifyPath5036__("participantsManager.participants.splices", {
  2104. indexSplices
  2105. });
  2106. indexSplices = null;
  2107. releaser();
  2108. releaser = null;
  2109. cnt.__notifyPath5036__("participantsManager.participants.length",
  2110. participants.length
  2111. );
  2112.  
  2113. });
  2114.  
  2115. await Promise.resolve(0); // play safe for the change of 'length'
  2116. countOfElements = cnt.__getAllParticipantsDOMRenderedLength__();
  2117.  
  2118. let wrongSize = participants.length !== countOfElements
  2119. if (wrongSize) {
  2120. console.warn("ERROR(0xE2C3): notifyPath7081", beforeParticipants.length, participants.length, doms.length)
  2121. return 0;
  2122. }
  2123.  
  2124. res = 2 | 4;
  2125.  
  2126. } else {
  2127.  
  2128. indexSplices = null;
  2129. releaser();
  2130. releaser = null;
  2131.  
  2132. if (participants.length !== countOfElements) {
  2133. // other unhandled cases
  2134. return 0;
  2135. }
  2136.  
  2137. }
  2138.  
  2139. // participants.length === countOfElements before contentUpdates
  2140. if (contentUpdates.length >= 1) {
  2141. for (const contentUpdate of contentUpdates) {
  2142. let isChanged = checkChangeToParticipantRendererContent(beforeParticipants[contentUpdate.indexI], participants[contentUpdate.indexJ]);
  2143. if (isChanged) {
  2144. cnt.__notifyPath5036__(`participantsManager.participants[${contentUpdate.indexJ}]`);
  2145. res |= 4 | 8;
  2146. }
  2147. }
  2148. }
  2149. contentUpdates = null;
  2150.  
  2151. return res;
  2152.  
  2153.  
  2154. })();
  2155.  
  2156.  
  2157. resPromise.then(resValue => {
  2158.  
  2159. const isLogRequired = SHOW_PARTICIPANT_CHANGES_IN_CONSOLE && ((resValue === 0) || ((resValue & 4) === 4));
  2160. isLogRequired && groupCollapsed("Participant List Change", `tid = ${tid}; res = ${resValue}`);
  2161. if (resValue === 0) {
  2162. new Promise(resolve => {
  2163. cnt.resolveForDOMRendering781 = resolve;
  2164. isLogRequired && console.log("Full Refresh begins");
  2165. cnt.__notifyPath5036__("participantsManager.participants"); // full refresh
  2166. }).then(() => {
  2167. isLogRequired && console.log("Full Refresh ends");
  2168. console.groupEnd();
  2169. }).then(lockResolve);
  2170. return;
  2171. }
  2172.  
  2173. const delayLockResolve = (resValue & 4) === 4;
  2174.  
  2175. if (delayLockResolve) {
  2176. isLogRequired && console.log(`Number of participants (before): ${beforeParticipants.length}`);
  2177. isLogRequired && console.log(`Number of participants (after): ${participants.length}`);
  2178. isLogRequired && console.log(`Total number of rendered participants: ${cnt.__getAllParticipantsDOMRenderedLength__()}`);
  2179. isLogRequired && console.log(`Participant Renderer Content Updated: ${(resValue & 8) === 8}`);
  2180. isLogRequired && console.groupEnd();
  2181. // requestAnimationFrame is required to avoid particiant update during DOM changing (stampDomArraySplices_)
  2182. // mutex lock with requestAnimationFrame can also disable participants update in background
  2183. requestAnimationFrame(lockResolve);
  2184. } else {
  2185. lockResolve();
  2186. }
  2187.  
  2188. });
  2189.  
  2190. });
  2191.  
  2192. }
  2193.  
  2194. return { notifyPath7081 };
  2195.  
  2196. })();
  2197.  
  2198. const whenDefinedMultiple = async (tags) => {
  2199.  
  2200. const sTags = [...new Set(tags)];
  2201. const len = sTags.length;
  2202.  
  2203. const pTags = new Array(len);
  2204. for (let i = 0; i < len; i++) {
  2205. pTags[i] = customElements.whenDefined(sTags[i]);
  2206. }
  2207.  
  2208. await Promise.all(pTags);
  2209. pTags.length = 0;
  2210.  
  2211. return sTags;
  2212.  
  2213. }
  2214.  
  2215. const onRegistryReadyForDataManipulation = () => {
  2216.  
  2217. function dummy5035(a, b, c) { }
  2218. function dummy411(a, b, c) { }
  2219.  
  2220.  
  2221.  
  2222. customElements.whenDefined("yt-live-chat-participant-list-renderer").then(() => {
  2223.  
  2224. if (!DO_PARTICIPANT_LIST_HACKS) return;
  2225.  
  2226. const tag = "yt-live-chat-participant-list-renderer";
  2227. const cProto = getProto(document.createElement(tag));
  2228. if (!cProto || typeof cProto.attached !== 'function') {
  2229. // for _registered, proto.attached shall exist when the element is defined.
  2230. // for controller extraction, attached shall exist when instance creates.
  2231. console.warn(`proto.attached for ${tag} is unavailable.`);
  2232. return;
  2233. }
  2234.  
  2235.  
  2236. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-participant-list-renderer hacks");
  2237.  
  2238. const fgsArr = ['kevlar_tuner_should_test_maintain_stable_list', 'kevlar_should_maintain_stable_list', 'kevlar_tuner_should_test_reuse_components', 'kevlar_tuner_should_reuse_components'];
  2239. const fgs = {};
  2240. for (const key of fgsArr) fgs[key] = undefined;
  2241.  
  2242. try {
  2243. const EXPERIMENT_FLAGS = ytcfg.data_.EXPERIMENT_FLAGS;
  2244. for (const key of fgsArr) fgs[key] = EXPERIMENT_FLAGS[key];
  2245. } catch (e) { }
  2246. console.log(`EXPERIMENT_FLAGS: ${JSON.stringify(fgs, null, 2)}`);
  2247.  
  2248. const canDoReplacement = (() => {
  2249. if (typeof cProto.__notifyPath5035__ === 'function' && cProto.__notifyPath5035__.name !== 'dummy5035') {
  2250. console.warn('YouTube Live Chat Tamer is running.');
  2251. return;
  2252. }
  2253.  
  2254. if (typeof cProto.__attached411__ === 'function' && cProto.__attached411__.name !== 'dummy411') {
  2255. console.warn('YouTube Live Chat Tamer is running.');
  2256. return;
  2257. }
  2258.  
  2259. cProto.__notifyPath5035__ = dummy5035 // just to against Live Chat Tamer
  2260. cProto.__attached411__ = dummy411 // just to against Live Chat Tamer
  2261.  
  2262. if (typeof cProto.flushRenderStamperComponentBindings_ !== 'function' || cProto.flushRenderStamperComponentBindings_.length !== 0) {
  2263. console.warn("ERROR(0xE355): cProto.flushRenderStamperComponentBindings_ not found");
  2264. return;
  2265. }
  2266.  
  2267. if (typeof cProto.flushRenderStamperComponentBindings66_ === 'function') {
  2268. console.warn("ERROR(0xE356): cProto.flushRenderStamperComponentBindings66_");
  2269. return;
  2270. }
  2271.  
  2272. if (typeof cProto.__getAllParticipantsDOMRenderedLength__ === 'function') {
  2273. console.warn("ERROR(0xE357): cProto.__getAllParticipantsDOMRenderedLength__");
  2274. return;
  2275. }
  2276. return true;
  2277. })();
  2278.  
  2279. console.log(`Data Manipulation Boost = ${canDoReplacement}`);
  2280.  
  2281. assertor(() => fnIntegrity(cProto.attached, '0.32.22')) // just warning
  2282. if (typeof cProto.flushRenderStamperComponentBindings_ === 'function') {
  2283. const fiRSCB = fnIntegrity(cProto.flushRenderStamperComponentBindings_);
  2284. const s = fiRSCB.split('.');
  2285. if (s[0] === '0' && +s[1] > 381 && +s[1] < 391 && +s[2] > 228 && +s[2] < 238) {
  2286. console.log(`flushRenderStamperComponentBindings_ ### ${fiRSCB} ### - OK`);
  2287. } else {
  2288. console.log(`flushRenderStamperComponentBindings_ ### ${fiRSCB} ### - NG`);
  2289. }
  2290. } else {
  2291. console.log("flushRenderStamperComponentBindings_ - not found");
  2292. }
  2293. // assertor(() => fnIntegrity(cProto.flushRenderStamperComponentBindings_, '0.386.233')) // just warning
  2294.  
  2295. if (typeof cProto.flushRenderStamperComponentBindings_ === 'function') {
  2296. cProto.flushRenderStamperComponentBindings66_ = cProto.flushRenderStamperComponentBindings_;
  2297. cProto.flushRenderStamperComponentBindings_ = function () {
  2298. // console.log('flushRenderStamperComponentBindings_')
  2299. this.flushRenderStamperComponentBindings66_();
  2300. if (this.resolveForDOMRendering781) {
  2301. this.resolveForDOMRendering781();
  2302. this.resolveForDOMRendering781 = null;
  2303. }
  2304. };
  2305. }
  2306.  
  2307. cProto.__getAllParticipantsDOMRenderedLength__ = function () {
  2308. const container = ((this || 0).$ || 0).participants;
  2309. if (!container) return 0;
  2310. return HTMLElement.prototype.querySelectorAll.call(container, 'yt-live-chat-participant-renderer').length;
  2311. }
  2312.  
  2313. const onPageElements = [...document.querySelectorAll('yt-live-chat-participant-list-renderer:not(.n9fJ3)')];
  2314.  
  2315. cProto.__attached412__ = cProto.attached;
  2316. const fpPList = function (hostElement) {
  2317. const cnt = insp(hostElement);
  2318. if (beforeParticipantsMap.has(cnt)) return;
  2319. hostElement.classList.add('n9fJ3');
  2320.  
  2321. assertor(() => (cnt.__dataEnabled === true && cnt.__dataReady === true));
  2322. if (typeof cnt.notifyPath !== 'function' || typeof cnt.__notifyPath5036__ !== 'undefined') {
  2323. console.warn("ERROR(0xE318): yt-live-chat-participant-list-renderer")
  2324. return;
  2325. }
  2326.  
  2327. groupCollapsed("Participant List attached", "");
  2328. // cnt.$.participants.appendChild = cnt.$.participants.__shady_native_appendChild = function(){
  2329. // console.log(123, 'appendChild');
  2330. // return HTMLElement.prototype.appendChild.apply(this, arguments)
  2331. // }
  2332.  
  2333. // cnt.$.participants.insertBefore =cnt.$.participants.__shady_native_insertBefore = function(){
  2334. // console.log(123, 'insertBefore');
  2335. // return HTMLElement.prototype.insertBefore.apply(this, arguments)
  2336. // }
  2337.  
  2338. cnt.__notifyPath5036__ = cnt.notifyPath
  2339. const participants = ((cnt.participantsManager || 0).participants || 0);
  2340. assertor(() => (participants.length > -1 && typeof participants.slice === 'function'));
  2341. console.log(`initial number of participants: ${participants.length}`);
  2342. const newParticipants = (participants.length >= 1 && typeof participants.slice === 'function') ? participants.slice(0) : [];
  2343. beforeParticipantsMap.set(cnt, newParticipants);
  2344. cnt.notifyPath = notifyPath7081;
  2345. console.log(`CHECK_CHANGE_TO_PARTICIPANT_RENDERER_CONTENT = ${CHECK_CHANGE_TO_PARTICIPANT_RENDERER_CONTENT}`);
  2346. console.groupEnd();
  2347. }
  2348. cProto.attached = function () {
  2349. fpPList(this.hostElement || this);
  2350. this.__attached412__.apply(this, arguments);
  2351. };
  2352.  
  2353.  
  2354. if (ENABLE_FLAGS_MAINTAIN_STABLE_LIST_FOR_PARTICIPANTS_LIST) {
  2355.  
  2356. /** @type {boolean | (()=>boolean)} */
  2357. let toUseMaintainStableList = USE_MAINTAIN_STABLE_LIST_ONLY_WHEN_KS_FLAG_IS_SET ? (() => ytcfg.data_.EXPERIMENT_FLAGS.kevlar_should_maintain_stable_list === true) : true;
  2358. if (typeof cProto.stampDomArray_ === 'function' && cProto.stampDomArray_.length === 6 && !cProto.stampDomArray_.nIegT && !cProto.stampDomArray66_) {
  2359.  
  2360. let lastMessageDate = 0;
  2361. cProto.stampDomArray66_ = cProto.stampDomArray_;
  2362.  
  2363. cProto.stampDomArray_ = function (...args) {
  2364. if (args[0] && args[0].length > 0 && args[1] === "participants" && args[2] && args[3] === true && !args[5]) {
  2365. if (typeof toUseMaintainStableList === 'function') {
  2366. toUseMaintainStableList = toUseMaintainStableList();
  2367. }
  2368. args[5] = toUseMaintainStableList;
  2369. let currentDate = Date.now();
  2370. if (currentDate - lastMessageDate > 440) {
  2371. lastMessageDate = currentDate;
  2372. console.log('maintain_stable_list for participants list', toUseMaintainStableList);
  2373. }
  2374. }
  2375. return this.stampDomArray66_.apply(this, args);
  2376. }
  2377.  
  2378. cProto.stampDomArray_.nIegT = 1;
  2379.  
  2380. }
  2381. console.log(`ENABLE_FLAGS_MAINTAIN_STABLE_LIST_FOR_PARTICIPANTS_LIST - YES`);
  2382. } else {
  2383. console.log(`ENABLE_FLAGS_MAINTAIN_STABLE_LIST_FOR_PARTICIPANTS_LIST - NO`);
  2384. }
  2385.  
  2386. console.groupEnd();
  2387.  
  2388. if (onPageElements.length >= 1) {
  2389. for (const s of onPageElements) {
  2390. if (insp(s).isAttached === true) {
  2391. fpPList(s);
  2392. }
  2393. }
  2394. }
  2395.  
  2396. }).catch(console.warn);
  2397.  
  2398. };
  2399.  
  2400. if (DO_PARTICIPANT_LIST_HACKS) {
  2401. promiseForCustomYtElementsReady.then(onRegistryReadyForDataManipulation);
  2402. }
  2403.  
  2404.  
  2405.  
  2406. const rafHub = (ENABLE_RAF_HACK_TICKERS || ENABLE_RAF_HACK_DOCKED_MESSAGE || ENABLE_RAF_HACK_INPUT_RENDERER || ENABLE_RAF_HACK_EMOJI_PICKER) ? new RAFHub() : null;
  2407.  
  2408.  
  2409.  
  2410.  
  2411. const bnForDelayChatOccurrence = () => {
  2412.  
  2413. document.addEventListener('animationstart', (evt) => {
  2414.  
  2415. if (evt.animationName === 'dontRenderAnimation') {
  2416. evt.target.classList.remove('dont-render');
  2417. if (scrollChatFn) scrollChatFn();
  2418. }
  2419.  
  2420. }, true);
  2421.  
  2422. const f = (elm) => {
  2423. if (elm && elm.nodeType === 1) {
  2424. if (!skipDontRender && allowDontRender === true) {
  2425. // innerTextFixFn();
  2426. elm.classList.add('dont-render');
  2427. }
  2428. }
  2429. }
  2430.  
  2431. Node.prototype.__appendChild931__ = function (a) {
  2432. a = dr(a);
  2433. if (this.id === 'items' && this.classList.contains('yt-live-chat-item-list-renderer')) {
  2434. if (a && a.nodeType === 1) f(a);
  2435. else if (a instanceof DocumentFragment) {
  2436. for (let n = a.firstChild; n; n = n.nextSibling) {
  2437. f(n);
  2438. }
  2439. }
  2440. }
  2441. }
  2442.  
  2443. Node.prototype.__appendChild932__ = function () {
  2444. this.__appendChild931__.apply(this, arguments);
  2445. return Node.prototype.appendChild.apply(this, arguments);
  2446. }
  2447.  
  2448.  
  2449. };
  2450.  
  2451. const watchUserCSS = () => {
  2452.  
  2453. // if (!CSS.supports('contain-intrinsic-size', 'auto var(--wsr94)')) return;
  2454.  
  2455. const getElemFromWR = (nr) => {
  2456. const n = kRef(nr);
  2457. if (n && n.isConnected) return n;
  2458. return null;
  2459. }
  2460.  
  2461. const clearContentVisibilitySizing = () => {
  2462. Promise.resolve().then(() => {
  2463.  
  2464. const e = document.querySelector('#show-more[disabled]');
  2465. let btnShowMoreWR = e ? mWeakRef(e) : null;
  2466.  
  2467. let lastVisibleItemWR = null;
  2468. for (const elm of document.querySelectorAll('[wSr93]')) {
  2469. if (elm.getAttribute('wSr93') === 'visible') lastVisibleItemWR = mWeakRef(elm);
  2470. elm.setAttribute('wSr93', '');
  2471. // custom CSS property --wsr94 not working when attribute wSr93 removed
  2472. }
  2473. requestAnimationFrame(() => {
  2474. const btnShowMore = getElemFromWR(btnShowMoreWR); btnShowMoreWR = null;
  2475. if (btnShowMore) btnShowMore.click();
  2476. else {
  2477. // would not work if switch it frequently
  2478. const lastVisibleItem = getElemFromWR(lastVisibleItemWR); lastVisibleItemWR = null;
  2479. if (lastVisibleItem) {
  2480.  
  2481. Promise.resolve()
  2482. .then(() => lastVisibleItem.scrollIntoView())
  2483. .then(() => lastVisibleItem.scrollIntoView(false))
  2484. .then(() => lastVisibleItem.scrollIntoView({ behavior: "instant", block: "end", inline: "nearest" }))
  2485. .catch(e => { }) // break the chain when method not callable
  2486.  
  2487. }
  2488. }
  2489. });
  2490.  
  2491. });
  2492.  
  2493. }
  2494.  
  2495. const mutObserver = new MutationObserver((mutations) => {
  2496. for (const mutation of mutations) {
  2497. if ((mutation.addedNodes || 0).length >= 1) {
  2498. for (const addedNode of mutation.addedNodes) {
  2499. if (addedNode.nodeName === 'STYLE') {
  2500. clearContentVisibilitySizing();
  2501. return;
  2502. }
  2503. }
  2504. }
  2505. if ((mutation.removedNodes || 0).length >= 1) {
  2506. for (const removedNode of mutation.removedNodes) {
  2507. if (removedNode.nodeName === 'STYLE') {
  2508. clearContentVisibilitySizing();
  2509. return;
  2510. }
  2511. }
  2512. }
  2513. }
  2514. });
  2515.  
  2516. mutObserver.observe(document.documentElement, {
  2517. childList: true,
  2518. subtree: false
  2519. });
  2520. mutObserver.observe(document.head, {
  2521. childList: true,
  2522. subtree: false
  2523. });
  2524. mutObserver.observe(document.body, {
  2525. childList: true,
  2526. subtree: false
  2527. });
  2528.  
  2529. }
  2530.  
  2531.  
  2532. class WillChangeController {
  2533. constructor(itemScroller, willChangeValue) {
  2534. this.element = itemScroller;
  2535. this.counter = 0;
  2536. this.active = false;
  2537. this.willChangeValue = willChangeValue;
  2538. }
  2539.  
  2540. beforeOper() {
  2541. if (!this.active) {
  2542. this.active = true;
  2543. this.element.style.willChange = this.willChangeValue;
  2544. }
  2545. this.counter++;
  2546. }
  2547.  
  2548. afterOper() {
  2549. const c = this.counter;
  2550. requestAnimationFrame(() => {
  2551. if (c === this.counter) {
  2552. this.active = false;
  2553. this.element.style.willChange = '';
  2554. }
  2555. });
  2556. }
  2557.  
  2558. release() {
  2559. const element = this.element;
  2560. this.element = null;
  2561. this.counter = 1e16;
  2562. this.active = false;
  2563. try {
  2564. element.style.willChange = '';
  2565. } catch (e) { }
  2566. }
  2567.  
  2568. }
  2569.  
  2570.  
  2571. const skzData = (skz) => skz.data = {
  2572. "message": {
  2573. "runs": [
  2574. {
  2575. "text": "em2o"
  2576. },
  2577. {
  2578. "emoji": {
  2579. "emojiId": "cm35z",
  2580. "shortcuts": [
  2581. ":_s:",
  2582. ":s:"
  2583. ],
  2584. "searchTerms": [
  2585. "_s",
  2586. "s"
  2587. ],
  2588. "image": {
  2589. "thumbnails": [
  2590. {
  2591. "url": dummyImgURL,
  2592. "width": 48,
  2593. "height": 48
  2594. }
  2595. ],
  2596. "accessibility": {
  2597. "accessibilityData": {
  2598. "label": "s"
  2599. }
  2600. }
  2601. },
  2602. "isCustomEmoji": true
  2603. }
  2604. },
  2605. {
  2606. "text": "ji"
  2607. }
  2608. ]
  2609. },
  2610. "authorName": {
  2611. "simpleText": "N"
  2612. },
  2613. "authorPhoto": {
  2614. "thumbnails": [
  2615. {
  2616. "url": dummyImgURL,
  2617. "width": 64,
  2618. "height": 64
  2619. }
  2620. ]
  2621. },
  2622. "contextMenuEndpoint": {
  2623. "commandMetadata": {
  2624. "webCommandMetadata": {
  2625. "ignoreNavigation": true
  2626. }
  2627. },
  2628. "liveChatItemContextMenuEndpoint": {
  2629. "params": "123=="
  2630. }
  2631. },
  2632. "id": "sk35z",
  2633. "timestampUsec": "1232302352350000",
  2634. "authorBadges": [
  2635. {
  2636. "liveChatAuthorBadgeRenderer": {
  2637. "customThumbnail": {
  2638. "thumbnails": [
  2639. {
  2640. "url": dummyImgURL,
  2641. "width": 16,
  2642. "height": 16
  2643. },
  2644. {
  2645. "url": dummyImgURL,
  2646. "width": 32,
  2647. "height": 32
  2648. }
  2649. ]
  2650. },
  2651. "tooltip": "T",
  2652. "accessibility": {
  2653. "accessibilityData": {
  2654. "label": "E"
  2655. }
  2656. }
  2657. }
  2658. }
  2659. ],
  2660. "authorExternalChannelId": "A",
  2661. "contextMenuAccessibility": {
  2662. "accessibilityData": {
  2663. "label": "E"
  2664. }
  2665. },
  2666. "timestampText": {
  2667. "simpleText": "0:43"
  2668. }
  2669. };
  2670.  
  2671.  
  2672.  
  2673. const { lcRendererElm, visObserver } = (() => {
  2674.  
  2675.  
  2676.  
  2677. let lcRendererWR = null;
  2678.  
  2679. const lcRendererElm = () => {
  2680. let lcRenderer = kRef(lcRendererWR);
  2681. if (!lcRenderer || !lcRenderer.isConnected) {
  2682. lcRenderer = document.querySelector('yt-live-chat-item-list-renderer.yt-live-chat-renderer');
  2683. lcRendererWR = lcRenderer ? mWeakRef(lcRenderer) : null;
  2684. }
  2685. return lcRenderer;
  2686. };
  2687.  
  2688.  
  2689. let hasFirstShowMore = false;
  2690.  
  2691. const visObserverFn = (entry) => {
  2692.  
  2693. const target = entry.target;
  2694. if (!target) return;
  2695. // if(target.classList.contains('dont-render')) return;
  2696. let isVisible = entry.isIntersecting === true && entry.intersectionRatio > 0.5;
  2697. // const h = entry.boundingClientRect.height;
  2698. /*
  2699. if (h < 16) { // wrong: 8 (padding/margin); standard: 32; test: 16 or 20
  2700. // e.g. under fullscreen. the element created but not rendered.
  2701. target.setAttribute('wSr93', '');
  2702. return;
  2703. }
  2704. */
  2705. if (isVisible) {
  2706. // target.style.setProperty('--wsr94', h + 'px');
  2707. target.setAttribute('wSr93', 'visible');
  2708. if (nNextElem(target) === null) {
  2709.  
  2710. // firstVisibleItemDetected = true;
  2711. /*
  2712. if (dateNow() - lastScroll < 80) {
  2713. lastLShow = 0;
  2714. lastScroll = 0;
  2715. Promise.resolve().then(clickShowMore);
  2716. } else {
  2717. lastLShow = dateNow();
  2718. }
  2719. */
  2720. // lastLShow = dateNow();
  2721. } else if (!hasFirstShowMore) { // should more than one item being visible
  2722. // implement inside visObserver to ensure there is sufficient delay
  2723. hasFirstShowMore = true;
  2724. requestAnimationFrame(() => {
  2725. // foreground page
  2726. // page visibly ready -> load the latest comments at initial loading
  2727. const lcRenderer = lcRendererElm();
  2728. if (lcRenderer) {
  2729. insp(lcRenderer).scrollToBottom_();
  2730. }
  2731. });
  2732. }
  2733. }
  2734. else if (target.getAttribute('wSr93') === 'visible') { // ignore target.getAttribute('wSr93') === '' to avoid wrong sizing
  2735.  
  2736. // target.style.setProperty('--wsr94', h + 'px');
  2737. target.setAttribute('wSr93', 'hidden');
  2738. } // note: might consider 0 < entry.intersectionRatio < 0.5 and target.getAttribute('wSr93') === '' <new last item>
  2739.  
  2740. }
  2741.  
  2742.  
  2743.  
  2744. const visObserver = new IntersectionObserver((entries) => {
  2745.  
  2746. for (const entry of entries) {
  2747.  
  2748. Promise.resolve(entry).then(visObserverFn);
  2749.  
  2750. }
  2751.  
  2752. }, {
  2753. // root: HTMLElement.prototype.closest.call(m2, '#item-scroller.yt-live-chat-item-list-renderer'), // nullable
  2754. rootMargin: "0px",
  2755. threshold: [0.05, 0.95],
  2756. });
  2757.  
  2758.  
  2759. return { lcRendererElm, visObserver }
  2760.  
  2761.  
  2762. })();
  2763.  
  2764. const { setupMutObserver } = (() => {
  2765.  
  2766. const mutFn = (items) => {
  2767. for (let node = nLastElem(items); node !== null; node = nPrevElem(node)) {
  2768. if (node.hasAttribute('wSr93')) break;
  2769. node.setAttribute('wSr93', '');
  2770. visObserver.observe(node);
  2771. }
  2772. }
  2773.  
  2774. const mutObserver = new MutationObserver((mutations) => {
  2775. const items = (mutations[0] || 0).target;
  2776. if (!items) return;
  2777. if (sk35zResolveFn) {
  2778. sk35zResolveFn();
  2779. sk35zResolveFn = null;
  2780. }
  2781. mutFn(items);
  2782. });
  2783.  
  2784. const setupMutObserver = (m2) => {
  2785. scrollChatFn = null;
  2786. mutObserver.disconnect();
  2787. mutObserver.takeRecords();
  2788. if (m2) {
  2789. ENABLE_DELAYED_CHAT_OCCURRENCE && bnForDelayChatOccurrence();
  2790. if (typeof m2.__appendChild932__ === 'function') {
  2791. if (typeof m2.appendChild === 'function') m2.appendChild = m2.__appendChild932__;
  2792. if (typeof m2.__shady_native_appendChild === 'function') m2.__shady_native_appendChild = m2.__appendChild932__;
  2793. }
  2794. mutObserver.observe(m2, {
  2795. childList: true,
  2796. subtree: false
  2797. });
  2798. mutFn(m2);
  2799.  
  2800. const isFirstList = firstList;
  2801. firstList = false;
  2802.  
  2803. if (ENABLE_OVERFLOW_ANCHOR) {
  2804.  
  2805. let items = m2;
  2806. let addedAnchor = false;
  2807. if (items) {
  2808. if (items.nextElementSibling === null) {
  2809. items.classList.add('no-anchor');
  2810. addedAnchor = true;
  2811. items.parentNode.appendChild(dr(document.createElement('item-anchor')));
  2812. }
  2813. }
  2814.  
  2815.  
  2816.  
  2817. if (addedAnchor) {
  2818. nodeParent(m2).classList.add('no-anchor'); // required
  2819. }
  2820.  
  2821. }
  2822.  
  2823. // let div = document.createElement('div');
  2824. // div.id = 'qwcc';
  2825. // HTMLElement.prototype.appendChild.call(document.querySelector('yt-live-chat-item-list-renderer'), div )
  2826. // bufferRegion =div;
  2827.  
  2828. // buffObserver.takeRecords();
  2829. // buffObserver.disconnect();
  2830. // buffObserver.observe(div, {
  2831. // childList: true,
  2832. // subtree: false
  2833. // })
  2834.  
  2835. if (ENABLE_DELAYED_CHAT_OCCURRENCE && isFirstList) {
  2836.  
  2837. promiseForCustomYtElementsReady.then(() => {
  2838.  
  2839. customElements.whenDefined('yt-live-chat-text-message-renderer').then(() => {
  2840.  
  2841.  
  2842.  
  2843.  
  2844. setTimeout(() => {
  2845.  
  2846. /** @type {HTMLTemplateElement} */
  2847. let skz = document.createElement('yt-live-chat-text-message-renderer');
  2848.  
  2849. let cz1 = null;
  2850.  
  2851. if (skz && 'data' in skz && 'attached' in skz) {
  2852.  
  2853. const deferredZy1 = new Promise(resolve => {
  2854.  
  2855. skz.attached = function () {
  2856. cz1 = HTMLElement.prototype.querySelector.call(skz, '#message img') !== null;
  2857. resolve(skz.textContent);
  2858. }
  2859. skz.detached = function () {
  2860.  
  2861. }
  2862.  
  2863. });
  2864. skz.id = 'sk35z';
  2865. skzData(skz);
  2866.  
  2867.  
  2868. sk35zResolveFn = null;
  2869. const deferredMutation = new Promise(resolve => {
  2870. sk35zResolveFn = resolve;
  2871. HTMLElement.prototype.appendChild.call(m2, skz);
  2872. });
  2873.  
  2874. Promise.all([deferredZy1, deferredMutation]).then(async (res) => {
  2875. const [zy1, _] = res;
  2876. function fn() {
  2877. const zy2 = skz.textContent;
  2878. const cz2 = HTMLElement.prototype.querySelector.call(skz, '#message img') !== null;
  2879. if (typeof zy1 === 'string' && typeof zy2 === 'string') {
  2880. allowDontRender = zy1 === zy2 && cz1 === cz2; // '0:43N​em2oji'
  2881. }
  2882. if (allowDontRender === false) {
  2883.  
  2884. console.groupCollapsed(`%c${"YouTube Super Fast Chat"}%c${" | Incompatibility Found"}`,
  2885. "background-color: #010502; color: #fe806a; font-weight: 700; padding: 2px;",
  2886. "background-color: #010502; color: #fe806a; font-weight: 300; padding: 2px;"
  2887. );
  2888.  
  2889. console.warn(`%cWarning:\n\tYou might have added a userscript or extension that stops YouTube Super Fast Chat's quick loading.\n\tTo figure out which one affects the script, turn them off one by one and let the author know.`, 'color: #bada55');
  2890.  
  2891. console.groupEnd();
  2892. } else if (allowDontRender === true) {
  2893. return true;
  2894. }
  2895. }
  2896. await new Promise(r => setTimeout(r, 1));
  2897. if (fn()) {
  2898. await new Promise(r => requestAnimationFrame(r));
  2899. if (fn()) {
  2900. skz.remove();
  2901. skz.textContent = '';
  2902. console.log('%cALLOW_DELAYED_CHAT_OCCURRENCE', 'background-color: #16c450; color: #102624; padding: 2px 4px');
  2903. }
  2904. }
  2905. });
  2906.  
  2907. }
  2908.  
  2909. }, 1);
  2910.  
  2911. }).catch(console.warn);
  2912.  
  2913. })
  2914.  
  2915. }
  2916.  
  2917.  
  2918. if (ENABLE_VIDEO_PLAYBACK_PROGRESS_STATE_FIX) {
  2919.  
  2920. (() => {
  2921.  
  2922. const tag = 'yt-iframed-player-events-relay'
  2923. const dummy = document.createElement(tag);
  2924.  
  2925. const cProto = getProto(dummy);
  2926. if (!cProto || !cProto.handlePostMessage_) {
  2927. console.warn(`proto.handlePostMessage_ for ${tag} is unavailable.`);
  2928. return;
  2929. }
  2930.  
  2931. if (typeof cProto.handlePostMessage_ === 'function' && !cProto.handlePostMessage66_) {
  2932.  
  2933. cProto.handlePostMessage66_ = cProto.handlePostMessage_;
  2934.  
  2935. cProto.handlePostMessage67_ = function (a) {
  2936.  
  2937. const da = a.data;
  2938.  
  2939.  
  2940.  
  2941. playEventsStack = playEventsStack.then(() => {
  2942.  
  2943.  
  2944.  
  2945. if ('yt-player-state-change' in da) {
  2946.  
  2947. const qc = da['yt-player-state-change'];
  2948.  
  2949.  
  2950. let isQcChanged = false;
  2951.  
  2952. if (qc === 2) { isQcChanged = qc !== _playerState; _playerState = 2; relayCount = 0; } // paused
  2953. else if (qc === 3) { isQcChanged = qc !== _playerState; _playerState = 3; } // playing
  2954. else if (qc === 1) { isQcChanged = qc !== _playerState; _playerState = 1; } // playing
  2955.  
  2956.  
  2957. if ((isQcChanged) && playerState !== _playerState) {
  2958. playerEventsByIframeRelay = true;
  2959. onPlayStateChangePromise = new Promise((resolve) => {
  2960. let k = _playerState;
  2961. foregroundPromiseFn().then(() => {
  2962. if (k === _playerState && playerState !== _playerState) playerState = _playerState;
  2963. onPlayStateChangePromise = null;
  2964. resolve();
  2965. })
  2966. }).catch(console.warn);
  2967.  
  2968. }
  2969.  
  2970. } else if ('yt-player-video-progress' in da) {
  2971. const vp = da['yt-player-video-progress'];
  2972.  
  2973.  
  2974. relayCount++;
  2975. lastPlayerProgress = vp > 0 ? vp : 0;
  2976.  
  2977.  
  2978. if (relayPromise && vp > 0 && relayCount >= 2) {
  2979. if (onPlayStateChangePromise) {
  2980. onPlayStateChangePromise.then(() => {
  2981. relayPromise && relayPromise.resolve();
  2982. relayPromise = null;
  2983. })
  2984. } else {
  2985. relayPromise.resolve();
  2986. relayPromise = null;
  2987. }
  2988. }
  2989.  
  2990.  
  2991.  
  2992. }
  2993.  
  2994.  
  2995.  
  2996.  
  2997.  
  2998.  
  2999. return this.handlePostMessage66_(a);
  3000.  
  3001.  
  3002.  
  3003. }).catch(console.warn);
  3004.  
  3005. }
  3006.  
  3007.  
  3008. cProto.handlePostMessage_ = function (a) {
  3009.  
  3010.  
  3011. const da = (a || 0).data || 0;
  3012.  
  3013. if (typeof da !== 'object') return;
  3014.  
  3015. if (waitForInitialDataCompletion === 1) return;
  3016.  
  3017. if (!isPlayProgressTriggered) {
  3018. isPlayProgressTriggered = true;
  3019.  
  3020. if ('yt-player-video-progress' in da) {
  3021. waitForInitialDataCompletion = 1;
  3022.  
  3023. const wrapWith = (data) => {
  3024. const { origin } = a;
  3025. return {
  3026. origin,
  3027. data
  3028. };
  3029. }
  3030.  
  3031. this.handlePostMessage67_(wrapWith({
  3032. "yt-iframed-parent-ready": true
  3033. }));
  3034.  
  3035.  
  3036.  
  3037. playEventsStack = playEventsStack.then(() => {
  3038.  
  3039.  
  3040.  
  3041. const lcr = document.querySelector('yt-live-chat-renderer');
  3042. const psc = document.querySelector("yt-player-seek-continuation");
  3043. if (lcr && psc && lcr.replayBuffer_) {
  3044.  
  3045.  
  3046. const rbProgress = lcr.replayBuffer_.lastVideoOffsetTimeMsec;
  3047. const daProgress = da['yt-player-video-progress'] * 1000
  3048. // document.querySelector('yt-live-chat-renderer').playerProgressChanged_(1e-5);
  3049.  
  3050.  
  3051. const front_ = (lcr.replayBuffer_.replayQueue || 0).front_;
  3052. const back_ = (lcr.replayBuffer_.replayQueue || 0).back_;
  3053.  
  3054.  
  3055. // console.log(deepCopy( front_))
  3056. // console.log(deepCopy( back_))
  3057. // console.log(rbProgress, daProgress, )
  3058. if (front_ && back_ && rbProgress > daProgress && back_.length > 2 && back_.some(e => e && +e.videoOffsetTimeMsec > daProgress) && back_.some(e => e && +e.videoOffsetTimeMsec < daProgress)) {
  3059. // no action
  3060. // console.log('ss1')
  3061. } else if (rbProgress < daProgress + 3400 && rbProgress > daProgress - 1200) {
  3062. // daProgress - 1200 < rbProgress < daProgress + 3400
  3063. // console.log('ss2')
  3064. } else {
  3065.  
  3066. // console.log('ss3')
  3067. // lcr.replayBuffer_.replayQueue.back_.length= 0;
  3068. // lcr.replayBuffer_.replayQueue.front_.length= 0;
  3069.  
  3070. // lcr
  3071. lcr.previousProgressSec = 1E-5;
  3072. // lcr._setIsSeeking(!0),
  3073. lcr.replayBuffer_.clear()
  3074. psc.fireSeekContinuation_(da['yt-player-video-progress']);
  3075. }
  3076.  
  3077. }
  3078.  
  3079.  
  3080. waitForInitialDataCompletion = 2;
  3081.  
  3082. this.handlePostMessage_(a);
  3083.  
  3084.  
  3085. }).catch(console.warn);
  3086.  
  3087.  
  3088.  
  3089. return;
  3090.  
  3091. }
  3092.  
  3093. }
  3094.  
  3095.  
  3096.  
  3097. this.handlePostMessage67_(a);
  3098.  
  3099.  
  3100.  
  3101. }
  3102.  
  3103. }
  3104.  
  3105.  
  3106. })();
  3107.  
  3108. }
  3109.  
  3110. if (isFirstList && DO_CHECK_TICKER_BACKGROUND_OVERRIDED) {
  3111. setTimeout(() => {
  3112. if (!hasTimerModified) return;
  3113. const tickerRenderer = document.querySelector('#ticker yt-live-chat-ticker-renderer.style-scope.yt-live-chat-renderer');
  3114. if (!tickerRenderer) return;
  3115.  
  3116. const tickerRendererDollar = indr(tickerRenderer);
  3117. const items = (tickerRendererDollar || 0).items || 0;
  3118. if (!items) return;
  3119. const template = document.createElement('template');
  3120. template.innerHTML = `<yt-live-chat-ticker-dummy777-item-renderer class="style-scope yt-live-chat-ticker-renderer" whole-message-clickable=""
  3121. modern="" aria-label="¥1,000" role="button" tabindex="0" id="Chw777" style="width: 94px; overflow: hidden;"
  3122. dimmed="" [dummy777]>
  3123. <div id="container" dir="ltr" class="style-scope yt-live-chat-ticker-dummy777-item-renderer"
  3124. style="--background:linear-gradient(90deg, rgba(1,2,3,1),rgba(1,2,3,1) 7%,rgba(4,0,0,1) 7%,rgba(4,0,0,1));">
  3125. <div id="content" class="style-scope yt-live-chat-ticker-dummy777-item-renderer" style="color: rgb(255, 255, 255);">
  3126. <yt-img-shadow777 id="author-photo" height="24" width="24"
  3127. class="style-scope yt-live-chat-ticker-dummy777-item-renderer no-transition"
  3128. style="background-color: transparent;" loaded=""><img id="img"
  3129. draggable="false" class="style-scope yt-img-shadow" alt="I" height="24" width="24"
  3130. src="${dummyImgURL}"></yt-img-shadow777>
  3131.  
  3132. <span id="text" dir="ltr" class="style-scope yt-live-chat-ticker-dummy777-item-renderer"1,000</span>
  3133. </div>
  3134. </div>
  3135. </yt-live-chat-ticker-dummy777-item-renderer>`;
  3136. const dummy777 = template.content.firstElementChild;
  3137. items.appendChild(dummy777);
  3138. Promise.resolve(dummy777).then((dummy777) => {
  3139. let container = HTMLElement.prototype.querySelector.call(dummy777, '#container') || 0;
  3140. if (container.isConnected === true) {
  3141.  
  3142. const evaluated = `${getComputedStyle(container).background}`;
  3143.  
  3144. container = null;
  3145. dummy777.remove();
  3146. dummy777.textContent = '';
  3147. dummy777 = null;
  3148.  
  3149. if (evaluated.indexOf('0.') < 4) {
  3150.  
  3151. // not fulfilling
  3152. // rgba(0, 0, 0, 0.004) none repeat scroll 0% 0% / auto padding-box border-box
  3153.  
  3154. console.groupCollapsed(`%c${"YouTube Super Fast Chat"}%c${" | Incompatibility Found"}`,
  3155. "background-color: #010502; color: #fe806a; font-weight: 700; padding: 2px;",
  3156. "background-color: #010502; color: #fe806a; font-weight: 300; padding: 2px;"
  3157. );
  3158. console.warn(`%cWarning:\n\tYou might have added a userscript or extension that also modifies the ticker background.\n\tYouTube Super Fast Chat is taking over.`, 'color: #bada55');
  3159. console.groupEnd();
  3160.  
  3161. console.log('%cALLOW_ADVANCED_ANIMATED_TICKER_BACKGROUND (Overriding other scripting)', 'background-color: #7eb32b; color: #102624; padding: 2px 4px');
  3162.  
  3163. } else {
  3164.  
  3165. console.log('%cALLOW_ADVANCED_ANIMATED_TICKER_BACKGROUND', 'background-color: #16c450; color: #102624; padding: 2px 4px');
  3166. }
  3167. }
  3168. });
  3169.  
  3170. }, 800);
  3171. }
  3172.  
  3173. }
  3174. }
  3175.  
  3176. return { setupMutObserver };
  3177.  
  3178.  
  3179.  
  3180. })();
  3181.  
  3182. const setupEvents = () => {
  3183.  
  3184.  
  3185. let scrollCount = 0;
  3186.  
  3187. const passiveCapture = typeof IntersectionObserver === 'function' ? { capture: true, passive: true } : true;
  3188.  
  3189.  
  3190. const delayFlushActiveItemsAfterUserActionK_ = () => {
  3191.  
  3192. const lcRenderer = lcRendererElm();
  3193. if (lcRenderer) {
  3194. const cnt = insp(lcRenderer);
  3195. if (!cnt.hasUserJustInteracted11_) return;
  3196. if (cnt.atBottom && cnt.allowScroll && cnt.activeItems_.length >= 1 && cnt.hasUserJustInteracted11_()) {
  3197. cnt.delayFlushActiveItemsAfterUserAction11_ && cnt.delayFlushActiveItemsAfterUserAction11_();
  3198. }
  3199. }
  3200.  
  3201. }
  3202.  
  3203. document.addEventListener('scroll', (evt) => {
  3204. if (!evt || !evt.isTrusted) return;
  3205. // lastScroll = dateNow();
  3206. if (++scrollCount > 1e9) scrollCount = 9;
  3207. }, passiveCapture); // support contain => support passive
  3208.  
  3209. let lastScrollCount = -1;
  3210. document.addEventListener('wheel', (evt) => {
  3211. if (!evt || !evt.isTrusted) return;
  3212. if (lastScrollCount === scrollCount) return;
  3213. lastScrollCount = scrollCount;
  3214. lastWheel = dateNow();
  3215. delayFlushActiveItemsAfterUserActionK_ && delayFlushActiveItemsAfterUserActionK_();
  3216. }, passiveCapture); // support contain => support passive
  3217.  
  3218. document.addEventListener('mousedown', (evt) => {
  3219. if (!evt || !evt.isTrusted) return;
  3220. if (((evt || 0).target || 0).id !== 'item-scroller') return;
  3221. lastMouseDown = dateNow();
  3222. currentMouseDown = true;
  3223. lastUserInteraction = lastMouseDown;
  3224. }, passiveCapture);
  3225.  
  3226. document.addEventListener('pointerdown', (evt) => {
  3227. if (!evt || !evt.isTrusted) return;
  3228. if (((evt || 0).target || 0).id !== 'item-scroller') return;
  3229. lastMouseDown = dateNow();
  3230. currentMouseDown = true;
  3231. lastUserInteraction = lastMouseDown;
  3232. }, passiveCapture);
  3233.  
  3234. document.addEventListener('click', (evt) => {
  3235. if (!evt || !evt.isTrusted) return;
  3236. if (((evt || 0).target || 0).id !== 'item-scroller') return;
  3237. lastMouseDown = lastMouseUp = dateNow();
  3238. currentMouseDown = false;
  3239. lastUserInteraction = lastMouseDown;
  3240. delayFlushActiveItemsAfterUserActionK_ && delayFlushActiveItemsAfterUserActionK_();
  3241. }, passiveCapture);
  3242.  
  3243. document.addEventListener('tap', (evt) => {
  3244. if (!evt || !evt.isTrusted) return;
  3245. if (((evt || 0).target || 0).id !== 'item-scroller') return;
  3246. lastMouseDown = lastMouseUp = dateNow();
  3247. currentMouseDown = false;
  3248. lastUserInteraction = lastMouseDown;
  3249. delayFlushActiveItemsAfterUserActionK_ && delayFlushActiveItemsAfterUserActionK_();
  3250. }, passiveCapture);
  3251.  
  3252.  
  3253. document.addEventListener('mouseup', (evt) => {
  3254. if (!evt || !evt.isTrusted) return;
  3255. if (currentMouseDown) {
  3256. lastMouseUp = dateNow();
  3257. currentMouseDown = false;
  3258. lastUserInteraction = lastMouseUp;
  3259. delayFlushActiveItemsAfterUserActionK_ && delayFlushActiveItemsAfterUserActionK_();
  3260. }
  3261. }, passiveCapture);
  3262.  
  3263.  
  3264. document.addEventListener('pointerup', (evt) => {
  3265. if (!evt || !evt.isTrusted) return;
  3266. if (currentMouseDown) {
  3267. lastMouseUp = dateNow();
  3268. currentMouseDown = false;
  3269. lastUserInteraction = lastMouseUp;
  3270. delayFlushActiveItemsAfterUserActionK_ && delayFlushActiveItemsAfterUserActionK_();
  3271. }
  3272. }, passiveCapture);
  3273.  
  3274. document.addEventListener('touchstart', (evt) => {
  3275. if (!evt || !evt.isTrusted) return;
  3276. lastTouchDown = dateNow();
  3277. currentTouchDown = true;
  3278. lastUserInteraction = lastTouchDown;
  3279. }, passiveCapture);
  3280.  
  3281. document.addEventListener('touchmove', (evt) => {
  3282. if (!evt || !evt.isTrusted) return;
  3283. lastTouchDown = dateNow();
  3284. currentTouchDown = true;
  3285. lastUserInteraction = lastTouchDown;
  3286. }, passiveCapture);
  3287.  
  3288. document.addEventListener('touchend', (evt) => {
  3289. if (!evt || !evt.isTrusted) return;
  3290. if (currentTouchDown) {
  3291. lastTouchUp = dateNow();
  3292. currentTouchDown = false;
  3293. lastUserInteraction = lastTouchUp;
  3294. delayFlushActiveItemsAfterUserActionK_ && delayFlushActiveItemsAfterUserActionK_();
  3295. }
  3296. }, passiveCapture);
  3297.  
  3298. document.addEventListener('touchcancel', (evt) => {
  3299. if (!evt || !evt.isTrusted) return;
  3300. if (currentTouchDown) {
  3301. lastTouchUp = dateNow();
  3302. currentTouchDown = false;
  3303. lastUserInteraction = lastTouchUp;
  3304. delayFlushActiveItemsAfterUserActionK_ && delayFlushActiveItemsAfterUserActionK_();
  3305. }
  3306. }, passiveCapture);
  3307.  
  3308.  
  3309. }
  3310.  
  3311. const getTimestampUsec = (itemRenderer) => {
  3312. if (itemRenderer && 'timestampUsec' in itemRenderer) {
  3313. return itemRenderer.timestampUsec
  3314. } else if (itemRenderer && itemRenderer.showItemEndpoint) {
  3315. const messageRenderer = ((itemRenderer.showItemEndpoint.showLiveChatItemEndpoint || 0).renderer || 0);
  3316. if (messageRenderer) {
  3317.  
  3318. const messageRendererKey = firstObjectKey(messageRenderer);
  3319. if (messageRendererKey && messageRenderer[messageRendererKey]) {
  3320. const messageRendererData = messageRenderer[messageRendererKey];
  3321. if (messageRendererData && 'timestampUsec' in messageRendererData) {
  3322. return messageRendererData.timestampUsec
  3323. }
  3324. }
  3325. }
  3326. }
  3327. return null;
  3328. }
  3329.  
  3330. const onRegistryReadyForDOMOperations = () => {
  3331.  
  3332. let firstCheckedOnYtInit = false;
  3333.  
  3334. const assertorURL = () => assertor(() => location.pathname.startsWith('/live_chat') && (location.search.indexOf('continuation=') > 0 || location.search.indexOf('v=') > 0));
  3335.  
  3336. const mightFirstCheckOnYtInit = () => {
  3337. if (firstCheckedOnYtInit) return;
  3338. firstCheckedOnYtInit = true;
  3339.  
  3340. if (!document.body || !document.head) return;
  3341. if (!assertorURL()) return;
  3342.  
  3343. addCssManaged();
  3344.  
  3345. let efsContainer = document.getElementById('elzm-fonts-yk75g');
  3346. if (efsContainer && efsContainer.parentNode !== document.body) {
  3347. document.body.appendChild(efsContainer);
  3348. }
  3349.  
  3350. };
  3351.  
  3352. if (!assertorURL()) return;
  3353. // if (!assertor(() => document.getElementById('yt-masthead') === null)) return;
  3354.  
  3355. if (document.documentElement && document.head) {
  3356. addCssManaged();
  3357. }
  3358. // console.log(document.body===null)
  3359.  
  3360. if (ATTEMPT_TICKER_ANIMATION_START_TIME_DETECTION) {
  3361. getLCRDummy().then(async (lcrDummy) => {
  3362.  
  3363. const tag = "yt-live-chat-renderer"
  3364. const dummy = lcrDummy;
  3365.  
  3366. const cProto = getProto(dummy);
  3367. if (!cProto || !cProto.attached) {
  3368. console.warn(`proto.attached for ${tag} is unavailable.`);
  3369. return;
  3370. }
  3371.  
  3372. mightFirstCheckOnYtInit();
  3373. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-renderer hacks");
  3374. console.log("[Begin]");
  3375.  
  3376.  
  3377.  
  3378.  
  3379.  
  3380.  
  3381. if (typeof cProto.playerProgressChanged_ === 'function' && !cProto.playerProgressChanged32_) {
  3382.  
  3383. cProto.playerProgressChanged32_ = cProto.playerProgressChanged_;
  3384.  
  3385. const pop078 = function () {
  3386. const r = this.pop78();
  3387.  
  3388. if (r && (r.actions || 0).length >= 1 && r.videoOffsetTimeMsec) {
  3389. for (const action of r.actions) {
  3390.  
  3391. const itemActionKey = !action ? null : 'addChatItemAction' in action ? 'addChatItemAction' : 'addLiveChatTickerItemAction' in action ? 'addLiveChatTickerItemAction' : null;
  3392. if (itemActionKey) {
  3393.  
  3394. const itemAction = action[itemActionKey];
  3395. const item = (itemAction || 0).item;
  3396. if (typeof item === 'object') {
  3397.  
  3398. const rendererKey = firstObjectKey(item);
  3399. if (rendererKey) {
  3400. const renderer = item[rendererKey];
  3401. if (renderer && typeof renderer === 'object') {
  3402. renderer.__videoOffsetTimeMsec__ = r.videoOffsetTimeMsec;
  3403. renderer.__progressAt__ = playerProgressChangedArg1;
  3404. }
  3405.  
  3406. }
  3407.  
  3408. }
  3409. }
  3410. }
  3411. }
  3412. return r;
  3413. }
  3414.  
  3415. cProto.playerProgressChanged_ = function (a, b, c) {
  3416. playerProgressChangedArg1 = a;
  3417. playerProgressChangedArg2 = b;
  3418. playerProgressChangedArg3 = c;
  3419. const replayBuffer_ = this.replayBuffer_;
  3420. if (replayBuffer_) {
  3421. const replayQueue = replayBuffer_.replayQueue
  3422. if (replayQueue && typeof replayQueue === 'object' && !replayQueue.qe3) {
  3423.  
  3424. replayBuffer_.replayQueue = new Proxy(replayBuffer_.replayQueue, {
  3425. get(target, prop, receiver) {
  3426. if (prop === 'qe3') return 1;
  3427. const v = target[prop];
  3428. if (prop === 'front_') {
  3429. if (v && typeof v.length === 'number') {
  3430. if (!v.pop78) {
  3431. v.pop78 = v.pop;
  3432. v.pop = pop078;
  3433. }
  3434. }
  3435. }
  3436. return v;
  3437. }
  3438. });
  3439.  
  3440. }
  3441. }
  3442. return this.playerProgressChanged32_.apply(this, arguments);
  3443. };
  3444.  
  3445. }
  3446.  
  3447. // if (typeof cProto.immediatelyApplyLiveChatActions === 'function' && !cProto.immediatelyApplyLiveChatActions32) {
  3448.  
  3449. // cProto.immediatelyApplyLiveChatActions32 = cProto.immediatelyApplyLiveChatActions;
  3450.  
  3451. // cProto.immediatelyApplyLiveChatActions = function (a) {
  3452. // // if (a.length > 8) {
  3453. // // console.log(a)
  3454. // // }
  3455. // // console.log(a)
  3456. // /*
  3457. // let arr=a.slice();
  3458.  
  3459. // if(arr.length >= 2){
  3460. // arr.sort((a, b)=>{
  3461. // let ak = firstObjectKey(a);
  3462. // let bk = firstObjectKey(b);
  3463. // if(!ak||!bk) return 0;
  3464. // const ax = +a[ak]._timestampUsec57;
  3465. // const bx = +b[bk]._timestampUsec57;
  3466. // if(ax >0 && bx >0){
  3467. // const c = bx - ax ;
  3468.  
  3469. // return c > 0.1 ? -1 : c< -0.1 ? 1 : 0;
  3470. // }
  3471. // return 0;
  3472.  
  3473. // });
  3474. // console.log('sort', JSON.parse(JSON.stringify(arr)));
  3475. // }
  3476. // a=arr;
  3477. // */
  3478.  
  3479. // if (a && typeof a === 'object' && a.length >= 1) {
  3480. // const d = Date.now();
  3481. // const m = [];
  3482. // for (let i = 0, l = a.length; i < l; i++) {
  3483. // const action = a[i];
  3484. // const key = !action ? null : 'addChatItemAction' in action ? 'addChatItemAction' : 'addLiveChatTickerItemAction' in action ? 'addLiveChatTickerItemAction' : null;
  3485. // if (key === 'addChatItemAction' || key === 'addLiveChatTickerItemAction') {
  3486. // const itemAction = action[key] || 0;
  3487. // const item = itemAction.item || 0;
  3488. // if (item && typeof item === 'object') {
  3489. // let rendererKey = firstObjectKey(item);
  3490. // const renderer = item[rendererKey];
  3491. // let timestampUsec = getTimestampUsec(renderer);
  3492. // if (timestampUsec !== null) {
  3493. // renderer._timestampUsec57 = timestampUsec;
  3494. // }
  3495. // m.push(renderer);
  3496. // // if(timestampUsec!==null){
  3497. // // if(key==='addLiveChatTickerItemAction')console.log(renderer, rendererKey, key)
  3498. // // m.push(renderer);
  3499.  
  3500. // // }
  3501. // }
  3502. // }
  3503. // }
  3504. // if (m.length >= 1) {
  3505.  
  3506. // let lastUsec = null;
  3507. // for (let i = 0, l = m.length; i < l; i++) {
  3508. // const renderer = m[i];
  3509. // if ('_timestampUsec57' in renderer) {
  3510. // lastUsec = +renderer._timestampUsec57 / 1E3;
  3511. // renderer.__lcrTime__ = d;
  3512. // renderer.__actionAt__ = d;
  3513. // }
  3514. // }
  3515.  
  3516.  
  3517. // if (lastUsec !== null) {
  3518.  
  3519. // const refUsec = lastUsec
  3520.  
  3521. // let prevUsec = null;
  3522. // for (let i = 0, l = m.length; i < l; i++) {
  3523. // const renderer = m[i];
  3524. // if ('_timestampUsec57' in renderer) {
  3525.  
  3526. // let actualTime = +renderer._timestampUsec57 / 1E3; // ms
  3527. // let lcrTime = d - Math.round(refUsec - actualTime); // ms
  3528.  
  3529. // renderer.__lcrTime__ = lcrTime; // ms
  3530. // renderer.__actionAt__ = d;
  3531.  
  3532. // prevUsec = lcrTime
  3533. // } else {
  3534.  
  3535. // renderer._prevUsec57 = prevUsec;
  3536. // }
  3537. // }
  3538.  
  3539.  
  3540. // let nextUsec = null;
  3541. // for (let i = m.length - 1; i >= 0; i--) {
  3542. // const renderer = m[i];
  3543. // if ('_timestampUsec57' in renderer) {
  3544.  
  3545. // nextUsec = renderer.__lcrTime__
  3546. // } else {
  3547.  
  3548. // renderer._nextUsec57 = nextUsec;
  3549.  
  3550. // if (renderer._nextUsec57 > 0 && renderer._prevUsec57 > 0 && renderer._nextUsec57 > renderer._prevUsec57) {
  3551. // renderer.__lcrTime__ = (renderer._nextUsec57 + renderer._prevUsec57) / 2;
  3552. // renderer.__actionAt__ = d;
  3553. // }
  3554. // }
  3555. // }
  3556.  
  3557.  
  3558. // }
  3559.  
  3560.  
  3561. // }
  3562. // }
  3563. // return this.immediatelyApplyLiveChatActions32.apply(this, arguments)
  3564. // }
  3565.  
  3566.  
  3567. // }
  3568.  
  3569.  
  3570.  
  3571. console.log("[End]");
  3572. console.groupEnd();
  3573.  
  3574.  
  3575. });
  3576.  
  3577. }
  3578.  
  3579. customElements.whenDefined('yt-live-chat-item-list-renderer').then(() => {
  3580.  
  3581. const tag = "yt-live-chat-item-list-renderer"
  3582. const dummy = document.createElement(tag);
  3583.  
  3584. const cProto = getProto(dummy);
  3585. if (!cProto || !cProto.attached) {
  3586. console.warn(`proto.attached for ${tag} is unavailable.`);
  3587. return;
  3588. }
  3589.  
  3590. mightFirstCheckOnYtInit();
  3591. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-item-list-renderer hacks");
  3592. console.log("[Begin]");
  3593.  
  3594. const mclp = cProto;
  3595. try {
  3596. assertor(() => typeof mclp.scrollToBottom_ === 'function');
  3597. assertor(() => typeof mclp.flushActiveItems_ === 'function');
  3598. assertor(() => typeof mclp.canScrollToBottom_ === 'function');
  3599. assertor(() => typeof mclp.setAtBottom === 'function');
  3600. assertor(() => typeof mclp.scrollToBottom66_ === 'undefined');
  3601. assertor(() => typeof mclp.flushActiveItems66_ === 'undefined');
  3602. } catch (e) { }
  3603.  
  3604.  
  3605. try {
  3606. assertor(() => typeof mclp.attached === 'function');
  3607. assertor(() => typeof mclp.detached === 'function');
  3608. assertor(() => typeof mclp.canScrollToBottom_ === 'function');
  3609. assertor(() => typeof mclp.isSmoothScrollEnabled_ === 'function');
  3610. assertor(() => typeof mclp.maybeResizeScrollContainer_ === 'function');
  3611. assertor(() => typeof mclp.refreshOffsetContainerHeight_ === 'function');
  3612. assertor(() => typeof mclp.smoothScroll_ === 'function');
  3613. assertor(() => typeof mclp.resetSmoothScroll_ === 'function');
  3614. } catch (e) { }
  3615.  
  3616. mclp.__intermediate_delay__ = null;
  3617.  
  3618. let mzk = 0;
  3619. let myk = 0;
  3620. let mlf = 0;
  3621. let myw = 0;
  3622. let mzt = 0;
  3623. let zarr = null;
  3624. let mlg = 0;
  3625.  
  3626. if ((mclp.clearList || 0).length === 0) {
  3627. assertor(() => fnIntegrity(mclp.clearList, '0.106.50'));
  3628. mclp.clearList66 = mclp.clearList;
  3629. mclp.clearList = function () {
  3630. mzk++;
  3631. myk++;
  3632. mlf++;
  3633. myw++;
  3634. mzt++;
  3635. mlg++;
  3636. zarr = null;
  3637. this.__intermediate_delay__ = null;
  3638. this.clearList66();
  3639. };
  3640. console.log("clearList", "OK");
  3641. } else {
  3642. console.log("clearList", "NG");
  3643. }
  3644.  
  3645.  
  3646. let onListRendererAttachedDone = false;
  3647.  
  3648. function setList(itemOffset, items) {
  3649.  
  3650. const isFirstTime = onListRendererAttachedDone === false;
  3651.  
  3652. if (isFirstTime) {
  3653. onListRendererAttachedDone = true;
  3654. Promise.resolve().then(watchUserCSS);
  3655. addCssManaged();
  3656. setupEvents();
  3657. }
  3658.  
  3659. setupStyle(itemOffset, items);
  3660.  
  3661. setupMutObserver(items);
  3662. }
  3663.  
  3664. mclp.attached419 = async function () {
  3665.  
  3666. if (!this.isAttached) return;
  3667.  
  3668. let maxTrial = 16;
  3669. while (!this.$ || !this.$['item-scroller'] || !this.$['item-offset'] || !this.$['items']) {
  3670. if (--maxTrial < 0 || !this.isAttached) return;
  3671. await new Promise(requestAnimationFrame);
  3672. }
  3673.  
  3674. if (this.isAttached !== true) return;
  3675.  
  3676. if (!this.$) {
  3677. console.warn("!this.$");
  3678. return;
  3679. }
  3680. if (!this.$) return;
  3681. /** @type {HTMLElement | null} */
  3682. const itemScroller = this.$['item-scroller'];
  3683. /** @type {HTMLElement | null} */
  3684. const itemOffset = this.$['item-offset'];
  3685. /** @type {HTMLElement | null} */
  3686. const items = this.$['items'];
  3687.  
  3688. if (!itemScroller || !itemOffset || !items) {
  3689. console.warn("items.parentNode !== itemOffset");
  3690. return;
  3691. }
  3692.  
  3693. if (nodeParent(items) !== itemOffset) {
  3694.  
  3695. console.warn("items.parentNode !== itemOffset");
  3696. return;
  3697. }
  3698.  
  3699.  
  3700. if (items.id !== 'items' || itemOffset.id !== "item-offset") {
  3701.  
  3702. console.warn("id incorrect");
  3703. return;
  3704. }
  3705.  
  3706. const isTargetItems = HTMLElement.prototype.matches.call(items, '#item-offset.style-scope.yt-live-chat-item-list-renderer > #items.style-scope.yt-live-chat-item-list-renderer')
  3707.  
  3708. if (!isTargetItems) {
  3709. console.warn("!isTargetItems");
  3710. return;
  3711. }
  3712.  
  3713. setList(itemOffset, items);
  3714.  
  3715. }
  3716.  
  3717. mclp.attached331 = mclp.attached;
  3718. mclp.attached = function () {
  3719. this.attached419 && this.attached419();
  3720. return this.attached331();
  3721. }
  3722.  
  3723. mclp.detached331 = mclp.detached;
  3724.  
  3725. mclp.detached = function () {
  3726. setupMutObserver();
  3727. return this.detached331();
  3728. }
  3729.  
  3730. const t29s = document.querySelectorAll("yt-live-chat-item-list-renderer");
  3731. for (const t29 of t29s) {
  3732. if (insp(t29).isAttached === true) {
  3733. t29.attached419();
  3734. }
  3735. }
  3736.  
  3737. if ((mclp.async || 0).length === 2 && (mclp.cancelAsync || 0).length === 1) {
  3738.  
  3739. assertor(() => fnIntegrity(mclp.async, '2.24.15'));
  3740. assertor(() => fnIntegrity(mclp.cancelAsync, '1.15.8'));
  3741.  
  3742. /** @type {Map<number, any>} */
  3743. const aMap = new Map();
  3744. let count = 6150;
  3745. mclp.async66 = mclp.async;
  3746. mclp.async = function (e, f) {
  3747. // ensure the previous operation is done
  3748. // .async is usually after the time consuming functions like flushActiveItems_ and scrollToBottom_
  3749. const hasF = arguments.length === 2;
  3750. const stack = new Error().stack;
  3751. const isFlushAsync = stack.indexOf('flushActiveItems_') >= 0;
  3752. if (count > 1e9) count = 6159;
  3753. const resId = ++count;
  3754. aMap.set(resId, e);
  3755. (this.__intermediate_delay__ || Promise.resolve()).then(rk => {
  3756. const rp = aMap.get(resId);
  3757. if (typeof rp !== 'function') {
  3758. return;
  3759. }
  3760. let cancelCall = false;
  3761. if (isFlushAsync) {
  3762. if (rk < 0) {
  3763. cancelCall = true;
  3764. } else if (rk === 2 && arguments[0] === this.maybeScrollToBottom_) {
  3765. cancelCall = true;
  3766. }
  3767. }
  3768. if (cancelCall) {
  3769. aMap.delete(resId);
  3770. } else {
  3771. const asyncEn = function () {
  3772. aMap.delete(resId);
  3773. return rp.apply(this, arguments);
  3774. };
  3775. aMap.set(resId, hasF ? this.async66(asyncEn, f) : this.async66(asyncEn));
  3776. }
  3777. });
  3778.  
  3779. return resId;
  3780. }
  3781.  
  3782. mclp.cancelAsync66 = mclp.cancelAsync;
  3783. mclp.cancelAsync = function (resId) {
  3784. if (resId <= 6150) {
  3785. this.cancelAsync66(resId);
  3786. } else if (aMap.has(resId)) {
  3787. const rp = aMap.get(resId);
  3788. aMap.delete(resId);
  3789. if (typeof rp !== 'function') {
  3790. this.cancelAsync66(rp);
  3791. }
  3792. }
  3793. }
  3794.  
  3795. console.log("async", "OK");
  3796. } else {
  3797. console.log("async", "NG");
  3798. }
  3799.  
  3800.  
  3801. if ((mclp.showNewItems_ || 0).length === 0 && ENABLE_NO_SMOOTH_TRANSFORM) {
  3802.  
  3803. assertor(() => fnIntegrity(mclp.showNewItems_, '0.170.79'));
  3804. mclp.showNewItems66_ = mclp.showNewItems_;
  3805.  
  3806. mclp.showNewItems77_ = async function () {
  3807. if (myk > 1e9) myk = 9;
  3808. let tid = ++myk;
  3809.  
  3810. await new Promise(requestAnimationFrame);
  3811.  
  3812. if (tid !== myk) {
  3813. return;
  3814. }
  3815.  
  3816. const cnt = this;
  3817.  
  3818. await Promise.resolve();
  3819. cnt.showNewItems66_();
  3820.  
  3821. await Promise.resolve();
  3822.  
  3823. }
  3824.  
  3825. mclp.showNewItems_ = function () {
  3826.  
  3827. const cnt = this;
  3828. cnt.__intermediate_delay__ = new Promise(resolve => {
  3829. cnt.showNewItems77_().then(() => {
  3830. resolve();
  3831. });
  3832. });
  3833. }
  3834.  
  3835. console.log("showNewItems_", "OK");
  3836. } else {
  3837. console.log("showNewItems_", "NG");
  3838. }
  3839.  
  3840.  
  3841. if ((mclp.flushActiveItems_ || 0).length === 0) {
  3842.  
  3843. const sfi = fnIntegrity(mclp.flushActiveItems_);
  3844. if (sfi === '0.150.84') {
  3845. // https://www.youtube.com/s/desktop/e4d15d2c/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  3846. // var b = Math.max(this.visibleItems.length + this.activeItems_.length - this.data.maxItemsToDisplay, 0);
  3847. // b && this.splice("visibleItems", 0, b);
  3848. // if (this.isSmoothScrollEnabled_() || this.dockableMessages.length)
  3849. // this.preinsertHeight_ = this.items.clientHeight;
  3850. // this.activeItems_.unshift("visibleItems");
  3851. // try {
  3852. // this.push.apply(this, this.activeItems_)
  3853. // } catch (c) {
  3854. // nm(c)
  3855. // }
  3856. // this.activeItems_ = [];
  3857. // this.isSmoothScrollEnabled_() ? this.canScrollToBottom_() && zQ(function() {
  3858. // a.showNewItems_()
  3859. // }) : zQ(function() {
  3860. // a.maybeScrollToBottom_()
  3861. // })
  3862. } else if (sfi === '0.137.81' || sfi === '0.138.81') {
  3863. // e.g. https://www.youtube.com/yts/jsbin/live_chat_polymer-vflCyWEBP/live_chat_polymer.js
  3864. } else {
  3865. assertor(() => fnIntegrity(mclp.flushActiveItems_, '0.150.84'));
  3866. }
  3867.  
  3868. let hasMoreMessageState = !ENABLE_SHOW_MORE_BLINKER ? -1 : 0;
  3869.  
  3870. let contensWillChangeController = null;
  3871.  
  3872. mclp.flushActiveItems66_ = mclp.flushActiveItems_;
  3873.  
  3874. mclp.flushActiveItems78_ = async function (tid) {
  3875. try {
  3876. if (tid !== mlf) return;
  3877. const lockedMaxItemsToDisplay = this.data.maxItemsToDisplay944;
  3878. let logger = false;
  3879. const cnt = this;
  3880. let immd = cnt.__intermediate_delay__;
  3881. await new Promise(requestAnimationFrame);
  3882.  
  3883. if (tid !== mlf || cnt.isAttached === false || (cnt.hostElement || cnt).isConnected === false) return;
  3884. if (!cnt.activeItems_ || cnt.activeItems_.length === 0) return;
  3885.  
  3886. mlf++;
  3887. if (mlg > 1e9) mlg = 9;
  3888. ++mlg;
  3889.  
  3890. const tmpMaxItemsCount = this.data.maxItemsToDisplay;
  3891. const reducedMaxItemsToDisplay = MAX_ITEMS_FOR_FULL_FLUSH;
  3892. let changeMaxItemsToDisplay = false;
  3893. const activeItemsLen = this.activeItems_.length;
  3894. if (activeItemsLen > tmpMaxItemsCount && tmpMaxItemsCount > 0) {
  3895. logger = true;
  3896.  
  3897. groupCollapsed("YouTube Super Fast Chat", " | flushActiveItems78_");
  3898.  
  3899. logger && console.log('[Begin]')
  3900.  
  3901. console.log('this.activeItems_.length > N', activeItemsLen, tmpMaxItemsCount);
  3902. if (ENABLE_REDUCED_MAXITEMS_FOR_FLUSH && lockedMaxItemsToDisplay === tmpMaxItemsCount && lockedMaxItemsToDisplay !== reducedMaxItemsToDisplay) {
  3903. console.log('reduce maxitems');
  3904. if (tmpMaxItemsCount > reducedMaxItemsToDisplay) {
  3905. // as all the rendered chats are already "outdated"
  3906. // all old chats shall remove and reduced number of few chats will be rendered
  3907. // then restore to the original number
  3908. changeMaxItemsToDisplay = true;
  3909. this.data.maxItemsToDisplay = reducedMaxItemsToDisplay;
  3910. console.log(`'maxItemsToDisplay' is reduced from ${tmpMaxItemsCount} to ${reducedMaxItemsToDisplay}.`)
  3911. }
  3912. this.activeItems_.splice(0, activeItemsLen - this.data.maxItemsToDisplay);
  3913. // console.log('changeMaxItemsToDisplay 01', this.data.maxItemsToDisplay, oMaxItemsToDisplay, reducedMaxItemsToDisplay)
  3914.  
  3915. console.log('new this.activeItems_.length > N', this.activeItems_.length);
  3916. } else {
  3917. this.activeItems_.splice(0, activeItemsLen - (tmpMaxItemsCount < 900 ? tmpMaxItemsCount : 900));
  3918.  
  3919. console.log('new this.activeItems_.length > N', this.activeItems_.length);
  3920. }
  3921. }
  3922. // it is found that it will render all stacked chats after switching back from background
  3923. // to avoid lagging in popular livestream with massive chats, trim first before rendering.
  3924. // this.activeItems_.length > this.data.maxItemsToDisplay && this.activeItems_.splice(0, this.activeItems_.length - this.data.maxItemsToDisplay);
  3925.  
  3926.  
  3927. const items = (cnt.$ || 0).items;
  3928.  
  3929. if (USE_WILL_CHANGE_CONTROLLER) {
  3930. if (contensWillChangeController && contensWillChangeController.element !== items) {
  3931. contensWillChangeController.release();
  3932. contensWillChangeController = null;
  3933. }
  3934. if (!contensWillChangeController) contensWillChangeController = new WillChangeController(items, 'contents');
  3935. }
  3936. const wcController = contensWillChangeController;
  3937. cnt.__intermediate_delay__ = Promise.all([cnt.__intermediate_delay__ || null, immd || null]);
  3938. wcController && wcController.beforeOper();
  3939. await Promise.resolve();
  3940. const acItems = cnt.activeItems_;
  3941. const len1 = acItems.length;
  3942. if (!len1) console.warn('cnt.activeItems_.length = 0');
  3943. let waitFor = [];
  3944.  
  3945.  
  3946. /** @type {Set<string>} */
  3947. const imageLinks = new Set();
  3948.  
  3949. if (ENABLE_PRELOAD_THUMBNAIL || EMOJI_IMAGE_SINGLE_THUMBNAIL || AUTHOR_PHOTO_SINGLE_THUMBNAIL) {
  3950. for (const item of acItems) {
  3951. fixLiveChatItem(item, imageLinks);
  3952. }
  3953. }
  3954. if (ENABLE_PRELOAD_THUMBNAIL && kptPF !== null && (kptPF & (8 | 4)) && imageLinks.size > 0) {
  3955. if (emojiPrefetched.size > PREFETCH_LIMITED_SIZE_EMOJI) emojiPrefetched.clear();
  3956. if (authorPhotoPrefetched.size > PREFETCH_LIMITED_SIZE_AUTHOR_PHOTO) authorPhotoPrefetched.clear();
  3957.  
  3958. // reference: https://github.com/Yuanfang-fe/Blog-X/issues/34
  3959. const rel = kptPF & 8 ? 'subresource' : kptPF & 16 ? 'preload' : kptPF & 4 ? 'prefetch' : '';
  3960. // preload performs the high priority fetching.
  3961. // prefetch delays the chat display if the video resoruce is demanding.
  3962.  
  3963. if (rel) {
  3964.  
  3965. imageLinks.forEach(imageLink => {
  3966. let d = false;
  3967. const isEmoji = imageLink.includes('/emoji/');
  3968. const pretechedSet = isEmoji ? emojiPrefetched : authorPhotoPrefetched;
  3969. if (!pretechedSet.has(imageLink)) {
  3970. pretechedSet.add(imageLink);
  3971. d = true;
  3972. }
  3973. if (d) {
  3974. waitFor.push(linker(null, rel, imageLink, 'image'));
  3975.  
  3976. }
  3977. })
  3978.  
  3979. }
  3980.  
  3981. }
  3982.  
  3983. const noVisibleItem1 = ((cnt.visibleItems || 0).length || 0) === 0;
  3984. skipDontRender = noVisibleItem1;
  3985. // console.log('ss1', Date.now())
  3986. if (waitFor.length > 0) {
  3987. await Promise.race([new Promise(r => setTimeout(r, 250)), Promise.all(waitFor)]);
  3988. }
  3989. waitFor.length = 0;
  3990. waitFor = null;
  3991. // console.log('ss2', Date.now())
  3992. cnt.flushActiveItems66_();
  3993. const noVisibleItem2 = ((cnt.visibleItems || 0).length || 0) === 0;
  3994. skipDontRender = noVisibleItem2;
  3995. const len2 = cnt.activeItems_.length;
  3996. const bAsync = len1 !== len2;
  3997. await Promise.resolve();
  3998. if (wcController) {
  3999. if (bAsync) {
  4000. cnt.async(() => {
  4001. wcController.afterOper();
  4002. });
  4003. } else {
  4004. wcController.afterOper();
  4005. }
  4006. }
  4007. if (changeMaxItemsToDisplay && this.data.maxItemsToDisplay === reducedMaxItemsToDisplay && tmpMaxItemsCount > reducedMaxItemsToDisplay) {
  4008. this.data.maxItemsToDisplay = tmpMaxItemsCount;
  4009.  
  4010. logger && console.log(`'maxItemsToDisplay' is restored from ${reducedMaxItemsToDisplay} to ${tmpMaxItemsCount}.`);
  4011. // console.log('changeMaxItemsToDisplay 02', this.data.maxItemsToDisplay, oMaxItemsToDisplay, reducedMaxItemsToDisplay)
  4012. } else if (changeMaxItemsToDisplay) {
  4013.  
  4014. logger && console.log(`'maxItemsToDisplay' cannot be restored`, {
  4015. maxItemsToDisplay: this.data.maxItemsToDisplay,
  4016. reducedMaxItemsToDisplay,
  4017. originalMaxItemsToDisplay: tmpMaxItemsCount
  4018. });
  4019. }
  4020. logger && console.log('[End]');
  4021.  
  4022. logger && console.groupEnd();
  4023.  
  4024. if (noVisibleItem1 && !noVisibleItem2) {
  4025. // fix possible no auto scroll issue.
  4026. setTimeout(() => cnt.setAtBottom(), 1);
  4027. }
  4028.  
  4029. if (!ENABLE_NO_SMOOTH_TRANSFORM) {
  4030.  
  4031.  
  4032. const ff = () => {
  4033.  
  4034. if (cnt.isAttached === false || (cnt.hostElement || cnt).isConnected === false) return;
  4035. // if (tid !== mlf || cnt.isAttached === false || (cnt.hostElement || cnt).isConnected === false) return;
  4036. if (!cnt.atBottom && cnt.allowScroll && cnt.hasUserJustInteracted11_ && !cnt.hasUserJustInteracted11_()) {
  4037. cnt.scrollToBottom_();
  4038.  
  4039. Promise.resolve().then(() => {
  4040.  
  4041. if (cnt.isAttached === false || (cnt.hostElement || cnt).isConnected === false) return;
  4042. if (!cnt.canScrollToBottom_()) cnt.scrollToBottom_();
  4043. });
  4044.  
  4045.  
  4046. }
  4047. }
  4048.  
  4049. ff();
  4050.  
  4051.  
  4052. Promise.resolve().then(ff);
  4053.  
  4054. // requestAnimationFrame(ff);
  4055. } else if (true) { // it might not be sticky to bottom when there is a full refresh.
  4056.  
  4057. const knt = cnt;
  4058. if (!scrollChatFn) {
  4059. const cnt = knt;
  4060. const f = () => {
  4061. const itemScroller = cnt.itemScroller;
  4062. if (!itemScroller || itemScroller.isConnected === false || cnt.isAttached === false) return;
  4063. if (!cnt.atBottom) {
  4064. cnt.scrollToBottom_();
  4065. } else if (itemScroller.scrollTop === 0) { // not yet interacted by user; cannot stick to bottom
  4066. itemScroller.scrollTop = itemScroller.scrollHeight;
  4067. }
  4068. };
  4069. scrollChatFn = () => Promise.resolve().then(f).then(f);
  4070. }
  4071.  
  4072. if (!ENABLE_DELAYED_CHAT_OCCURRENCE) scrollChatFn();
  4073. }
  4074.  
  4075. return 1;
  4076.  
  4077.  
  4078. } catch (e) {
  4079. console.warn(e);
  4080. }
  4081. }
  4082.  
  4083. mclp.flushActiveItems77_ = function () {
  4084.  
  4085. return new Promise(resResolve => {
  4086. try {
  4087. const cnt = this;
  4088. if (mlf > 1e9) mlf = 9;
  4089. let tid = ++mlf;
  4090. const hostElement = cnt.hostElement || cnt;
  4091. if (tid !== mlf || cnt.isAttached === false || hostElement.isConnected === false) return resResolve();
  4092. if (!cnt.activeItems_ || cnt.activeItems_.length === 0) return resResolve();
  4093.  
  4094. // 4 times to maxItems to avoid frequent trimming.
  4095. // 1 ... 10 ... 20 ... 30 ... 40 ... 50 ... 60 => 16 ... 20 ... 30 ..... 60 ... => 16
  4096.  
  4097. const lockedMaxItemsToDisplay = this.data.maxItemsToDisplay944;
  4098. this.activeItems_.length > lockedMaxItemsToDisplay * 4 && lockedMaxItemsToDisplay > 4 && this.activeItems_.splice(0, this.activeItems_.length - lockedMaxItemsToDisplay - 1);
  4099. if (cnt.canScrollToBottom_()) {
  4100. cnt.mutexPromiseFA78 = (cnt.mutexPromiseFA78 || Promise.resolve())
  4101. .then(() => cnt.flushActiveItems78_(tid)) // async function
  4102. .then((asyncResult) => {
  4103. resResolve(asyncResult); // either undefined or 1
  4104. resResolve = null;
  4105. }).catch((e) => {
  4106. console.warn(e);
  4107. if (resResolve) resResolve();
  4108. });
  4109. } else {
  4110. resResolve(2);
  4111. resResolve = null;
  4112. }
  4113. } catch (e) {
  4114. console.warn(e);
  4115. if (resResolve) resResolve();
  4116. }
  4117.  
  4118.  
  4119. });
  4120.  
  4121. }
  4122.  
  4123. mclp.flushActiveItems_ = function () {
  4124. const cnt = this;
  4125.  
  4126. if (arguments.length !== 0 || !cnt.activeItems_ || !cnt.canScrollToBottom_) return cnt.flushActiveItems66_.apply(this, arguments);
  4127.  
  4128. if (cnt.activeItems_.length === 0) {
  4129. cnt.__intermediate_delay__ = null;
  4130. return;
  4131. }
  4132.  
  4133. const cntData = ((cnt || 0).data || 0);
  4134. if (cntData.maxItemsToDisplay944 === undefined) {
  4135. cntData.maxItemsToDisplay944 = null;
  4136. if (cntData.maxItemsToDisplay > MAX_ITEMS_FOR_TOTAL_DISPLAY) cntData.maxItemsToDisplay = MAX_ITEMS_FOR_TOTAL_DISPLAY;
  4137. cntData.maxItemsToDisplay944 = cntData.maxItemsToDisplay || null;
  4138. }
  4139.  
  4140. // ignore previous __intermediate_delay__ and create a new one
  4141. cnt.__intermediate_delay__ = new Promise(resolve => {
  4142. cnt.flushActiveItems77_().then(rt => { // either undefined or 1 or 2
  4143. if (rt === 1) {
  4144. resolve(1); // success, scroll to bottom
  4145. if (hasMoreMessageState === 1) {
  4146. hasMoreMessageState = 0;
  4147. const showMore = (cnt.$ || 0)['show-more'];
  4148. if (showMore) {
  4149. showMore.classList.remove('has-new-messages-miuzp');
  4150. }
  4151. }
  4152. }
  4153. else if (rt === 2) {
  4154. resolve(2); // success, trim
  4155. if (hasMoreMessageState === 0) {
  4156. hasMoreMessageState = 1;
  4157. const showMore = cnt.$['show-more'];
  4158. if (showMore) {
  4159. showMore.classList.add('has-new-messages-miuzp');
  4160. }
  4161. }
  4162. }
  4163. else resolve(-1); // skip
  4164. }).catch(e => {
  4165. console.warn(e);
  4166. });
  4167. });
  4168.  
  4169. }
  4170. console.log("flushActiveItems_", "OK");
  4171. } else {
  4172. console.log("flushActiveItems_", "NG");
  4173. }
  4174.  
  4175. mclp.delayFlushActiveItemsAfterUserAction11_ = async function () {
  4176. try {
  4177. if (mlg > 1e9) mlg = 9;
  4178. const tid = ++mlg;
  4179. const keepTrialCond = () => this.atBottom && this.allowScroll && (tid === mlg) && this.isAttached === true && this.activeItems_.length >= 1 && (this.hostElement || 0).isConnected === true;
  4180. const runCond = () => this.canScrollToBottom_();
  4181. if (!keepTrialCond()) return;
  4182. if (runCond()) return this.flushActiveItems_() | 1; // avoid return promise
  4183. await new Promise(r => setTimeout(r, 80));
  4184. if (!keepTrialCond()) return;
  4185. if (runCond()) return this.flushActiveItems_() | 1;
  4186. await new Promise(requestAnimationFrame);
  4187. if (runCond()) return this.flushActiveItems_() | 1;
  4188. } catch (e) {
  4189. console.warn(e);
  4190. }
  4191. }
  4192.  
  4193. if ((mclp.atBottomChanged_ || 0).length === 1) {
  4194. // note: if the scrolling is too frequent, the show more visibility might get wrong.
  4195.  
  4196. const sfi = fnIntegrity(mclp.atBottomChanged_);
  4197. if (sfi === '1.73.37') {
  4198. // https://www.youtube.com/s/desktop/e4d15d2c/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  4199. } else if (sfi === '1.75.39') {
  4200. // e.g. https://www.youtube.com/yts/jsbin/live_chat_polymer-vflCyWEBP/live_chat_polymer.js
  4201. } else {
  4202. assertor(() => fnIntegrity(mclp.atBottomChanged_, '1.73.37'));
  4203. }
  4204.  
  4205. const querySelector = HTMLElement.prototype.querySelector;
  4206. const U = (element) => ({
  4207. querySelector: (selector) => querySelector.call(element, selector)
  4208. });
  4209.  
  4210. let qid = 0;
  4211. mclp.atBottomChanged_ = function (a) {
  4212. let tid = ++qid;
  4213. let b = this;
  4214. a ? this.hideShowMoreAsync_ || (this.hideShowMoreAsync_ = this.async(function () {
  4215. if (tid !== qid) return;
  4216. U(b.hostElement).querySelector("#show-more").style.visibility = "hidden"
  4217. }, 200)) : (this.hideShowMoreAsync_ && this.cancelAsync(this.hideShowMoreAsync_),
  4218. this.hideShowMoreAsync_ = null,
  4219. U(this.hostElement).querySelector("#show-more").style.visibility = "visible")
  4220. }
  4221.  
  4222. console.log("atBottomChanged_", "OK");
  4223. } else {
  4224. console.log("atBottomChanged_", "NG");
  4225. }
  4226.  
  4227. if ((mclp.onScrollItems_ || 0).length === 1) {
  4228.  
  4229. assertor(() => fnIntegrity(mclp.onScrollItems_, '1.17.9'));
  4230. mclp.onScrollItems66_ = mclp.onScrollItems_;
  4231. mclp.onScrollItems77_ = async function (evt) {
  4232. if (myw > 1e9) myw = 9;
  4233. let tid = ++myw;
  4234.  
  4235. await new Promise(requestAnimationFrame);
  4236.  
  4237. if (tid !== myw) {
  4238. return;
  4239. }
  4240.  
  4241. const cnt = this;
  4242.  
  4243. await Promise.resolve();
  4244. if (USE_OPTIMIZED_ON_SCROLL_ITEMS) {
  4245. await Promise.resolve().then(() => {
  4246. this.ytRendererBehavior.onScroll(evt);
  4247. }).then(() => {
  4248. if (this.canScrollToBottom_()) {
  4249. const hasUserJustInteracted = this.hasUserJustInteracted11_ ? this.hasUserJustInteracted11_() : true;
  4250. if (hasUserJustInteracted) {
  4251. // only when there is an user action
  4252. this.setAtBottom();
  4253. return 1;
  4254. }
  4255. } else {
  4256. // no message inserting
  4257. this.setAtBottom();
  4258. return 1;
  4259. }
  4260. }).then((r) => {
  4261.  
  4262. if (this.activeItems_.length) {
  4263.  
  4264. if (this.canScrollToBottom_()) {
  4265. this.flushActiveItems_();
  4266. return 1 && r;
  4267. } else if (this.atBottom && this.allowScroll && (this.hasUserJustInteracted11_ && this.hasUserJustInteracted11_())) {
  4268. // delayed due to user action
  4269. this.delayFlushActiveItemsAfterUserAction11_ && this.delayFlushActiveItemsAfterUserAction11_();
  4270. return 0;
  4271. }
  4272. }
  4273. }).then((r) => {
  4274. if (r) {
  4275. // ensure setAtBottom is correctly set
  4276. this.setAtBottom();
  4277. }
  4278. });
  4279. } else {
  4280. cnt.onScrollItems66_(evt);
  4281. }
  4282.  
  4283. await Promise.resolve();
  4284.  
  4285. }
  4286.  
  4287. mclp.onScrollItems_ = function (evt) {
  4288.  
  4289. const cnt = this;
  4290. cnt.__intermediate_delay__ = new Promise(resolve => {
  4291. cnt.onScrollItems77_(evt).then(() => {
  4292. resolve();
  4293. });
  4294. });
  4295. }
  4296. console.log("onScrollItems_", "OK");
  4297. } else {
  4298. console.log("onScrollItems_", "NG");
  4299. }
  4300.  
  4301. if ((mclp.handleLiveChatActions_ || 0).length === 1) {
  4302.  
  4303. const sfi = fnIntegrity(mclp.handleLiveChatActions_);
  4304. if (sfi === '1.39.20') {
  4305. // TBC
  4306. } else if (sfi === '1.31.17') {
  4307. // original
  4308. } else {
  4309. assertor(() => fnIntegrity(mclp.handleLiveChatActions_, '1.31.17'));
  4310. }
  4311.  
  4312. mclp.handleLiveChatActions66_ = mclp.handleLiveChatActions_;
  4313.  
  4314. mclp.handleLiveChatActions77_ = async function (arr) {
  4315. if (typeof (arr || 0).length !== 'number') {
  4316. this.handleLiveChatActions66_(arr);
  4317. return;
  4318. }
  4319. if (mzt > 1e9) mzt = 9;
  4320. let tid = ++mzt;
  4321.  
  4322. if (zarr === null) zarr = arr;
  4323. else Array.prototype.push.apply(zarr, arr);
  4324. arr = null;
  4325.  
  4326. await new Promise(requestAnimationFrame);
  4327.  
  4328. if (tid !== mzt || zarr === null) {
  4329. return;
  4330. }
  4331.  
  4332. const carr = zarr;
  4333. zarr = null;
  4334.  
  4335. await Promise.resolve();
  4336. this.handleLiveChatActions66_(carr);
  4337. await Promise.resolve();
  4338.  
  4339. }
  4340.  
  4341. mclp.handleLiveChatActions_ = function (arr) {
  4342.  
  4343. const cnt = this;
  4344. cnt.__intermediate_delay__ = new Promise(resolve => {
  4345. cnt.handleLiveChatActions77_(arr).then(() => {
  4346. resolve();
  4347. });
  4348. });
  4349. }
  4350. console.log("handleLiveChatActions_", "OK");
  4351. } else {
  4352. console.log("handleLiveChatActions_", "NG");
  4353. }
  4354.  
  4355. mclp.hasUserJustInteracted11_ = () => {
  4356. const t = dateNow();
  4357. return (t - lastWheel < 80) || currentMouseDown || currentTouchDown || (t - lastUserInteraction < 80);
  4358. }
  4359.  
  4360. if ((mclp.canScrollToBottom_ || 0).length === 0) {
  4361.  
  4362. assertor(() => fnIntegrity(mclp.canScrollToBottom_, '0.9.5'));
  4363.  
  4364. mclp.canScrollToBottom_ = function () {
  4365. return this.atBottom && this.allowScroll && !this.hasUserJustInteracted11_();
  4366. }
  4367.  
  4368. console.log("canScrollToBottom_", "OK");
  4369. } else {
  4370. console.log("canScrollToBottom_", "NG");
  4371. }
  4372.  
  4373. if (ENABLE_NO_SMOOTH_TRANSFORM) {
  4374.  
  4375. mclp.isSmoothScrollEnabled_ = function () {
  4376. return false;
  4377. }
  4378.  
  4379. mclp.maybeResizeScrollContainer_ = function () {
  4380. //
  4381. }
  4382.  
  4383. mclp.refreshOffsetContainerHeight_ = function () {
  4384. //
  4385. }
  4386.  
  4387. mclp.smoothScroll_ = function () {
  4388. //
  4389. }
  4390.  
  4391. mclp.resetSmoothScroll_ = function () {
  4392. //
  4393. }
  4394. console.log("ENABLE_NO_SMOOTH_TRANSFORM", "OK");
  4395. } else {
  4396. console.log("ENABLE_NO_SMOOTH_TRANSFORM", "NG");
  4397. }
  4398.  
  4399. if (typeof mclp.handleAddChatItemAction_ === 'function' && !mclp.handleAddChatItemAction66_ && FIX_THUMBNAIL_SIZE_ON_ITEM_ADDITION && (EMOJI_IMAGE_SINGLE_THUMBNAIL || AUTHOR_PHOTO_SINGLE_THUMBNAIL)) {
  4400.  
  4401. mclp.handleAddChatItemAction66_ = mclp.handleAddChatItemAction_;
  4402. mclp.handleAddChatItemAction_ = function (a) {
  4403. try {
  4404. if (a && typeof a === 'object' && !('length' in a)) {
  4405. fixLiveChatItem(a.item, null);
  4406. console.assert(arguments[0] === a);
  4407. }
  4408. } catch (e) { console.warn(e) }
  4409. return this.handleAddChatItemAction66_.apply(this, arguments);
  4410. }
  4411.  
  4412. if (FIX_THUMBNAIL_SIZE_ON_ITEM_ADDITION) console.log("handleAddChatItemAction_ [ FIX_THUMBNAIL_SIZE_ON_ITEM_ADDITION ]", "OK");
  4413. } else {
  4414.  
  4415. if (FIX_THUMBNAIL_SIZE_ON_ITEM_ADDITION) console.log("handleAddChatItemAction_ [ FIX_THUMBNAIL_SIZE_ON_ITEM_ADDITION ]", "OK");
  4416. }
  4417.  
  4418.  
  4419. if (typeof mclp.handleReplaceChatItemAction_ === 'function' && !mclp.handleReplaceChatItemAction66_ && FIX_THUMBNAIL_SIZE_ON_ITEM_REPLACEMENT && (EMOJI_IMAGE_SINGLE_THUMBNAIL || AUTHOR_PHOTO_SINGLE_THUMBNAIL)) {
  4420.  
  4421. mclp.handleReplaceChatItemAction66_ = mclp.handleReplaceChatItemAction_;
  4422. mclp.handleReplaceChatItemAction_ = function (a) {
  4423. try {
  4424. if (a && typeof a === 'object' && !('length' in a)) {
  4425. fixLiveChatItem(a.replacementItem, null);
  4426. console.assert(arguments[0] === a);
  4427. }
  4428. } catch (e) { console.warn(e) }
  4429. return this.handleReplaceChatItemAction66_.apply(this, arguments);
  4430. }
  4431.  
  4432. if (FIX_THUMBNAIL_SIZE_ON_ITEM_REPLACEMENT) console.log("handleReplaceChatItemAction_ [ FIX_THUMBNAIL_SIZE_ON_ITEM_REPLACEMENT ]", "OK");
  4433. } else {
  4434.  
  4435. if (FIX_THUMBNAIL_SIZE_ON_ITEM_REPLACEMENT) console.log("handleReplaceChatItemAction_ [ FIX_THUMBNAIL_SIZE_ON_ITEM_REPLACEMENT ]", "OK");
  4436. }
  4437.  
  4438. console.log("[End]");
  4439. console.groupEnd();
  4440.  
  4441. }).catch(console.warn);
  4442.  
  4443.  
  4444. const tickerContainerSetAttribute = function (attrName, attrValue) { // ensure '14.30000001%'.toFixed(1)
  4445.  
  4446. let yd = (this.__dataHost || insp(this).__dataHost || 0).__data;
  4447.  
  4448. if (arguments.length === 2 && attrName === 'style' && yd && attrValue) {
  4449.  
  4450. // let v = yd.containerStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;
  4451. let v = `${attrValue}`;
  4452. // conside a ticker is 101px width
  4453. // 1% = 1.01px
  4454. // 0.2% = 0.202px
  4455.  
  4456.  
  4457. const ratio1 = (yd.ratio * 100);
  4458. if (ratio1 > -1) { // avoid NaN
  4459.  
  4460. // countdownDurationMs
  4461. // 600000 - 0.2% <1% = 6s> <0.2% = 1.2s>
  4462. // 300000 - 0.5% <1% = 3s> <0.5% = 1.5s>
  4463. // 150000 - 1% <1% = 1.5s>
  4464. // 75000 - 2% <1% =0.75s > <2% = 1.5s>
  4465. // 30000 - 5% <1% =0.3s > <5% = 1.5s>
  4466.  
  4467. // 99px * 5% = 4.95px
  4468.  
  4469. // 15000 - 10% <1% =0.15s > <10% = 1.5s>
  4470.  
  4471.  
  4472. // 1% Duration
  4473.  
  4474. let ratio2 = ratio1;
  4475.  
  4476. const ydd = yd.data;
  4477. if (ydd) {
  4478.  
  4479. const d1 = ydd.durationSec;
  4480. const d2 = ydd.fullDurationSec;
  4481.  
  4482. // @ step timing [min. 0.2%]
  4483. let numOfSteps = 500;
  4484. if ((d1 === d2 || (d1 + 1 === d2)) && d1 > 1) {
  4485. if (d2 > 400) numOfSteps = 500; // 0.2%
  4486. else if (d2 > 200) numOfSteps = 200; // 0.5%
  4487. else if (d2 > 100) numOfSteps = 100; // 1%
  4488. else if (d2 > 50) numOfSteps = 50; // 2%
  4489. else if (d2 > 25) numOfSteps = 20; // 5% (max => 99px * 5% = 4.95px)
  4490. else numOfSteps = 20;
  4491. }
  4492. if (numOfSteps > TICKER_MAX_STEPS_LIMIT) numOfSteps = TICKER_MAX_STEPS_LIMIT;
  4493. if (numOfSteps < 5) numOfSteps = 5;
  4494.  
  4495. const rd = numOfSteps / 100.0;
  4496.  
  4497. ratio2 = Math.round(ratio2 * rd) / rd;
  4498.  
  4499. // ratio2 = Math.round(ratio2 * 5) / 5;
  4500. ratio2 = ratio2.toFixed(1);
  4501. v = v.replace(`${ratio1}%`, `${ratio2}%`).replace(`${ratio1}%`, `${ratio2}%`);
  4502.  
  4503. if (yd.__style_last__ === v) return;
  4504. yd.__style_last__ = v;
  4505. // do not consider any delay here.
  4506. // it shall be inside the looping for all properties changes. all the css background ops are in the same microtask.
  4507.  
  4508. }
  4509. }
  4510.  
  4511. HTMLElement.prototype.setAttribute.call(dr(this), attrName, v);
  4512.  
  4513.  
  4514. } else {
  4515. HTMLElement.prototype.setAttribute.apply(dr(this), arguments);
  4516. }
  4517.  
  4518. };
  4519.  
  4520.  
  4521. const fpTicker = (renderer) => {
  4522. const cnt = insp(renderer);
  4523. assertor(() => typeof (cnt || 0).is === 'string');
  4524. assertor(() => ((cnt || 0).hostElement || 0).nodeType === 1);
  4525. const container = (cnt.$ || 0).container;
  4526. if (container) {
  4527. assertor(() => (container || 0).nodeType === 1);
  4528. assertor(() => typeof container.setAttribute === 'function');
  4529. container.setAttribute = tickerContainerSetAttribute;
  4530. } else {
  4531. console.warn(`"container" does not exist in ${cnt.is}`);
  4532. }
  4533. };
  4534.  
  4535.  
  4536. const tags = [
  4537. "yt-live-chat-ticker-paid-message-item-renderer",
  4538. "yt-live-chat-ticker-paid-sticker-item-renderer",
  4539. "yt-live-chat-ticker-renderer",
  4540. "yt-live-chat-ticker-sponsor-item-renderer"
  4541. ];
  4542.  
  4543.  
  4544. Promise.all(tags.map(tag => customElements.whenDefined(tag))).then(() => {
  4545.  
  4546. mightFirstCheckOnYtInit();
  4547. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-ticker-... hacks");
  4548. console.log("[Begin]");
  4549.  
  4550. let dummyValueForStyleReturn = null;
  4551.  
  4552. const genDummyValueForStyleReturn = () => {
  4553. let s = `--nx:82;`
  4554. let ro = {
  4555. "privateDoNotAccessOrElseSafeStyleWrappedValue_": s,
  4556. "implementsGoogStringTypedString": true
  4557. };
  4558. ro.getTypedStringValue = ro.toString = function () { return this.privateDoNotAccessOrElseSafeStyleWrappedValue_ };
  4559. return ro;
  4560. }
  4561.  
  4562. let isCSSPropertySupported_ = null;
  4563. const isCSSPropertySupported = () => {
  4564.  
  4565. // @property --ticker-rtime
  4566.  
  4567. if (typeof isCSSPropertySupported_ === 'boolean') return isCSSPropertySupported_;
  4568. isCSSPropertySupported_ = false;
  4569.  
  4570. if (typeof CSS !== 'object' || typeof (CSS || 0).registerProperty !== 'function') return false;
  4571. const documentElement = document.documentElement;
  4572. if (!documentElement) {
  4573. console.warn('document.documentElement is not found');
  4574. return false;
  4575. }
  4576. if (`${getComputedStyle(documentElement).getPropertyValue('--ticker-rtime')}`.length === 0) {
  4577. return false;
  4578. }
  4579.  
  4580. const ae = animate.call(documentElement,
  4581. [
  4582. { '--ticker-rtime': '70%' },
  4583. { '--ticker-rtime': '30%' }
  4584. ],
  4585. {
  4586. fill: "forwards",
  4587. duration: 1000 * 40,
  4588. easing: 'linear'
  4589. }
  4590. );
  4591.  
  4592. let animatedValue = getComputedStyle(document.documentElement).getPropertyValue('--ticker-rtime');
  4593. ae.finish();
  4594. if (`${animatedValue}`.length !== 3) return false;
  4595.  
  4596. isCSSPropertySupported_ = true;
  4597. return true;
  4598.  
  4599. };
  4600.  
  4601.  
  4602. let windowShownAt = -1;
  4603. const setupEventForWindowShownAt = () => {
  4604. window.addEventListener('visibilitychange', () => {
  4605. if (document.visibilityState === 'visible') windowShownAt = Date.now();
  4606. else windowShownAt = 0;
  4607. }, false);
  4608. }
  4609.  
  4610. const dProto = {
  4611.  
  4612. attachedForTickerInit: function () {
  4613.  
  4614. fpTicker(this.hostElement || this);
  4615. return this.attached77();
  4616.  
  4617. },
  4618.  
  4619.  
  4620. // doAnimator
  4621.  
  4622. _makeAnimator: function () {
  4623. if (this._r782) return;
  4624. // if (!this.isAttached) return;
  4625. if (!this._runnerAE) {
  4626. /** @type {HTMLElement | null} */
  4627. const aElement = (this.$ || 0).container;
  4628. if (!aElement) return console.warn("this.$.container is undefined");
  4629. const da = this.data;
  4630. if (!da || !da.startBackgroundColor || !da.endBackgroundColor) return console.warn("this.data is undefined or incorrect");
  4631. const c1 = this.colorFromDecimal(da.startBackgroundColor);
  4632. const c2 = this.colorFromDecimal(da.endBackgroundColor);
  4633. if (typeof c1 !== 'string' || typeof c2 !== 'string') return console.warn('c1, c2 is not a string');
  4634.  
  4635. // if (!this.__tickerBackgroundInitialChecked__) {
  4636. // this.constructor.prototype.__tickerBackgroundInitialChecked__ = true;
  4637. // console.log('__tickerBackgroundInitialChecked__')
  4638. // this._checkTickerBackgroundChanged();
  4639. // }
  4640.  
  4641. aElement.style.setProperty('--ticker-c1', c1);
  4642. aElement.style.setProperty('--ticker-c2', c2);
  4643. aElement.classList.add(runTickerClassName);
  4644. const p = (this.countdownMs / this.countdownDurationMs) * 100;
  4645. // this._aeStartV = this.countdownMs;
  4646. // this._aeStartT = this.countdownDurationMs;
  4647. if (!(p >= 0 && p <= 100)) {
  4648. console.warn('incorrect time ratio', p);
  4649. } else {
  4650. /*
  4651. const u0 = p.toFixed(4) + '%';
  4652. this._runnerAE = animate.call(aElement,
  4653. [
  4654. { '--ticker-rtime': u0 },
  4655. { '--ticker-rtime': '0%' }
  4656. ]
  4657. ,
  4658. {
  4659. fill: "forwards",
  4660. duration: this.countdownMs,
  4661. easing: "linear"
  4662. }
  4663. );
  4664. */
  4665.  
  4666. let timingFn = 'linear';
  4667.  
  4668. const totalDuration = this.countdownDurationMs;
  4669.  
  4670. if (ATTEMPT_ANIMATED_TICKER_BACKGROUND === 'steps') {
  4671.  
  4672. // @ step timing [min. 0.2%]
  4673. let stepInterval = 0.2; // unit: %
  4674. if (totalDuration > 400000) stepInterval = 0.2;
  4675. else if (totalDuration > 200000) stepInterval = 0.5;
  4676. else if (totalDuration > 100000) stepInterval = 1;
  4677. else if (totalDuration > 50000) stepInterval = 2;
  4678. else if (totalDuration > 25000) stepInterval = 5;
  4679. else stepInterval = 5;
  4680.  
  4681. let numOfSteps = Math.round(100 / stepInterval);
  4682.  
  4683. if (numOfSteps > TICKER_MAX_STEPS_LIMIT) numOfSteps = TICKER_MAX_STEPS_LIMIT;
  4684. if (numOfSteps < 5) numOfSteps = 5;
  4685.  
  4686. timingFn = `steps(${numOfSteps}, end)`;
  4687.  
  4688. }
  4689.  
  4690.  
  4691. /** @type {Animation} */
  4692. const ae = animate.call(aElement,
  4693. [
  4694. { '--ticker-rtime': '100%' },
  4695. { '--ticker-rtime': '0%' }
  4696. ]
  4697. ,
  4698. {
  4699. fill: "forwards",
  4700. duration: totalDuration,
  4701. easing: timingFn
  4702. }
  4703. );
  4704.  
  4705. this._runnerAE = ae;
  4706.  
  4707. ae.onfinish = (event) => {
  4708. this.onfinish = null;
  4709. if (this._runnerAE !== ae) return;
  4710. if (this.isAttached === true && !this._r782 && ((this.$ || 0).container || 0).isConnected === true) {
  4711. this._aeFinished(event);
  4712. }
  4713. }
  4714.  
  4715. let bq = (1.0 - (this.countdownMs / totalDuration)) * totalDuration;
  4716.  
  4717. if (bq >= 0 && bq <= totalDuration) {
  4718.  
  4719. if (bq > totalDuration - 1) {
  4720. ae.currentTime = bq;
  4721. // setTimeout(() => {
  4722. // if (this._runnerAE === ae && ae.onfinish) ae.onfinish();
  4723. // }, 1);
  4724. } else {
  4725. ae.currentTime = bq;
  4726. }
  4727. } else {
  4728. console.warn('Error on setting _runnerAE.currentTime!');
  4729. }
  4730.  
  4731.  
  4732. aeConstructor = ae.constructor; // constructor is from iframe
  4733. return ae;
  4734. }
  4735. } else {
  4736. if (!aeConstructor) return console.warn('aeConstructor is undefined');
  4737. // assume just time update
  4738. const ae = this._runnerAE;
  4739. if (!(ae instanceof aeConstructor)) return console.warn('this._runnerAE is not Animation');
  4740. if (ae.playState !== 'paused') console.warn('ae.playState !== paused');
  4741. let p = (this.countdownMs / this.countdownDurationMs) * 100;
  4742. if (!(p >= 0 && p <= 100)) {
  4743. console.warn('incorrect time ratio', p);
  4744. } else {
  4745. // let u0 = p.toFixed(4) + '%'
  4746. /*
  4747. ae.effect.setKeyframes([
  4748. { '--ticker-rtime': u0 },
  4749. { '--ticker-rtime': '0%' }
  4750. ]);
  4751. ae.effect.updateTiming({ duration: this.countdownMs });
  4752. */
  4753. // ae.currentTime = 0;
  4754.  
  4755.  
  4756.  
  4757. let bq = (1.0 - (this.countdownMs / this.countdownDurationMs)) * this.countdownDurationMs;
  4758. if (bq >= 0 && bq <= this.countdownDurationMs) {
  4759.  
  4760. this._runnerAE.currentTime = bq
  4761. } else {
  4762. console.warn('Error on setting _runnerAE.currentTime!');
  4763. }
  4764.  
  4765.  
  4766. ae.play();
  4767. return ae;
  4768. }
  4769. }
  4770. },
  4771.  
  4772. _aeFinished: function (event) {
  4773.  
  4774. if (this._r782) return;
  4775.  
  4776. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  4777. this._throwOut();
  4778. return;
  4779. }
  4780.  
  4781. if (!this._runnerAE) console.warn('Error in .updateTimeout; this._runnerAE is undefined');
  4782.  
  4783. let lc = window.performance.now();
  4784. this.countdownMs = Math.max(0, this.countdownMs - (lc - this.lastCountdownTimeMs));
  4785. if (this.countdownMs > this.countdownDurationMs) this.countdownMs = this.countdownDurationMs;
  4786. this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = lc;
  4787. if (this.countdownMs > 76) console.warn('Warning: this.countdownMs is not zero when finished!', this.countdownMs, this, event); // just warning.
  4788.  
  4789. this.countdownMs = 0;
  4790. this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = null;
  4791.  
  4792. if (this.isAttached) {
  4793. let fastRemoved = false;
  4794. if (Date.now() - windowShownAt < 80 && typeof this.requestRemoval === 'function') {
  4795. // no animation if the video page is switched from background to foreground
  4796. // this.hostElement.style.display = 'none';
  4797. const id = (this.data || 0).id || 0;
  4798. if (!id) this.data = { id: 1 }
  4799. try {
  4800. this.requestRemoval();
  4801. fastRemoved = true;
  4802. } catch (e) {
  4803.  
  4804. }
  4805. }
  4806.  
  4807. if (!fastRemoved) {
  4808. "auto" === this.hostElement.style.width && this.setContainerWidth();
  4809. this.slideDown();
  4810. }
  4811. }
  4812.  
  4813.  
  4814.  
  4815. },
  4816.  
  4817.  
  4818. /** @type {()} */
  4819. _throwOut: function () {
  4820. this._r782 = 1;
  4821. Promise.resolve().then(() => {
  4822. if (typeof this.requestRemoval === 'function') {
  4823. const id = (this.data || 0).id;
  4824. if (!id) this.data = { id: 1 };
  4825. try {
  4826. this.requestRemoval();
  4827. } catch (e) { }
  4828. }
  4829. this.detached();
  4830. if (this.__dataClientsReady === true) this.__dataClientsReady = false;
  4831. if (this.__dataEnabled === true) this.__dataEnabled = false;
  4832. if (this.__dataReady === true) this.__dataReady = false;
  4833. this.data = null;
  4834. this.countdownMs = 0;
  4835. this.lastCountdownTimeMs = null;
  4836. const hm = this.hostElement || this;
  4837. if (hm.parentNode) hm.remove();
  4838. for (let t; t = hm.firstChild;) t.remove();
  4839. }).catch(e => {
  4840. console.warn(e);
  4841. });
  4842. },
  4843.  
  4844.  
  4845. // doTimerFnModification
  4846.  
  4847.  
  4848. /** @type {(a, b)} */
  4849. startCountdownForTimerFnModA: function (a, b) { // .startCountdown(a.durationSec, a.fullDurationSec)
  4850. try {
  4851. // a.durationSec [s] => countdownMs [ms]
  4852. // a.fullDurationSec [s] => countdownDurationMs [ms] OR countdownMs [ms]
  4853. // lastCountdownTimeMs => raf ongoing
  4854. // lastCountdownTimeMs = 0 when rafId = 0 OR countdownDurationMs = 0
  4855.  
  4856. if (this._r782) return;
  4857.  
  4858. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  4859. this._throwOut();
  4860. return;
  4861. }
  4862.  
  4863. // TimerFnModA
  4864.  
  4865. b = void 0 === b ? 0 : b;
  4866. if (void 0 !== a) {
  4867.  
  4868. this.countdownMs = 1E3 * a; // decreasing from durationSec[s] to zero
  4869. this.countdownDurationMs = b ? 1E3 * b : this.countdownMs; // constant throughout the animation
  4870. if (!(this.lastCountdownTimeMs || this.isAnimationPaused)) {
  4871. this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = performance.now()
  4872. this.rafId = 1
  4873. if (this._runnerAE) console.warn('Error in .startCountdown; this._runnerAE already created.')
  4874. this.detlaSincePausedSecs = 0;
  4875. const ae = this._makeAnimator();
  4876. if (!ae) console.warn('Error in startCountdown._makeAnimator()');
  4877.  
  4878. // if (playerProgressChangedArg1 === null) {
  4879. // console.log('startCountdownForTimerFnModA', this.data)
  4880. // }
  4881.  
  4882. if (isPlayProgressTriggered && this.isAnimationPaused !== true && this.__ENABLE_VIDEO_PROGRESS_STATE_FIX_AND_URT_PASSED__) {
  4883.  
  4884.  
  4885.  
  4886.  
  4887. this.playerProgressSec = lastPlayerProgress > 0 ? lastPlayerProgress : 0; // save the progress first
  4888. this.isAnimationPaused = true; // trigger isAnimationPausedChanged
  4889. this.detlaSincePausedSecs = 0;
  4890. this._forceNoDetlaSincePausedSecs783 = 1; // reset this.detlaSincePausedSecs = 0 when resumed
  4891.  
  4892. relayPromise = relayPromise || new PromiseExternal();
  4893.  
  4894. relayPromise.then(() => {
  4895. if (this.isAttached === true && this.countdownDurationMs > 0 && this.isAnimationPaused === true && this.isReplayPaused !== true) {
  4896. this.isAnimationPaused = false;
  4897. }
  4898. });
  4899.  
  4900.  
  4901. }
  4902.  
  4903.  
  4904.  
  4905. }
  4906. }
  4907.  
  4908. } catch (e) {
  4909. console.warn(e);
  4910. }
  4911.  
  4912. },
  4913.  
  4914.  
  4915.  
  4916. /** @type {(a, b)} */
  4917. startCountdownForTimerFnModT: function (a, b) { // .startCountdown(a.durationSec, a.fullDurationSec)
  4918. try {
  4919. // a.durationSec [s] => countdownMs [ms]
  4920. // a.fullDurationSec [s] => countdownDurationMs [ms] OR countdownMs [ms]
  4921. // lastCountdownTimeMs => raf ongoing
  4922. // lastCountdownTimeMs = 0 when rafId = 0 OR countdownDurationMs = 0
  4923.  
  4924. if (this._r782) return;
  4925.  
  4926. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  4927. this._throwOut();
  4928. return;
  4929. }
  4930.  
  4931. // TimerFnModT
  4932.  
  4933. // console.log('cProto.startCountdown', tag) // yt-live-chat-ticker-sponsor-item-renderer
  4934. if (!this.boundUpdateTimeout37_) this.boundUpdateTimeout37_ = this.updateTimeout.bind(this);
  4935. b = void 0 === b ? 0 : b;
  4936. void 0 !== a && (this.countdownMs = 1E3 * a,
  4937. this.countdownDurationMs = b ? 1E3 * b : this.countdownMs,
  4938. this.ratio = 1,
  4939. this.lastCountdownTimeMs || this.isAnimationPaused || (this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = performance.now(),
  4940. this.rafId = rafHub.request(this.boundUpdateTimeout37_)))
  4941.  
  4942. } catch (e) {
  4943. console.warn(e);
  4944. }
  4945.  
  4946. },
  4947.  
  4948.  
  4949. /** @type {(a,)} */
  4950. updateTimeoutForTimerFnModA: function (a) {
  4951.  
  4952. try {
  4953.  
  4954. // _lastCountdownTimeMsX0 is required since performance.now() is not fully the same with rAF timestamp
  4955.  
  4956. if (this._r782) return;
  4957.  
  4958. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  4959. this._throwOut();
  4960. return;
  4961. }
  4962.  
  4963. // TimerFnModA
  4964.  
  4965. if (!this._runnerAE) console.warn('Error in .updateTimeout; this._runnerAE is undefined');
  4966. if (this.lastCountdownTimeMs !== this._lastCountdownTimeMsX0) {
  4967. this.countdownMs = Math.max(0, this.countdownMs - (a - (this.lastCountdownTimeMs || 0)));
  4968. }
  4969. if (this.countdownMs > this.countdownDurationMs) this.countdownMs = this.countdownDurationMs;
  4970. if (this.isAttached && this.countdownMs) {
  4971. this.lastCountdownTimeMs = a
  4972. const ae = this._makeAnimator(); // request raf
  4973. if (!ae) console.warn('Error in startCountdown._makeAnimator()');
  4974. } else {
  4975. (this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = null,
  4976. this.isAttached && ("auto" === this.hostElement.style.width && this.setContainerWidth(),
  4977. this.slideDown()));
  4978. }
  4979.  
  4980. } catch (e) {
  4981. console.warn(e);
  4982. }
  4983.  
  4984.  
  4985. },
  4986.  
  4987. /** @type {(a,)} */
  4988. updateTimeoutForTimerFnModT: function (a) {
  4989.  
  4990. try {
  4991.  
  4992. // _lastCountdownTimeMsX0 is required since performance.now() is not fully the same with rAF timestamp
  4993.  
  4994. if (this._r782) return;
  4995.  
  4996. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  4997. this._throwOut();
  4998. return;
  4999. }
  5000.  
  5001. // TimerFnModT
  5002.  
  5003. // console.log('cProto.updateTimeout', tag) // yt-live-chat-ticker-sponsor-item-renderer
  5004. if (!this.boundUpdateTimeout37_) this.boundUpdateTimeout37_ = this.updateTimeout.bind(this);
  5005. if (this.lastCountdownTimeMs !== this._lastCountdownTimeMsX0) {
  5006. this.countdownMs = Math.max(0, this.countdownMs - (a - (this.lastCountdownTimeMs || 0)));
  5007. }
  5008. // console.log(703, this.countdownMs)
  5009. this.ratio = this.countdownMs / this.countdownDurationMs;
  5010. this.isAttached && this.countdownMs ? (this.lastCountdownTimeMs = a,
  5011. this.rafId = rafHub.request(this.boundUpdateTimeout37_)) : (this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = null,
  5012. this.isAttached && ("auto" === this.hostElement.style.width && this.setContainerWidth(),
  5013. this.slideDown()))
  5014.  
  5015.  
  5016. } catch (e) {
  5017. console.warn(e);
  5018. }
  5019. },
  5020.  
  5021. /** @type {(a,b)} */
  5022. isAnimationPausedChangedForTimerFnModA: function (a, b) {
  5023.  
  5024. if (this._r782) return;
  5025.  
  5026. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  5027. this._throwOut();
  5028. return;
  5029. }
  5030. let forceNoDetlaSincePausedSecs783 = this._forceNoDetlaSincePausedSecs783;
  5031. this._forceNoDetlaSincePausedSecs783 = 0;
  5032.  
  5033. Promise.resolve().then(() => {
  5034.  
  5035. if (a) {
  5036.  
  5037. if (this._runnerAE && this._runnerAE.playState === 'running') {
  5038.  
  5039. this._runnerAE.pause()
  5040. let lc = window.performance.now();
  5041. this.countdownMs = Math.max(0, this.countdownMs - (lc - this.lastCountdownTimeMs));
  5042. if (this.countdownMs > this.countdownDurationMs) this.countdownMs = this.countdownDurationMs;
  5043. this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = lc;
  5044. }
  5045.  
  5046. } else if (!a && b) {
  5047.  
  5048.  
  5049. if (forceNoDetlaSincePausedSecs783) this.detlaSincePausedSecs = 0;
  5050. a = this.detlaSincePausedSecs ? (this.lastCountdownTimeMs || 0) + 1000 * this.detlaSincePausedSecs : (this.lastCountdownTimeMs || 0);
  5051. this.detlaSincePausedSecs = 0;
  5052. this.updateTimeout(a);
  5053. this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = window.performance.now();
  5054.  
  5055. }
  5056.  
  5057.  
  5058. }).catch(e => {
  5059. console.log(e);
  5060. });
  5061.  
  5062.  
  5063.  
  5064. },
  5065.  
  5066.  
  5067. /** @type {(a,b)} */
  5068. isAnimationPausedChangedForTimerFnModT: function (a, b) {
  5069.  
  5070. if (this._r782) return;
  5071.  
  5072. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  5073. this._throwOut();
  5074. return;
  5075. }
  5076. let forceNoDetlaSincePausedSecs783 = this._forceNoDetlaSincePausedSecs783;
  5077. this._forceNoDetlaSincePausedSecs783 = 0;
  5078.  
  5079. Promise.resolve().then(() => {
  5080.  
  5081. // TimerFnModT
  5082.  
  5083. // ez++;
  5084. // if(ez> 1e9) ez=9;
  5085. if (!this.boundUpdateTimeout37_) this.boundUpdateTimeout37_ = this.updateTimeout.bind(this);
  5086. a ? rafHub.cancel(this.rafId) : !a && b && (a = this.lastCountdownTimeMs || 0,
  5087. this.detlaSincePausedSecs && (a = (this.lastCountdownTimeMs || 0) + 1E3 * this.detlaSincePausedSecs,
  5088. this.detlaSincePausedSecs = 0),
  5089. this.boundUpdateTimeout37_(a),
  5090. this.lastCountdownTimeMs = this._lastCountdownTimeMsX0 = window.performance.now())
  5091.  
  5092.  
  5093. }).catch(e => {
  5094. console.log(e);
  5095. });
  5096.  
  5097.  
  5098.  
  5099. },
  5100.  
  5101.  
  5102. /** @type {(a,b)} */
  5103. computeContainerStyleForAnimatorEnabled: function (a, b) {
  5104.  
  5105. if (this._r782) return;
  5106.  
  5107. if (this.isAttached === false && ((this.$ || 0).container || 0).isConnected === false) {
  5108. this._throwOut();
  5109. return;
  5110. }
  5111.  
  5112. return (dummyValueForStyleReturn || (dummyValueForStyleReturn = genDummyValueForStyleReturn()));
  5113.  
  5114. },
  5115.  
  5116.  
  5117.  
  5118. /** @type {()} */
  5119. handlePauseReplayForPlaybackProgressState: function () {
  5120. if (!playerEventsByIframeRelay) return this.handlePauseReplay66.apply(this, arguments);
  5121.  
  5122. if (onPlayStateChangePromise) {
  5123.  
  5124. if (this.rtu > 1e9) this.rtu = this.rtu % 1e4;
  5125. const tid = ++this.rtu;
  5126.  
  5127. onPlayStateChangePromise.then(() => {
  5128. if (tid === this.rtu && !onPlayStateChangePromise) this.handlePauseReplay.apply(this, arguments);
  5129. });
  5130.  
  5131. return;
  5132. }
  5133.  
  5134. if (playerState !== 2) return;
  5135. if (this.isAttached) {
  5136. if (this.rtk > 1e9) this.rtk = this.rtk % 1e4;
  5137. const tid = ++this.rtk;
  5138. const tc = relayCount;
  5139. foregroundPromiseFn().then(() => {
  5140. if (tid === this.rtk && tc === relayCount && playerState === 2 && _playerState === playerState) {
  5141. this.handlePauseReplay66();
  5142. }
  5143.  
  5144. })
  5145. }
  5146. },
  5147.  
  5148. /** @type {()} */
  5149. handleResumeReplayForPlaybackProgressState: function () {
  5150. if (!playerEventsByIframeRelay) return this.handleResumeReplay66.apply(this, arguments);
  5151.  
  5152.  
  5153. if (onPlayStateChangePromise) {
  5154.  
  5155. if (this.rtv > 1e9) this.rtv = this.rtv % 1e4;
  5156. const tid = ++this.rtv;
  5157.  
  5158. onPlayStateChangePromise.then(() => {
  5159. if (tid === this.rtv && !onPlayStateChangePromise) this.handleResumeReplay.apply(this, arguments);
  5160. });
  5161.  
  5162. return;
  5163. }
  5164.  
  5165.  
  5166. if (playerState !== 1) return;
  5167. if (this.isAttached) {
  5168. const tc = relayCount;
  5169.  
  5170. relayPromise = relayPromise || new PromiseExternal();
  5171. relayPromise.then(() => {
  5172. if (relayCount > tc && playerState === 1 && _playerState === playerState) {
  5173. this.handleResumeReplay66();
  5174. }
  5175. });
  5176. }
  5177. },
  5178.  
  5179. /** @type {(a,)} */
  5180. handleReplayProgressForPlaybackProgressState: function (a) {
  5181. if (this.isAttached) {
  5182. const tid = ++this.rtk;
  5183. foregroundPromiseFn().then(() => {
  5184. if (tid === this.rtk) {
  5185. this.handleReplayProgress66(a);
  5186. }
  5187. })
  5188. }
  5189. }
  5190.  
  5191.  
  5192. }
  5193.  
  5194.  
  5195. for (const tag of tags) { // ##tag##
  5196. const dummy = document.createElement(tag);
  5197.  
  5198. const cProto = getProto(dummy);
  5199. if (!cProto || !cProto.attached) {
  5200. console.warn(`proto.attached for ${tag} is unavailable.`);
  5201. continue;
  5202. }
  5203.  
  5204. cProto.attached77 = cProto.attached;
  5205.  
  5206. cProto.attached = dProto.attachedForTickerInit;
  5207.  
  5208. let rafHackState = 0;
  5209.  
  5210. let isTimingFunctionHackable = false;
  5211.  
  5212. let urt = 0;
  5213.  
  5214. if (typeof cProto.startCountdown === 'function' && typeof cProto.updateTimeout === 'function' && typeof cProto.isAnimationPausedChanged === 'function') {
  5215.  
  5216. // console.log('startCountdown', typeof cProto.startCountdown)
  5217. // console.log('updateTimeout', typeof cProto.updateTimeout)
  5218. // console.log('isAnimationPausedChanged', typeof cProto.isAnimationPausedChanged)
  5219.  
  5220. isTimingFunctionHackable = fnIntegrity(cProto.startCountdown, '2.66.37') && fnIntegrity(cProto.updateTimeout, '1.76.45') && fnIntegrity(cProto.isAnimationPausedChanged, '2.56.30')
  5221.  
  5222. } else {
  5223. console.log(`Skip Timing Function Modification for ${tag}`);
  5224. continue;
  5225. }
  5226.  
  5227.  
  5228. if (ENABLE_RAF_HACK_TICKERS && rafHub !== null) {
  5229.  
  5230. // cancelable - this.rafId < isAnimationPausedChanged >
  5231. rafHackState = 1;
  5232.  
  5233. if (isTimingFunctionHackable) {
  5234. rafHackState = 2;
  5235.  
  5236. } else {
  5237. rafHackState = 4;
  5238. }
  5239.  
  5240. }
  5241.  
  5242. const doAnimator = !!ATTEMPT_ANIMATED_TICKER_BACKGROUND && isTimingFunctionHackable && typeof KeyframeEffect === 'function' && typeof animate === 'function' && typeof cProto.computeContainerStyle === 'function' && typeof cProto.colorFromDecimal === 'function' && isCSSPropertySupported();
  5243.  
  5244. const doRAFHack = rafHackState === 2;
  5245.  
  5246. cProto._throwOut = dProto._throwOut;
  5247.  
  5248. cProto._makeAnimator = doAnimator ? dProto._makeAnimator : null;
  5249.  
  5250. cProto._aeFinished = doAnimator ? dProto._aeFinished : null;
  5251.  
  5252.  
  5253. if (ENABLE_VIDEO_PLAYBACK_PROGRESS_STATE_FIX) {
  5254.  
  5255.  
  5256.  
  5257. if (typeof cProto.handlePauseReplay === 'function' && !cProto.handlePauseReplay66 && cProto.handlePauseReplay.length === 0) {
  5258. urt++;
  5259. assertor(() => fnIntegrity(cProto.handlePauseReplay, '0.12.4'));
  5260. } else {
  5261. console.log('Error for setting cProto.handlePauseReplay', tag)
  5262. }
  5263.  
  5264. if (typeof cProto.handleResumeReplay === 'function' && !cProto.handleResumeReplay66 && cProto.handlePauseReplay.length === 0) {
  5265. urt++;
  5266. assertor(() => fnIntegrity(cProto.handleResumeReplay, '0.8.2'));
  5267. } else {
  5268. console.log('Error for setting cProto.handleResumeReplay', tag)
  5269. }
  5270.  
  5271. if (typeof cProto.handleReplayProgress === 'function' && !cProto.handleReplayProgress66 && cProto.handleReplayProgress.length === 1) {
  5272. urt++;
  5273. assertor(() => fnIntegrity(cProto.handleReplayProgress, '1.16.13'));
  5274. } else {
  5275. console.log('Error for setting cProto.handleReplayProgress', tag)
  5276. }
  5277.  
  5278.  
  5279.  
  5280. }
  5281.  
  5282. const ENABLE_VIDEO_PROGRESS_STATE_FIX_AND_URT_PASSED = ENABLE_VIDEO_PLAYBACK_PROGRESS_STATE_FIX && urt === 3;
  5283. cProto.__ENABLE_VIDEO_PROGRESS_STATE_FIX_AND_URT_PASSED__ = ENABLE_VIDEO_PROGRESS_STATE_FIX_AND_URT_PASSED;
  5284.  
  5285. if (ENABLE_VIDEO_PROGRESS_STATE_FIX_AND_URT_PASSED) {
  5286.  
  5287. cProto.rtk = 0;
  5288. cProto.rtu = 0;
  5289. cProto.rtv = 0;
  5290.  
  5291. cProto.handlePauseReplay66 = cProto.handlePauseReplay;
  5292. cProto.handlePauseReplay = dProto.handlePauseReplayForPlaybackProgressState;
  5293.  
  5294. cProto.handleResumeReplay66 = cProto.handleResumeReplay;
  5295. cProto.handleResumeReplay = dProto.handleResumeReplayForPlaybackProgressState;
  5296.  
  5297. cProto.handleReplayProgress66 = cProto.handleReplayProgress;
  5298. cProto.handleReplayProgress = dProto.handleReplayProgressForPlaybackProgressState;
  5299.  
  5300. }
  5301.  
  5302. const doTimerFnModification = (doRAFHack || doAnimator);
  5303.  
  5304. if (doAnimator && windowShownAt < 0) {
  5305. windowShownAt = 0;
  5306. setupEventForWindowShownAt();
  5307. }
  5308.  
  5309. if (doTimerFnModification) {
  5310.  
  5311. cProto.startCountdown = (
  5312. doAnimator ? dProto.startCountdownForTimerFnModA : dProto.startCountdownForTimerFnModT
  5313. );
  5314.  
  5315. // _lastCountdownTimeMsX0 is required since performance.now() is not fully the same with rAF timestamp
  5316. cProto.updateTimeout = (
  5317. doAnimator ? dProto.updateTimeoutForTimerFnModA : dProto.updateTimeoutForTimerFnModT
  5318. );
  5319.  
  5320.  
  5321. // let ez = 0;
  5322. cProto.isAnimationPausedChanged = (
  5323. doAnimator ? dProto.isAnimationPausedChangedForTimerFnModA : dProto.isAnimationPausedChangedForTimerFnModT
  5324. );
  5325.  
  5326. }
  5327.  
  5328. if (doAnimator) {
  5329.  
  5330. const s = fnIntegrity(cProto.computeContainerStyle);
  5331. // 2.44.29 or 2.81.31
  5332. if (s === '2.44.29' || s === '2.81.31') {
  5333.  
  5334. // var ofb = da([""])
  5335. // pfb = da("background:linear-gradient(90deg, {,{ {,{ {,{);".split("{"))
  5336.  
  5337. // f.computeContainerStyle = function(a, b) {
  5338. // if (!a)
  5339. // return pi(ofb);
  5340. // var c = this.colorFromDecimal(a.startBackgroundColor);
  5341. // a = this.colorFromDecimal(a.endBackgroundColor);
  5342. // b = 100 * b + "%";
  5343. // return pi(pfb, c, c, b, a, b, a)
  5344. // }
  5345.  
  5346. } else {
  5347. assertor(() => fnIntegrity(cProto.computeContainerStyle, '2.44.29'));
  5348. }
  5349.  
  5350. cProto.computeContainerStyle66 = cProto.computeContainerStyle;
  5351.  
  5352. cProto.computeContainerStyle = dProto.computeContainerStyleForAnimatorEnabled;
  5353.  
  5354. }
  5355.  
  5356. if (doTimerFnModification === true) hasTimerModified = true;
  5357.  
  5358. if (!!ATTEMPT_ANIMATED_TICKER_BACKGROUND) {
  5359. console.log('ATTEMPT_ANIMATED_TICKER_BACKGROUND', tag, doAnimator ? 'OK' : 'NG');
  5360. }
  5361.  
  5362. if (!doAnimator && (rafHackState === 2 || rafHackState === 4)) {
  5363. console.log('RAF_HACK_TICKERS', tag, doRAFHack ? "OK" : "NG");
  5364. }
  5365.  
  5366. }
  5367.  
  5368. const selector = tags.join(', ');
  5369. const elements = document.querySelectorAll(selector);
  5370. if (elements.length >= 1) {
  5371. for (const elm of elements) {
  5372. if (insp(elm).isAttached === true) {
  5373. fpTicker(elm);
  5374. }
  5375. }
  5376. }
  5377.  
  5378. console.log("[End]");
  5379. console.groupEnd();
  5380.  
  5381.  
  5382. }).catch(console.warn);
  5383.  
  5384. customElements.whenDefined('yt-live-chat-ticker-renderer').then(() => {
  5385.  
  5386. mightFirstCheckOnYtInit();
  5387. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-ticker-renderer hacks");
  5388. console.log("[Begin]");
  5389. (() => {
  5390.  
  5391. /* pending!!
  5392.  
  5393. handleLiveChatAction
  5394.  
  5395. removeTickerItemById
  5396.  
  5397. _itemsChanged
  5398. itemsChanged
  5399.  
  5400. handleMarkChatItemAsDeletedAction
  5401. handleMarkChatItemsByAuthorAsDeletedAction
  5402. handleRemoveChatItemByAuthorAction
  5403.  
  5404.  
  5405. */
  5406.  
  5407. const tag = "yt-live-chat-ticker-renderer"
  5408. const dummy = document.createElement(tag);
  5409.  
  5410. const cProto = getProto(dummy);
  5411. if (!cProto || !cProto.attached) {
  5412. console.warn(`proto.attached for ${tag} is unavailable.`);
  5413. return;
  5414. }
  5415.  
  5416. if (AMEND_TICKER_handleLiveChatAction
  5417. && typeof cProto.handleLiveChatAction === 'function' && !cProto.handleLiveChatAction45 && '|1.63.48|1.64.48|'.includes(`|${fnIntegrity(cProto.handleLiveChatAction)}|`)
  5418. && typeof cProto.handleLiveChatActions === 'function' && !cProto.handleLiveChatActions45 && fnIntegrity(cProto.handleLiveChatActions) === '1.23.12'
  5419. && typeof cProto.unshift === 'function' && cProto.unshift.length === 1
  5420. && typeof cProto.handleMarkChatItemAsDeletedAction === 'function' && cProto.handleMarkChatItemAsDeletedAction.length === 1
  5421. && typeof cProto.removeTickerItemById === 'function' && cProto.removeTickerItemById.length === 1
  5422. && typeof cProto.handleMarkChatItemsByAuthorAsDeletedAction === 'function' && cProto.handleMarkChatItemsByAuthorAsDeletedAction.length === 1
  5423. && typeof cProto.handleRemoveChatItemByAuthorAction === 'function' && cProto.handleRemoveChatItemByAuthorAction.length === 1
  5424. ) {
  5425.  
  5426. cProto.handleLiveChatActions45 = cProto.handleLiveChatActions;
  5427.  
  5428. cProto.handleLiveChatActions = function (a) {
  5429. /**
  5430. *
  5431. f.handleLiveChatActions = function(a) {
  5432. a.length && (a.forEach(this.handleLiveChatAction, this),
  5433. this.updateHighlightedItem(),
  5434. this.shouldAnimateIn = !0)
  5435. }
  5436. *
  5437. */
  5438.  
  5439. if (a.length) {
  5440. const batchToken = String.fromCharCode(Date.now() % 26 + 97) + Math.floor(Math.random() * 19861 + 19861).toString(36);
  5441. const len = a.length;
  5442. if (FIX_BATCH_TICKER_ORDER && len >= 2) {
  5443. // Primarily for the initial batch, this is due to replayBuffer._back.
  5444. const entries = [];
  5445. const entriesI = [];
  5446. for (let i = 0; i < len; i++) {
  5447. const item = ((a[i] || 0).addLiveChatTickerItemAction || 0).item || 0;
  5448. if (item) {
  5449. const itemRendererKey = firstObjectKey(item);
  5450. const itemRenderer = item[itemRendererKey];
  5451. if (itemRenderer) {
  5452. let timestampUsec = getTimestampUsec(itemRenderer);
  5453. if (timestampUsec !== null) {
  5454. timestampUsec = parseInt(timestampUsec);
  5455. if (timestampUsec > 0) {
  5456. entriesI.push(i);
  5457. entries.push({ e: a[i], timestampUsec })
  5458. }
  5459. }
  5460. }
  5461. }
  5462. }
  5463. const mLen = entries.length;
  5464. if (mLen >= 2) {
  5465. entries.sort((a, b) => {
  5466. const diff = a.timestampUsec - b.timestampUsec;
  5467. return diff > 0.1 ? 1 : diff < -0.1 ? -1 : 0;
  5468. });
  5469. for (let j = 0; j < mLen; j++) {
  5470. const i = entriesI[j];
  5471. a[i] = entries[j].e;
  5472. }
  5473. }
  5474. entries.length = 0;
  5475. entriesI.length = 0;
  5476. }
  5477. for (const action of a) {
  5478. action.__batchId45__ = batchToken;
  5479. this.handleLiveChatAction(action);
  5480. }
  5481. }
  5482. }
  5483.  
  5484. cProto.handleLiveChatAction45 = cProto.handleLiveChatAction;
  5485.  
  5486.  
  5487.  
  5488. cProto._nszlv_ = 0;
  5489. cProto._stackedLCAs_ = null;
  5490. cProto._lastAddItem_ = null;
  5491. cProto._lastAddItemInStack_ = false;
  5492. cProto.handleLiveChatAction = function (a) {
  5493.  
  5494.  
  5495. /**
  5496. *
  5497. *
  5498. f.handleLiveChatAction = function(a) {
  5499. var b = C(a, xO)
  5500. , c = C(a, yO)
  5501. , d = C(a, o1a)
  5502. , e = C(a, p1a);
  5503. a = C(a, A1a);
  5504. b ? this.unshift("items", b.item) : c ? this.handleMarkChatItemAsDeletedAction(c) : d ? this.removeTickerItemById(d.targetItemId) : e ? this.handleMarkChatItemsByAuthorAsDeletedAction(e) : a && this.handleRemoveChatItemByAuthorAction(a)
  5505. }
  5506. *
  5507. */
  5508.  
  5509. // return this.handleLiveChatAction45(a)
  5510. const { addChatItemAction, addLiveChatTickerItemAction, markChatItemAsDeletedAction,
  5511. removeChatItemAction, markChatItemsByAuthorAsDeletedAction, removeChatItemByAuthorAction, __batchId45__ } = a
  5512.  
  5513. if (addChatItemAction) return;
  5514.  
  5515.  
  5516. const d = Date.now();
  5517.  
  5518.  
  5519. // console.log(Object.keys(a));
  5520.  
  5521. if (this._stackedLCAs_ === null) this._stackedLCAs_ = [];
  5522. const stackArr = this._stackedLCAs_;
  5523. let newStackEntry = null;
  5524. if (addLiveChatTickerItemAction) {
  5525. let isDuplicated = false;
  5526.  
  5527. const newItem = addLiveChatTickerItemAction.item;
  5528. const tickerType = firstObjectKey(newItem);
  5529. if (!tickerType) return;
  5530. const tickerItem = newItem[tickerType];
  5531. const tickerId = tickerItem.id;
  5532. if (!tickerId) return;
  5533.  
  5534. if (this._lastAddItem_ && this._lastAddItem_.id === tickerId) {
  5535. let prevTickerItem = null;
  5536. if (this._lastAddItemInStack_) {
  5537. const entry = stackArr[stackArr.length - 1]; // only consider the last entry
  5538. if (entry && entry.action === 'addItem') {
  5539. prevTickerItem = entry.data; // only consider the first item;
  5540. }
  5541. } else {
  5542. prevTickerItem = this.items[0]; // only consider the first item;
  5543. }
  5544. if (prevTickerItem && prevTickerItem[tickerType]) {
  5545. if (prevTickerItem[tickerType].id === tickerId) {
  5546. isDuplicated = true;
  5547. }
  5548. }
  5549. }
  5550. if (!isDuplicated) {
  5551. this._lastAddItem_ = tickerItem;
  5552. this._lastAddItemInStack_ = true;
  5553. // console.log('newItem', newItem)
  5554.  
  5555. const item = newItem;
  5556. const key = firstObjectKey(item);
  5557. if (key) {
  5558. const itemRenderer = item[key] || 0;
  5559. if (itemRenderer.fullDurationSec > 0) {
  5560. itemRenderer.__actionAt__ = d;
  5561. }
  5562. }
  5563.  
  5564.  
  5565. newStackEntry = { action: 'addItem', data: newItem };
  5566.  
  5567. } else {
  5568. console.log('handleLiveChatAction Repeated Item', tickerItem.id, tickerItem); // happen in both live and playback. Reason Unknown.
  5569. return;
  5570. }
  5571.  
  5572. } else {
  5573. markChatItemAsDeletedAction && (newStackEntry = { action: 'mcItemD', data: markChatItemAsDeletedAction });
  5574. removeChatItemAction && (newStackEntry = { action: 'removeItemById', data: removeChatItemAction.targetId });
  5575. markChatItemsByAuthorAsDeletedAction && (newStackEntry = { action: 'mcItemAD', data: markChatItemsByAuthorAsDeletedAction });
  5576. removeChatItemByAuthorAction && (newStackEntry = { action: 'removeItemA', data: removeChatItemByAuthorAction })
  5577. }
  5578.  
  5579.  
  5580. if (!newStackEntry) return;
  5581. stackArr.push(newStackEntry);
  5582.  
  5583.  
  5584. this._nszlv_++;
  5585. if (this._nszlv_ > 1e9) this._nszlv_ = 9;
  5586. const tid = this._nszlv_;
  5587.  
  5588. newStackEntry.__batchId45__ = __batchId45__ || '';
  5589. newStackEntry.dateTime = Date.now();
  5590.  
  5591.  
  5592. foregroundPromiseFn().then(() => {
  5593.  
  5594. if (tid !== this._nszlv_) return;
  5595. const dateNow = Date.now(); // time difference to shift animation start time shall be considered. (pending)
  5596. const stackArr = this._stackedLCAs_.slice(0);
  5597. this._stackedLCAs_.length = 0;
  5598. this._lastAddItemInStack_ = false;
  5599. let lastDateTime = 0;
  5600. let prevBatchId = '';
  5601. const addItems = [];
  5602. // const previousShouldAnimateIn = this.shouldAnimateIn;
  5603.  
  5604. const addItemsFx = () => {
  5605.  
  5606. if (addItems.length >= 1) {
  5607. const eArr = addItems.slice(0);
  5608. addItems.length = 0;
  5609. if (ADJUST_TICKER_DURATION_ALIGN_RENDER_TIME) {
  5610.  
  5611. const arr = []; // size of arr <= size of eArr
  5612. const d = Date.now();
  5613. for (const item of eArr) {
  5614. const key = firstObjectKey(item);
  5615. if (key) {
  5616.  
  5617.  
  5618. const itemRenderer = item[key] || 0;
  5619. const { durationSec, fullDurationSec, __actionAt__ } = itemRenderer;
  5620. if (__actionAt__ > 0 && durationSec > 0 && fullDurationSec > 0) {
  5621.  
  5622.  
  5623. const offset = d - __actionAt__;
  5624. if (offset > 0 && typeof durationSec === 'number' && typeof fullDurationSec === 'number' && fullDurationSec >= durationSec) {
  5625. const adjustedDurationSec = durationSec - Math.floor(offset / 1000);
  5626. if (adjustedDurationSec < durationSec) { // prevent NaN
  5627. // console.log('adjustedDurationSec', adjustedDurationSec);
  5628. if (adjustedDurationSec > 0) {
  5629. // console.log('offset Sec', Math.floor(offset / 1000));
  5630. itemRenderer.durationSec = adjustedDurationSec;
  5631. } else {
  5632. // if adjustedDurationSec equal 0 or invalid
  5633. continue; // skip adding
  5634. }
  5635. }
  5636.  
  5637. }
  5638.  
  5639. }
  5640.  
  5641. if (fullDurationSec > 0 && durationSec < 1) continue; // fallback check
  5642.  
  5643.  
  5644.  
  5645. }
  5646. arr.push(item)
  5647. // arr.unshift(item);
  5648. }
  5649.  
  5650.  
  5651. // console.log(arr.slice(0))
  5652. this.unshift("items", ...arr);
  5653. } else {
  5654. this.unshift("items", ...eArr);
  5655. }
  5656. }
  5657. }
  5658.  
  5659. for (const entry of stackArr) {
  5660.  
  5661. const { action, data, dateTime, __batchId45__ } = entry;
  5662.  
  5663. const finishLastAction = (
  5664. (prevBatchId !== __batchId45__ && prevBatchId)
  5665. || (dateNow - lastDateTime >= 1000 && dateNow - dateTime < 1000)
  5666. );
  5667.  
  5668. const addPrevItems = addItems.length >= 1 && (finishLastAction || action !== 'addItem');
  5669. lastDateTime = dateTime;
  5670. prevBatchId = __batchId45__;
  5671.  
  5672. // if (dateNow - dateTime >= 1000 && this.shouldAnimateIn) this.shouldAnimateIn = false;
  5673.  
  5674.  
  5675. if (addPrevItems) {
  5676. addItemsFx();
  5677. }
  5678. // if (finishLastAction) {
  5679. // this.updateHighlightedItem();
  5680. // if (!this.shouldAnimateIn) this.shouldAnimateIn = true;
  5681. // }
  5682.  
  5683.  
  5684. if (action === 'addItem') addItems.unshift(data);
  5685. else if (action === 'mcItemD') this.handleMarkChatItemAsDeletedAction(data);
  5686. else if (action === 'removeItemById') this.removeTickerItemById(data);
  5687. else if (action === 'mcItemAD') this.handleMarkChatItemsByAuthorAsDeletedAction(data);
  5688. else if (action === 'removeItemA') this.handleRemoveChatItemByAuthorAction(data);
  5689.  
  5690. }
  5691.  
  5692.  
  5693. // if (previousShouldAnimateIn && !this.shouldAnimateIn) this.shouldAnimateIn = true;
  5694.  
  5695. addItemsFx();
  5696.  
  5697. // if (prevBatchId || dateNow - lastDateTime >= 1000) {
  5698. // this.updateHighlightedItem();
  5699. // if (!this.shouldAnimateIn) this.shouldAnimateIn = true;
  5700. // }
  5701.  
  5702. })
  5703.  
  5704. }
  5705.  
  5706. console.log("AMEND_TICKER_handleLiveChatAction - OK");
  5707. } else {
  5708. console.log("AMEND_TICKER_handleLiveChatAction - NG");
  5709. }
  5710.  
  5711. if (RAF_FIX_keepScrollClamped) {
  5712.  
  5713. // to be improved
  5714.  
  5715. if (typeof cProto.keepScrollClamped === 'function' && !cProto.keepScrollClamped72 && fnIntegrity(cProto.keepScrollClamped) === '0.17.10') {
  5716.  
  5717. cProto.keepScrollClamped72 = cProto.keepScrollClamped;
  5718. cProto.keepScrollClamped = function () {
  5719. this._bound_keepScrollClamped = this._bound_keepScrollClamped || this.keepScrollClamped.bind(this);
  5720. this.scrollClampRaf = requestAnimationFrame(this._bound_keepScrollClamped);
  5721. this.maybeClampScroll()
  5722. }
  5723.  
  5724. console.log('RAF_FIX: keepScrollClamped', tag, "OK")
  5725. } else {
  5726.  
  5727. assertor(() => fnIntegrity(cProto.keepScrollClamped, '0.17.10'));
  5728. console.log('RAF_FIX: keepScrollClamped', tag, "NG")
  5729. }
  5730.  
  5731. }
  5732.  
  5733.  
  5734. if (RAF_FIX_scrollIncrementally && typeof cProto.startScrolling === 'function' && typeof cProto.scrollIncrementally === 'function' && fnIntegrity(cProto.startScrolling) === '1.43.31' && fnIntegrity(cProto.scrollIncrementally) === '1.82.43') {
  5735. // to be replaced by animator
  5736.  
  5737. cProto.startScrolling = function (a) {
  5738. this.scrollStopHandle && this.cancelAsync(this.scrollStopHandle);
  5739. this.asyncHandle && cancelAnimationFrame(this.asyncHandle);
  5740. this.lastFrameTimestamp = this.scrollStartTime = performance.now();
  5741. this.scrollRatePixelsPerSecond = a;
  5742. this._bound_scrollIncrementally = this._bound_scrollIncrementally || this.scrollIncrementally.bind(this);
  5743. this.asyncHandle = requestAnimationFrame(this._bound_scrollIncrementally)
  5744. };
  5745.  
  5746. // related functions: startScrollBack, startScrollingLeft, startScrollingRight, etc.
  5747.  
  5748. cProto.scrollIncrementally = (RAF_FIX_scrollIncrementally === 2) ? function (a) {
  5749. const b = a - (this.lastFrameTimestamp || 0);
  5750. const rate = this.scrollRatePixelsPerSecond
  5751. const q = b / 1E3 * (rate || 0);
  5752.  
  5753. const sl = this.$.items.scrollLeft;
  5754. // console.log(rate, sl, q)
  5755. if (this.lastFrameTimestamp == this.scrollStartTime) {
  5756.  
  5757. } else if (q > -1e-5 && q < 1e-5) {
  5758.  
  5759. } else {
  5760. let cond1 = sl > 0 && rate > 0 && q > 0;
  5761. let cond2 = sl > 0 && rate < 0 && q < 0;
  5762. let cond3 = sl < 1e-5 && sl > -1e-5 && rate > 0 && q > 0;
  5763. if (cond1 || cond2 || cond3) {
  5764. this.$.items.scrollLeft += q;
  5765. this.maybeClampScroll();
  5766. this.updateArrows();
  5767. }
  5768. }
  5769.  
  5770. this.lastFrameTimestamp = a;
  5771. this._bound_scrollIncrementally = this._bound_scrollIncrementally || this.scrollIncrementally.bind(this);
  5772. 0 < this.$.items.scrollLeft || rate && 0 < rate ? this.asyncHandle = requestAnimationFrame(this._bound_scrollIncrementally) : this.stopScrolling()
  5773. } : function (a) {
  5774. const b = a - (this.lastFrameTimestamp || 0);
  5775. this.$.items.scrollLeft += b / 1E3 * (this.scrollRatePixelsPerSecond || 0);
  5776. this.maybeClampScroll();
  5777. this.updateArrows();
  5778. this.lastFrameTimestamp = a;
  5779. this._bound_scrollIncrementally = this._bound_scrollIncrementally || this.scrollIncrementally.bind(this);
  5780. 0 < this.$.items.scrollLeft || this.scrollRatePixelsPerSecond && 0 < this.scrollRatePixelsPerSecond ? this.asyncHandle = requestAnimationFrame(this._bound_scrollIncrementally) : this.stopScrolling()
  5781. };
  5782.  
  5783. console.log(`RAF_FIX: scrollIncrementally${RAF_FIX_scrollIncrementally}`, tag, "OK")
  5784. } else {
  5785. assertor(() => fnIntegrity(cProto.startScrolling, '1.43.31'));
  5786. assertor(() => fnIntegrity(cProto.scrollIncrementally, '1.82.43'));
  5787. console.log('RAF_FIX: scrollIncrementally', tag, "NG")
  5788. }
  5789.  
  5790.  
  5791. if (CLOSE_TICKER_PINNED_MESSAGE_WHEN_HEADER_CLICKED && typeof cProto.attached === 'function' && !cProto.attached37 && typeof cProto.detached === 'function' && !cProto.detached37) {
  5792.  
  5793. cProto.attached37 = cProto.attached;
  5794. cProto.detached37 = cProto.detached;
  5795.  
  5796. let naohzId = 0;
  5797. cProto.__naohzId__ = 0;
  5798. cProto.attached = function () {
  5799. Promise.resolve().then(() => {
  5800.  
  5801. const hostElement = this.hostElement || this;
  5802. if (!(hostElement instanceof HTMLElement)) return;
  5803. if (!HTMLElement.prototype.matches.call(hostElement, '.yt-live-chat-renderer')) return;
  5804. const ironPage = HTMLElement.prototype.closest.call(hostElement, 'iron-pages.yt-live-chat-renderer');
  5805. // or #chat-messages
  5806. if (!ironPage) return;
  5807.  
  5808. if (this.__naohzId__) removeEventListener.call(ironPage, 'click', this.messageBoxClickHandlerForFade, { capture: false, passive: true });
  5809. if (naohzId > 1e9) naohzId = naohzId % 1e4;
  5810. this.__naohzId__ = ++naohzId;
  5811. ironPage.setAttribute('naohz', `${+this.__naohzId__}`);
  5812.  
  5813. addEventListener.call(ironPage, 'click', this.messageBoxClickHandlerForFade, { capture: false, passive: true });
  5814.  
  5815. });
  5816. return this.attached37.apply(this, arguments);
  5817. };
  5818. cProto.detached = function () {
  5819. Promise.resolve().then(() => {
  5820.  
  5821. const ironPage = document.querySelector(`iron-pages[naohz="${+this.__naohzId__}"]`);
  5822. if (!ironPage) return;
  5823.  
  5824. removeEventListener.call(ironPage, 'click', this.messageBoxClickHandlerForFade, { capture: false, passive: true });
  5825.  
  5826. });
  5827. return this.detached37.apply(this, arguments);
  5828. };
  5829.  
  5830. const clickFade = (u) => {
  5831. u.click();
  5832. };
  5833. cProto.messageBoxClickHandlerForFade = async (evt) => {
  5834.  
  5835. const target = (evt || 0).target || 0;
  5836. if (!target) return;
  5837.  
  5838. for (let p = target; p instanceof HTMLElement; p = nodeParent(p)) {
  5839. const is = p.is;
  5840. if (typeof is === 'string' && is) {
  5841.  
  5842. if (is === 'yt-live-chat-pinned-message-renderer') {
  5843. return;
  5844. }
  5845. if (is === 'iron-pages' || is === 'yt-live-chat-renderer' || is === 'yt-live-chat-app') {
  5846. const fade = HTMLElement.prototype.querySelector.call(p, 'yt-live-chat-pinned-message-renderer:not([hidden]) #fade');
  5847. if (fade) {
  5848. Promise.resolve(fade).then(clickFade);
  5849. evt && evt.stopPropagation();
  5850. }
  5851. return;
  5852. }
  5853. if (is !== 'yt-live-chat-ticker-renderer') {
  5854. if (is.startsWith('yt-live-chat-ticker-')) return;
  5855. if (!is.endsWith('-renderer')) return;
  5856. }
  5857.  
  5858. } else {
  5859. if ((p.nodeName || '').includes('BUTTON')) return;
  5860. }
  5861.  
  5862. }
  5863. };
  5864.  
  5865. console.log("CLOSE_TICKER_PINNED_MESSAGE_WHEN_HEADER_CLICKED - OK")
  5866.  
  5867. } else {
  5868. console.log("CLOSE_TICKER_PINNED_MESSAGE_WHEN_HEADER_CLICKED - NG")
  5869. }
  5870.  
  5871.  
  5872. })();
  5873.  
  5874. console.log("[End]");
  5875.  
  5876. console.groupEnd();
  5877.  
  5878. }).catch(console.warn);
  5879.  
  5880.  
  5881. if (ENABLE_RAF_HACK_INPUT_RENDERER && rafHub !== null) {
  5882.  
  5883.  
  5884. customElements.whenDefined("yt-live-chat-message-input-renderer").then(() => {
  5885.  
  5886. mightFirstCheckOnYtInit();
  5887. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-message-input-renderer hacks");
  5888. console.log("[Begin]");
  5889. (() => {
  5890.  
  5891. const tag = "yt-live-chat-message-input-renderer"
  5892. const dummy = document.createElement(tag);
  5893.  
  5894. const cProto = getProto(dummy);
  5895. if (!cProto || !cProto.attached) {
  5896. console.warn(`proto.attached for ${tag} is unavailable.`);
  5897. return;
  5898. }
  5899.  
  5900. let doHack = false;
  5901. if (typeof cProto.handleTimeout === 'function' && typeof cProto.updateTimeout === 'function') {
  5902.  
  5903. // not cancellable
  5904.  
  5905.  
  5906. doHack = fnIntegrity(cProto.handleTimeout, '1.27.16') && fnIntegrity(cProto.updateTimeout, '1.50.33');
  5907.  
  5908. }
  5909.  
  5910. if (doHack) {
  5911.  
  5912. cProto.handleTimeout = function (a) {
  5913. console.log('cProto.handleTimeout', tag)
  5914. if (!this.boundUpdateTimeout38_) this.boundUpdateTimeout38_ = this.updateTimeout.bind(this);
  5915. this.timeoutDurationMs = this.timeoutMs = a;
  5916. this.countdownRatio = 1;
  5917. 0 === this.lastTimeoutTimeMs && rafHub.request(this.boundUpdateTimeout38_)
  5918. };
  5919. cProto.updateTimeout = function (a) {
  5920. console.log('cProto.updateTimeout', tag)
  5921. if (!this.boundUpdateTimeout38_) this.boundUpdateTimeout38_ = this.updateTimeout.bind(this);
  5922. this.lastTimeoutTimeMs && (this.timeoutMs = Math.max(0, this.timeoutMs - (a - this.lastTimeoutTimeMs)),
  5923. this.countdownRatio = this.timeoutMs / this.timeoutDurationMs);
  5924. this.isAttached && this.timeoutMs ? (this.lastTimeoutTimeMs = a,
  5925. rafHub.request(this.boundUpdateTimeout38_)) : this.lastTimeoutTimeMs = 0
  5926. };
  5927.  
  5928. console.log('RAF_HACK_INPUT_RENDERER', tag, "OK")
  5929. } else {
  5930.  
  5931. console.log('typeof handleTimeout', typeof cProto.handleTimeout)
  5932. console.log('typeof updateTimeout', typeof cProto.updateTimeout)
  5933.  
  5934. console.log('RAF_HACK_INPUT_RENDERER', tag, "NG")
  5935. }
  5936.  
  5937. })();
  5938.  
  5939. console.log("[End]");
  5940.  
  5941. console.groupEnd();
  5942.  
  5943.  
  5944. })
  5945.  
  5946.  
  5947. }
  5948.  
  5949. if (ENABLE_RAF_HACK_EMOJI_PICKER && rafHub !== null) {
  5950.  
  5951.  
  5952. customElements.whenDefined("yt-emoji-picker-renderer").then(() => {
  5953.  
  5954. mightFirstCheckOnYtInit();
  5955. groupCollapsed("YouTube Super Fast Chat", " | yt-emoji-picker-renderer hacks");
  5956. console.log("[Begin]");
  5957. (() => {
  5958.  
  5959. const tag = "yt-emoji-picker-renderer"
  5960. const dummy = document.createElement(tag);
  5961.  
  5962. const cProto = getProto(dummy);
  5963. if (!cProto || !cProto.attached) {
  5964. console.warn(`proto.attached for ${tag} is unavailable.`);
  5965. return;
  5966. }
  5967.  
  5968. let doHack = false;
  5969. if (typeof cProto.animateScroll_ === 'function') {
  5970.  
  5971. // not cancellable
  5972. console.log('animateScroll_', typeof cProto.animateScroll_)
  5973.  
  5974. doHack = fnIntegrity(cProto.animateScroll_, '1.102.49')
  5975.  
  5976. }
  5977.  
  5978. if (doHack) {
  5979.  
  5980. const querySelector = HTMLElement.prototype.querySelector;
  5981. const U = (element) => ({
  5982. querySelector: (selector) => querySelector.call(element, selector)
  5983. });
  5984.  
  5985. cProto.animateScroll_ = function (a) {
  5986. // console.log('cProto.animateScroll_', tag) // yt-emoji-picker-renderer
  5987. if (!this.boundAnimateScroll39_) this.boundAnimateScroll39_ = this.animateScroll_.bind(this);
  5988. this.lastAnimationTime_ || (this.lastAnimationTime_ = a);
  5989. a -= this.lastAnimationTime_;
  5990. 200 > a ? (U(this.hostElement).querySelector("#categories").scrollTop = this.animationStart_ + (this.animationEnd_ - this.animationStart_) * a / 200,
  5991. rafHub.request(this.boundAnimateScroll39_)) : (null != this.animationEnd_ && (U(this.hostElement).querySelector("#categories").scrollTop = this.animationEnd_),
  5992. this.animationEnd_ = this.animationStart_ = null,
  5993. this.lastAnimationTime_ = 0);
  5994. this.updateButtons_()
  5995. }
  5996.  
  5997. console.log('ENABLE_RAF_HACK_EMOJI_PICKER', tag, "OK")
  5998. } else {
  5999.  
  6000. console.log('ENABLE_RAF_HACK_EMOJI_PICKER', tag, "NG")
  6001. }
  6002.  
  6003. })();
  6004.  
  6005. console.log("[End]");
  6006.  
  6007. console.groupEnd();
  6008. });
  6009. }
  6010.  
  6011. if (ENABLE_RAF_HACK_DOCKED_MESSAGE && rafHub !== null) {
  6012.  
  6013.  
  6014. customElements.whenDefined("yt-live-chat-docked-message").then(() => {
  6015.  
  6016. mightFirstCheckOnYtInit();
  6017. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-docked-message hacks");
  6018. console.log("[Begin]");
  6019. (() => {
  6020.  
  6021. const tag = "yt-live-chat-docked-message"
  6022. const dummy = document.createElement(tag);
  6023.  
  6024. const cProto = getProto(dummy);
  6025. if (!cProto || !cProto.attached) {
  6026. console.warn(`proto.attached for ${tag} is unavailable.`);
  6027. return;
  6028. }
  6029.  
  6030. let doHack = false;
  6031. if (typeof cProto.detached === 'function' && typeof cProto.checkIntersections === 'function' && typeof cProto.onDockableMessagesChanged === 'function' && typeof cProto.boundCheckIntersections === 'undefined') {
  6032.  
  6033. // cancelable - this.intersectRAF <detached>
  6034. // yt-live-chat-docked-message
  6035. // boundCheckIntersections <-> checkIntersections
  6036. // onDockableMessagesChanged
  6037. // this.intersectRAF = window.requestAnimationFrame(this.boundCheckIntersections);
  6038.  
  6039. console.log('detached', typeof cProto.detached)
  6040. console.log('checkIntersections', typeof cProto.checkIntersections)
  6041. console.log('onDockableMessagesChanged', typeof cProto.onDockableMessagesChanged)
  6042.  
  6043. doHack = fnIntegrity(cProto.detached, '0.32.22') && fnIntegrity(cProto.checkIntersections, '0.128.85') && fnIntegrity(cProto.onDockableMessagesChanged, '0.20.11')
  6044.  
  6045. }
  6046.  
  6047. if (doHack) {
  6048.  
  6049. cProto.checkIntersections = function () {
  6050. // console.log('cProto.checkIntersections', tag)
  6051. if (this.dockableMessages.length) {
  6052. this.intersectRAF = rafHub.request(this.boundCheckIntersections);
  6053. let a = this.dockableMessages[0]
  6054. , b = this.hostElement.getBoundingClientRect();
  6055. a = a.getBoundingClientRect();
  6056. let c = a.top - b.top
  6057. , d = 8 >= c;
  6058. c = 8 >= c - this.hostElement.clientHeight;
  6059. if (d) {
  6060. let e;
  6061. for (; d;) {
  6062. e = this.dockableMessages.shift();
  6063. d = this.dockableMessages[0];
  6064. if (!d)
  6065. break;
  6066. d = d.getBoundingClientRect();
  6067. c = d.top - b.top;
  6068. let f = 8 >= c;
  6069. if (8 >= c - a.height)
  6070. if (f)
  6071. a = d;
  6072. else
  6073. return;
  6074. d = f
  6075. }
  6076. this.dock(e)
  6077. } else
  6078. c && this.dockedItem && this.clear()
  6079. } else
  6080. this.intersectRAF = 0
  6081. }
  6082.  
  6083. cProto.onDockableMessagesChanged = function () {
  6084. // console.log('cProto.onDockableMessagesChanged', tag) // yt-live-chat-docked-message
  6085. this.dockableMessages.length && !this.intersectRAF && (this.intersectRAF = rafHub.request(this.boundCheckIntersections))
  6086. }
  6087.  
  6088. cProto.detached = function () {
  6089. this.intersectRAF && rafHub.cancel(this.intersectRAF)
  6090. }
  6091.  
  6092. console.log('ENABLE_RAF_HACK_DOCKED_MESSAGE', tag, "OK")
  6093. } else {
  6094.  
  6095. console.log('ENABLE_RAF_HACK_DOCKED_MESSAGE', tag, "NG")
  6096. }
  6097.  
  6098. })();
  6099.  
  6100. console.log("[End]");
  6101.  
  6102. console.groupEnd();
  6103.  
  6104. }).catch(console.warn);
  6105.  
  6106. }
  6107.  
  6108. if (FIX_SETSRC_AND_THUMBNAILCHANGE_) {
  6109.  
  6110.  
  6111. customElements.whenDefined("yt-img-shadow").then(() => {
  6112.  
  6113. mightFirstCheckOnYtInit();
  6114. groupCollapsed("YouTube Super Fast Chat", " | yt-img-shadow hacks");
  6115. console.log("[Begin]");
  6116. (() => {
  6117.  
  6118. const tag = "yt-img-shadow"
  6119. const dummy = document.createElement(tag);
  6120.  
  6121. const cProto = getProto(dummy);
  6122. if (!cProto || !cProto.attached) {
  6123. console.warn(`proto.attached for ${tag} is unavailable.`);
  6124. return;
  6125. }
  6126.  
  6127. if (typeof cProto.thumbnailChanged_ === 'function' && !cProto.thumbnailChanged66_) {
  6128.  
  6129. cProto.thumbnailChanged66_ = cProto.thumbnailChanged_;
  6130. cProto.thumbnailChanged_ = function (a) {
  6131.  
  6132. if (this.oldThumbnail_ && this.thumbnail && this.oldThumbnail_.thumbnails === this.thumbnail.thumbnails) return;
  6133. if (!this.oldThumbnail_ && !this.thumbnail) return;
  6134.  
  6135. return this.thumbnailChanged66_.apply(this, arguments)
  6136.  
  6137. }
  6138. console.log("cProto.thumbnailChanged_ - OK");
  6139.  
  6140. } else {
  6141. console.log("cProto.thumbnailChanged_ - NG");
  6142.  
  6143. }
  6144. if (typeof cProto.setSrc_ === 'function' && !cProto.setSrc66_) {
  6145.  
  6146. cProto.setSrc66_ = cProto.setSrc_;
  6147. cProto.setSrc_ = function (a) {
  6148. if ((((this || 0).$ || 0).img || 0).src === a) return;
  6149. return this.setSrc66_.apply(this, arguments)
  6150. }
  6151.  
  6152. console.log("cProto.setSrc_ - OK");
  6153. } else {
  6154.  
  6155. console.log("cProto.setSrc_ - NG");
  6156. }
  6157.  
  6158. })();
  6159.  
  6160. console.log("[End]");
  6161.  
  6162. console.groupEnd();
  6163.  
  6164. }).catch(console.warn);
  6165.  
  6166. }
  6167.  
  6168. if (FIX_THUMBNAIL_DATACHANGED) {
  6169.  
  6170.  
  6171.  
  6172. customElements.whenDefined("yt-live-chat-author-badge-renderer").then(() => {
  6173.  
  6174. mightFirstCheckOnYtInit();
  6175. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-author-badge-renderer hacks");
  6176. console.log("[Begin]");
  6177. (() => {
  6178.  
  6179. const tag = "yt-live-chat-author-badge-renderer"
  6180. const dummy = document.createElement(tag);
  6181.  
  6182. const cProto = getProto(dummy);
  6183. if (!cProto || !cProto.attached) {
  6184. console.warn(`proto.attached for ${tag} is unavailable.`);
  6185. return;
  6186. }
  6187.  
  6188.  
  6189. if (typeof cProto.dataChanged === 'function' && !cProto.dataChanged86 && '|1.160.97|1.159.97|'.includes(`|${fnIntegrity(cProto.dataChanged)}|`)) {
  6190.  
  6191.  
  6192.  
  6193. cProto.dataChanged86 = cProto.dataChanged;
  6194. cProto.dataChanged = function (a) {
  6195.  
  6196. /*
  6197.  
  6198. for (var b = xC(Z(this.hostElement).querySelector("#image")); b.firstChild; )
  6199. b.removeChild(b.firstChild);
  6200. if (a)
  6201. if (a.icon) {
  6202. var c = document.createElement("yt-icon");
  6203. "MODERATOR" === a.icon.iconType && this.enableNewModeratorBadge ? (c.icon = "yt-sys-icons:shield-filled",
  6204. c.defaultToFilled = !0) : c.icon = "live-chat-badges:" + a.icon.iconType.toLowerCase();
  6205. b.appendChild(c)
  6206. } else if (a.customThumbnail) {
  6207. c = document.createElement("img");
  6208. var d;
  6209. (d = (d = KC(a.customThumbnail.thumbnails, 16)) ? lc(oc(d)) : null) ? (c.src = d,
  6210. b.appendChild(c),
  6211. c.setAttribute("alt", this.hostElement.ariaLabel || "")) : lq(new tm("Could not compute URL for thumbnail",a.customThumbnail))
  6212. }
  6213.  
  6214. */
  6215.  
  6216. const image = ((this || 0).$ || 0).image
  6217. if (image && a && image.firstElementChild) {
  6218. let exisiting = image.firstElementChild;
  6219. if (exisiting === image.lastElementChild) {
  6220.  
  6221.  
  6222. if (a.icon && exisiting.nodeName.toUpperCase() === 'YT-ICON') {
  6223.  
  6224. let c = exisiting;
  6225. if ("MODERATOR" === a.icon.iconType && this.enableNewModeratorBadge) {
  6226. if (c.icon !== "yt-sys-icons:shield-filled") c.icon = "yt-sys-icons:shield-filled";
  6227. if (c.defaultToFilled !== true) c.defaultToFilled = true;
  6228. } else {
  6229. let p = "live-chat-badges:" + a.icon.iconType.toLowerCase();;
  6230. if (c.icon !== p) c.icon = p;
  6231. if (c.defaultToFilled !== false) c.defaultToFilled = false;
  6232. }
  6233. return;
  6234.  
  6235.  
  6236. } else if (a.customThumbnail && exisiting.nodeName.toUpperCase() == 'IMG') {
  6237.  
  6238. let c = exisiting;
  6239. if (a.customThumbnail.thumbnails.map(e => e.url).includes(c.src)) {
  6240.  
  6241. c.setAttribute("alt", this.hostElement.ariaLabel || "");
  6242. return;
  6243. }
  6244. /*
  6245.  
  6246. var d;
  6247. (d = (d = KC(a.customThumbnail.thumbnails, 16)) ? lc(oc(d)) : null) ? (c.src = d,
  6248.  
  6249.  
  6250. c.setAttribute("alt", this.hostElement.ariaLabel || "")) : lq(new tm("Could not compute URL for thumbnail", a.customThumbnail))
  6251. */
  6252. }
  6253.  
  6254.  
  6255. }
  6256. }
  6257. return this.dataChanged86.apply(this, arguments)
  6258.  
  6259. }
  6260. console.log("cProto.dataChanged - OK");
  6261.  
  6262. } else {
  6263. assertor(() => fnIntegrity(cProto.dataChanged, '1.160.97'));
  6264. console.log("cProto.dataChanged - NG");
  6265.  
  6266. }
  6267.  
  6268. })();
  6269.  
  6270. console.log("[End]");
  6271.  
  6272. console.groupEnd();
  6273.  
  6274. }).catch(console.warn);
  6275.  
  6276.  
  6277. }
  6278.  
  6279.  
  6280. if (FIX_TOOLTIP_DISPLAY) {
  6281.  
  6282.  
  6283. customElements.whenDefined("tp-yt-paper-tooltip").then(() => {
  6284.  
  6285. mightFirstCheckOnYtInit();
  6286. groupCollapsed("YouTube Super Fast Chat", " | tp-yt-paper-tooltip hacks");
  6287. console.log("[Begin]");
  6288. (() => {
  6289.  
  6290. const tag = "tp-yt-paper-tooltip"
  6291. const dummy = document.createElement(tag);
  6292.  
  6293. const cProto = getProto(dummy);
  6294. if (!cProto || !cProto.attached) {
  6295. console.warn(`proto.attached for ${tag} is unavailable.`);
  6296. return;
  6297. }
  6298.  
  6299. if (typeof cProto.attached === 'function' && typeof cProto.detached === 'function' && cProto._readyClients && cProto._attachDom && cProto.ready && !cProto._readyClients43) {
  6300.  
  6301. cProto._readyClients43 = cProto._readyClients;
  6302. cProto._readyClients = function () {
  6303. let r = cProto._readyClients43.apply(this, arguments);
  6304. if (this.$ && this.$$ && this.$.tooltip) this.root = null; // fix this.root = null != (b = a.root) ? b : this.host
  6305. return r;
  6306. }
  6307.  
  6308. console.log("_readyClients - OK");
  6309.  
  6310. } else {
  6311. console.log("_readyClients - NG");
  6312.  
  6313. }
  6314.  
  6315. if (typeof cProto.show === 'function' && !cProto.show17) {
  6316. cProto.show17 = cProto.show;
  6317. cProto.show = function () {
  6318.  
  6319. let r = this.show17.apply(this, arguments);
  6320. this._showing === true && Promise.resolve().then(() => {
  6321. const tooltip = (this.$ || 0).tooltip;
  6322.  
  6323. if (tooltip && tooltip.firstElementChild === null) {
  6324. let text = tooltip.textContent;
  6325. if (typeof text === 'string' && text.length >= 2) {
  6326. tooltip.textContent = text.trim();
  6327. }
  6328. }
  6329. }).catch(console.warn)
  6330. return r;
  6331. }
  6332.  
  6333. console.log("trim tooltip content - OK");
  6334.  
  6335. } else {
  6336. console.log("trim tooltip content - NG");
  6337.  
  6338. }
  6339.  
  6340. /*
  6341. cProto.updatePosition61 = cProto.updatePosition;
  6342.  
  6343.  
  6344. cProto.updatePosition = function () {
  6345.  
  6346.  
  6347. if (this._target && this.offsetParent) {
  6348. var a = this.offset;
  6349. 14 != this.marginTop && 14 == this.offset && (a = this.marginTop);
  6350. var b = this.offsetParent.getBoundingClientRect()
  6351. , c = this._target.getBoundingClientRect()
  6352. , d = this.getBoundingClientRect()
  6353. , e = (c.width - d.width) / 2
  6354. , h = (c.height - d.height) / 2
  6355. , l = c.left - b.left
  6356. , m = c.top - b.top;
  6357. switch (this.position) {
  6358. case "top":
  6359. var p = l + e;
  6360. var q = m - d.height - a;
  6361. break;
  6362. case "bottom":
  6363. p = l + e;
  6364. q = m + c.height + a;
  6365. break;
  6366. case "left":
  6367. p = l - d.width - a;
  6368. q = m + h;
  6369. break;
  6370. case "right":
  6371. p = l + c.width + a,
  6372. q = m + h;
  6373. }
  6374.  
  6375. if(this.ascee) {
  6376. this.fitToVisibleBounds = false;
  6377. }
  6378. this.fitToVisibleBounds ? (b.left + p + d.width > window.innerWidth ? (this.style.right = "0px",
  6379. this.style.left = "auto") : (this.style.left = Math.max(0, p) + "px",
  6380. this.style.right = "auto"),
  6381. b.top + q + d.height > window.innerHeight ? (this.style.bottom = b.height + "px",
  6382. this.style.top = "auto") : (this.style.top = Math.max(-b.top, q) + "px",
  6383. this.style.bottom = "auto")) : (this.style.left = p + "px",
  6384. this.style.top = q + "px")
  6385. }
  6386. }
  6387.  
  6388. cProto.updateStyles61 = cProto.updateStyles;
  6389. cProto.updateStyles= function(){
  6390. if(this.ascee) return;
  6391. return this.updateStyles61.apply(this,arguments);
  6392. }
  6393. */
  6394.  
  6395.  
  6396. })();
  6397.  
  6398. console.log("[End]");
  6399.  
  6400. console.groupEnd();
  6401.  
  6402. }).catch(console.warn);
  6403.  
  6404.  
  6405.  
  6406. }
  6407.  
  6408.  
  6409.  
  6410. if (FIX_CLICKING_MESSAGE_MENU_DISPLAY_ON_MOUSE_CLICK) {
  6411.  
  6412.  
  6413. const hookDocumentMouseDownSetupFn = () => {
  6414.  
  6415.  
  6416.  
  6417. let muzTimestamp = 0;
  6418. let nszDropdown = null;
  6419.  
  6420.  
  6421.  
  6422. const handlerObject = {
  6423.  
  6424. // mdHandler282 : function (evt) {
  6425. // // console.log(evt, 1, document.querySelector('tp-yt-iron-dropdown[focused].style-scope.yt-live-chat-app'))
  6426. // if (!evt || !evt.isTrusted) return;
  6427. // muzTimestamp = 0;
  6428. // nszDropdown = null;
  6429.  
  6430. // const hostElement = this.hostElement || this;
  6431. // if (!evt || !evt.isTrusted || !hostElement.hasAttribute('menu-visible')) return;
  6432. // if (!hostElement.contains(evt.target)) return;
  6433. // let targetDropDown = null;
  6434. // for(const dropdown of document.querySelectorAll('tp-yt-iron-dropdown.style-scope.yt-live-chat-app')){
  6435. // if(dropdown && dropdown.positionTarget && hostElement.contains( dropdown.positionTarget)){
  6436. // targetDropDown = dropdown;
  6437. // }
  6438. // }
  6439. // if ((nszDropdown = targetDropDown)) {
  6440. // muzTimestamp = Date.now();
  6441. // evt.stopImmediatePropagation();
  6442. // evt.stopPropagation();
  6443. // }
  6444.  
  6445. // },
  6446.  
  6447.  
  6448. muHandler282: function (evt) {
  6449. // console.log(evt, 7, document.querySelector('tp-yt-iron-dropdown[focused].style-scope.yt-live-chat-app'))
  6450. if (!evt || !evt.isTrusted || !muzTimestamp) return;
  6451. const dropdown = nszDropdown;
  6452. muzTimestamp = 0;
  6453. nszDropdown = null;
  6454.  
  6455. const kurMPC = kRef(currentMenuPivotWR) || 0;
  6456. const hostElement = kurMPC.hostElement || kurMPC;
  6457. if (!hostElement.hasAttribute('menu-visible')) return;
  6458.  
  6459. const chatBanner = HTMLElement.prototype.closest.call(hostElement, 'yt-live-chat-banner-renderer') || 0;
  6460. if (chatBanner) return;
  6461.  
  6462. if (dropdown && dropdown.positionTarget && hostElement.contains(dropdown.positionTarget)) {
  6463.  
  6464. /*
  6465. const parentButton = HTMLElement.prototype.closest.call(evt.target, 'button, yt-icon, yt-icon-shape, icon-shape');
  6466. if(parentButton) return;
  6467. */
  6468.  
  6469. muzTimestamp = Date.now();
  6470. evt.stopImmediatePropagation();
  6471. evt.stopPropagation();
  6472. Promise.resolve(dropdown).then((dropdown) => {
  6473. dropdown.cancel();
  6474. });
  6475. // document.body.click();
  6476. }
  6477.  
  6478. },
  6479.  
  6480. mlHandler282: function (evt) {
  6481. muzTimestamp = 0;
  6482. nszDropdown = null;
  6483. },
  6484.  
  6485. ckHandler282: function (evt) {
  6486. // console.log(evt, 3, document.querySelector('tp-yt-iron-dropdown[focused].style-scope.yt-live-chat-app'))
  6487.  
  6488. if (!evt || !evt.isTrusted || !muzTimestamp) return;
  6489. if (Date.now() - muzTimestamp < 40) {
  6490.  
  6491. /*
  6492. const parentButton = HTMLElement.prototype.closest.call(evt.target, 'button, yt-icon, yt-icon-shape, icon-shape');
  6493. if(parentButton) return;
  6494. */
  6495.  
  6496. muzTimestamp = Date.now();
  6497. evt.stopImmediatePropagation();
  6498. evt.stopPropagation();
  6499. }
  6500.  
  6501. },
  6502.  
  6503. tapHandler282: function (evt) {
  6504. // console.log(evt, 2, document.querySelector('tp-yt-iron-dropdown[focused].style-scope.yt-live-chat-app'))
  6505.  
  6506. if (!evt || !evt.isTrusted || !muzTimestamp) return;
  6507. if (Date.now() - muzTimestamp < 40) {
  6508.  
  6509. /*
  6510. const parentButton = HTMLElement.prototype.closest.call(evt.target, 'button, yt-icon, yt-icon-shape, icon-shape');
  6511. if(parentButton) return;
  6512. */
  6513.  
  6514. muzTimestamp = Date.now();
  6515. evt.stopImmediatePropagation();
  6516. evt.stopPropagation();
  6517. }
  6518.  
  6519. },
  6520.  
  6521.  
  6522. handleEvent(evt) {
  6523.  
  6524.  
  6525. if (evt) {
  6526. const kurMPC = kRef(currentMenuPivotWR) || 0;
  6527. const cnt = insp(kurMPC);
  6528. const hostElement = cnt.hostElement || cnt;
  6529. if (!cnt || cnt.isAttached !== true || hostElement.isConnected !== true) return;
  6530. switch (evt.type) {
  6531. // case 'mousedown':
  6532. // return this.mdHandler282.call(kurMPC, evt);
  6533. case 'mouseup':
  6534. return this.muHandler282(evt);
  6535. case 'mouseleave':
  6536. return this.mlHandler282(evt);
  6537. case 'tap':
  6538. return this.tapHandler282(evt);
  6539. case 'click':
  6540. return this.ckHandler282(evt);
  6541. }
  6542. }
  6543.  
  6544. }
  6545.  
  6546.  
  6547.  
  6548. }
  6549.  
  6550. document.addEventListener('mousedown', function (evt) {
  6551.  
  6552. if (!evt || !evt.isTrusted || !evt.target) return;
  6553.  
  6554.  
  6555.  
  6556. muzTimestamp = 0;
  6557. nszDropdown = null;
  6558.  
  6559. /*
  6560. const parentButton = HTMLElement.prototype.closest.call(evt.target, 'button, yt-icon, yt-icon-shape, icon-shape');
  6561. if(parentButton){
  6562. const kurMPC = HTMLElement.prototype.closest.call(parentButton, '[whole-message-clickable]') || 0;
  6563. if(kurMPC){
  6564. evt.preventDefault();
  6565. evt.stopImmediatePropagation();
  6566. evt.stopPropagation();
  6567. }
  6568. return;
  6569. }
  6570. */
  6571.  
  6572. /** @type {HTMLElement | null} */
  6573. const kurMP = kRef(currentMenuPivotWR);
  6574. if (!kurMP) return;
  6575. const kurMPC = HTMLElement.prototype.closest.call(kurMP, '[menu-visible]') || 0;
  6576.  
  6577. if (!kurMPC || !kurMPC.hasAttribute('whole-message-clickable')) return;
  6578.  
  6579. if (!kurMPC.isClickableChatRow111 || !kurMPC.isClickableChatRow111() || !HTMLElement.prototype.contains.call(kurMPC, evt.target)) return;
  6580.  
  6581. const chatBanner = HTMLElement.prototype.closest.call(kurMPC, 'yt-live-chat-banner-renderer') || 0;
  6582. if (chatBanner) return;
  6583.  
  6584.  
  6585. let targetDropDown = null;
  6586. for (const dropdown of document.querySelectorAll('tp-yt-iron-dropdown.style-scope.yt-live-chat-app')) {
  6587. if (dropdown && dropdown.positionTarget === kurMP) {
  6588. targetDropDown = dropdown;
  6589. }
  6590. }
  6591.  
  6592. if (!targetDropDown) return;
  6593.  
  6594.  
  6595. /*
  6596. if (parentButton) {
  6597. evt.preventDefault();
  6598. evt.stopImmediatePropagation();
  6599. evt.stopPropagation();
  6600. currentMenuPivotWR = mWeakRef(kurMPC);
  6601. return;
  6602. }
  6603. */
  6604.  
  6605. if ((nszDropdown = targetDropDown)) {
  6606. muzTimestamp = Date.now();
  6607. evt.stopImmediatePropagation();
  6608. evt.stopPropagation();
  6609. currentMenuPivotWR = mWeakRef(kurMPC);
  6610.  
  6611. const listenOpts = { capture: true, passive: false, once: true };
  6612.  
  6613. // remove unexcecuted eventHandler
  6614. document.removeEventListener('mouseup', handlerObject, listenOpts);
  6615. document.removeEventListener('mouseleave', handlerObject, listenOpts);
  6616. document.removeEventListener('tap', handlerObject, listenOpts);
  6617. document.removeEventListener('click', handlerObject, listenOpts);
  6618.  
  6619. // inject one time eventHandler to by pass events
  6620. document.addEventListener('mouseup', handlerObject, listenOpts);
  6621. document.addEventListener('mouseleave', handlerObject, listenOpts);
  6622. document.addEventListener('tap', handlerObject, listenOpts);
  6623. document.addEventListener('click', handlerObject, listenOpts);
  6624.  
  6625. }
  6626.  
  6627. }, true);
  6628.  
  6629. }
  6630.  
  6631.  
  6632. // yt-live-chat-paid-message-renderer ??
  6633.  
  6634. /*
  6635.  
  6636. [...(new Set([...document.querySelectorAll('*')].filter(e=>e.is&&('shouldSupportWholeItemClick' in e)).map(e=>e.is))).keys()]
  6637.  
  6638.  
  6639. "yt-live-chat-ticker-paid-message-item-renderer"
  6640. "yt-live-chat-ticker-paid-sticker-item-renderer"
  6641. "yt-live-chat-paid-message-renderer"
  6642. "yt-live-chat-text-message-renderer"
  6643. "yt-live-chat-paid-sticker-renderer"
  6644.  
  6645. */
  6646.  
  6647.  
  6648. whenDefinedMultiple([
  6649.  
  6650. "yt-live-chat-paid-message-renderer",
  6651. "yt-live-chat-membership-item-renderer",
  6652. "yt-live-chat-paid-sticker-renderer",
  6653. "yt-live-chat-text-message-renderer",
  6654. "yt-live-chat-auto-mod-message-renderer",
  6655.  
  6656. /*
  6657. "yt-live-chat-ticker-paid-message-item-renderer",
  6658. "yt-live-chat-ticker-paid-sticker-item-renderer",
  6659. "yt-live-chat-paid-message-renderer",
  6660. "yt-live-chat-text-message-renderer",
  6661. "yt-live-chat-paid-sticker-renderer",
  6662.  
  6663. "yt-live-chat-ticker-sponsor-item-renderer",
  6664. "yt-live-chat-banner-header-renderer",
  6665. "ytd-sponsorships-live-chat-gift-purchase-announcement-renderer",
  6666. "ytd-sponsorships-live-chat-header-renderer",
  6667. "ytd-sponsorships-live-chat-gift-redemption-announcement-renderer",
  6668.  
  6669.  
  6670.  
  6671.  
  6672. "yt-live-chat-auto-mod-message-renderer",
  6673. "yt-live-chat-text-message-renderer",
  6674. "yt-live-chat-paid-message-renderer",
  6675.  
  6676. "yt-live-chat-legacy-paid-message-renderer",
  6677. "yt-live-chat-membership-item-renderer",
  6678. "yt-live-chat-paid-sticker-renderer",
  6679. "yt-live-chat-donation-announcement-renderer",
  6680. "yt-live-chat-moderation-message-renderer",
  6681. "ytd-sponsorships-live-chat-gift-purchase-announcement-renderer",
  6682. "ytd-sponsorships-live-chat-gift-redemption-announcement-renderer",
  6683. "yt-live-chat-viewer-engagement-message-renderer",
  6684.  
  6685. */
  6686.  
  6687.  
  6688. ]).then(sTags => {
  6689.  
  6690.  
  6691. mightFirstCheckOnYtInit();
  6692. groupCollapsed("YouTube Super Fast Chat", " | yt-live-chat-message-renderer(s)... hacks");
  6693. console.log("[Begin]");
  6694. let doMouseHook = false;
  6695.  
  6696. const dProto = {
  6697. isClickableChatRow111: function () {
  6698. return (
  6699. this.data && typeof this.shouldSupportWholeItemClick === 'function' && typeof this.hasModerationOverlayVisible === 'function' &&
  6700. this.data.contextMenuEndpoint && this.wholeMessageClickable && this.shouldSupportWholeItemClick() && !this.hasModerationOverlayVisible()
  6701. ); // follow .onItemTap(a)
  6702. }
  6703. };
  6704.  
  6705. for (const sTag of sTags) { // ##tag##
  6706.  
  6707.  
  6708. (() => {
  6709.  
  6710. const tag = sTag;
  6711. const dummy = document.createElement(tag);
  6712.  
  6713. const cProto = getProto(dummy);
  6714. if (!cProto || !cProto.attached) {
  6715. console.warn(`proto.attached for ${tag} is unavailable.`);
  6716. return;
  6717. }
  6718.  
  6719. const dCnt = insp(dummy);
  6720. if ('wholeMessageClickable' in dCnt && typeof dCnt.hasModerationOverlayVisible === 'function' && typeof dCnt.shouldSupportWholeItemClick === 'function') {
  6721.  
  6722. cProto.isClickableChatRow111 = dProto.isClickableChatRow111;
  6723.  
  6724. const toHookDocumentMouseDown = typeof cProto.shouldSupportWholeItemClick === 'function' && typeof cProto.hasModerationOverlayVisible === 'function';
  6725.  
  6726. if (toHookDocumentMouseDown) {
  6727. doMouseHook = true;
  6728. }
  6729.  
  6730. console.log("shouldSupportWholeItemClick Y", tag);
  6731.  
  6732. } else {
  6733.  
  6734. console.log("shouldSupportWholeItemClick N", tag);
  6735. }
  6736.  
  6737.  
  6738. })();
  6739.  
  6740. }
  6741.  
  6742.  
  6743. if (doMouseHook) {
  6744.  
  6745. hookDocumentMouseDownSetupFn();
  6746.  
  6747.  
  6748. console.log("FIX_CLICKING_MESSAGE_MENU_DISPLAY_ON_MOUSE_CLICK - Doc MouseEvent OK");
  6749. }
  6750.  
  6751. console.log("[End]");
  6752.  
  6753. console.groupEnd();
  6754.  
  6755.  
  6756. }).catch(console.warn);
  6757.  
  6758.  
  6759. // https://www.youtube.com/watch?v=oQzFi1NO7io
  6760.  
  6761.  
  6762. }
  6763.  
  6764. if (NO_ITEM_TAP_FOR_NON_STATIONARY_TAP) {
  6765. let targetElementCntWR = null;
  6766. let _e0 = null;
  6767. document.addEventListener('mousedown', (e) => {
  6768. if (!e || !e.isTrusted) return;
  6769. let element = e.target;
  6770. for (; element instanceof HTMLElement; element = element.parentNode) {
  6771. if (element.is) break;
  6772. }
  6773. if (!element || !element.is) return;
  6774. const cnt = insp(element);
  6775. if (typeof cnt.onItemTap === 'function') {
  6776. cnt._onItemTap_isNonStationary = 0;
  6777. const cProto = getProto(element);
  6778. if (!cProto.onItemTap366 && typeof cProto.onItemTap === 'function' && cProto.onItemTap.length === 1) {
  6779. cProto.onItemTap366 = cProto.onItemTap;
  6780. cProto.onItemTap = function (a) {
  6781. const t = this._onItemTap_isNonStationary;
  6782. this._onItemTap_isNonStationary = 0;
  6783. if (t > Date.now()) return;
  6784. return this.onItemTap366.apply(this, arguments)
  6785. }
  6786. }
  6787. _e0 = e;
  6788. targetElementCntWR = mWeakRef(cnt);
  6789. } else {
  6790. _e0 = null;
  6791. targetElementCntWR = null;
  6792. }
  6793. }, { capture: true, passive: true });
  6794.  
  6795. document.addEventListener('mouseup', (e) => {
  6796. if (!e || !e.isTrusted) return;
  6797. const e0 = _e0;
  6798. _e0 = null;
  6799. if (!e0) return;
  6800. const cnt = kRef(targetElementCntWR);
  6801. targetElementCntWR = null;
  6802. if (!cnt) return;
  6803. if (e.timeStamp - e0.timeStamp > TAP_ACTION_DURATION) {
  6804. cnt._onItemTap_isNonStationary = Date.now() + 40;
  6805. } else if ((window.getSelection() + "").trim().replace(/[\u2000-\u200a\u202f\u2800\u200B\u200C\u200D\uFEFF]+/g, '').length >= 1) {
  6806. cnt._onItemTap_isNonStationary = Date.now() + 40;
  6807. } else {
  6808. const dx = e.clientX - e0.clientX;
  6809. const dy = e.clientY - e0.clientY;
  6810. const dd = Math.sqrt(dx * dx + dy * dy);
  6811. const ddmm = px2mm(dd);
  6812. if (ddmm > 1.0) {
  6813. cnt._onItemTap_isNonStationary = Date.now() + 40;
  6814. } else {
  6815. cnt._onItemTap_isNonStationary = 0;
  6816. }
  6817. }
  6818. }, { capture: true, passive: true });
  6819.  
  6820. }
  6821.  
  6822.  
  6823. const __showContextMenu_assign_lock_with_external_unlock_ = function (targetCnt) {
  6824.  
  6825. let rr = null;
  6826. const p1 = new Promise(resolve => {
  6827. rr = resolve;
  6828. });
  6829.  
  6830. const p1unlock = () => {
  6831. const f = rr;
  6832. if (f) {
  6833. rr = null;
  6834. f();
  6835. }
  6836. }
  6837.  
  6838. return {
  6839. p1,
  6840. p1unlock,
  6841. assignLock: (targetCnt, timeout) => {
  6842. targetCnt.__showContextMenu_assign_lock__(p1);
  6843. if (timeout) setTimeout(p1unlock, timeout);
  6844. }
  6845. }
  6846.  
  6847. }
  6848.  
  6849. if (PREREQUEST_CONTEXT_MENU_ON_MOUSE_DOWN) {
  6850.  
  6851. document.addEventListener('mousedown', function (evt) {
  6852.  
  6853. const maxloopDOMTreeElements = 4;
  6854. const maxloopYtCompontents = 4;
  6855. let j1 = 0;
  6856. let j2 = 0;
  6857. let target = (evt || 0).target || 0;
  6858. if (!target) return;
  6859.  
  6860.  
  6861. while (target instanceof HTMLElement) {
  6862. if (++j1 > maxloopDOMTreeElements) break;
  6863. if (typeof (target.is || insp(target).is || null) === 'string') break;
  6864. target = nodeParent(target);
  6865. }
  6866. const components = [];
  6867. while (target instanceof HTMLElement) {
  6868. if (++j2 > maxloopYtCompontents) break;
  6869. const cnt = insp(target);
  6870. if (typeof (target.is || cnt.is || null) === 'string') {
  6871. components.push(target);
  6872. }
  6873. if (typeof cnt.showContextMenu === 'function') break;
  6874. target = target.parentComponent || cnt.parentComponent || null;
  6875. }
  6876. if (!(target instanceof HTMLElement)) return;
  6877. const targetCnt = insp(target);
  6878. if (typeof targetCnt.handleGetContextMenuResponse_ !== 'function' || typeof targetCnt.handleGetContextMenuError !== 'function') {
  6879. console.log('Error Found: handleGetContextMenuResponse_ OR handleGetContextMenuError is not defined on a component with showContextMenu')
  6880. return;
  6881. }
  6882.  
  6883. const endpoint = (targetCnt.data || 0).contextMenuEndpoint
  6884. if (!endpoint) return;
  6885. if (targetCnt.opened || !targetCnt.isAttached) return;
  6886.  
  6887. if (typeof targetCnt.__cacheResolvedEndpointData__ !== 'function') {
  6888. console.log(`preRequest for showContextMenu in ${targetCnt.is} is not yet supported.`)
  6889. }
  6890.  
  6891. const targetDollar = indr(target);
  6892.  
  6893. let doPreRequest = false;
  6894. if (components.length >= 2 && components[0].id === 'menu-button' && (targetDollar || 0)['menu-button'] === components[0]) {
  6895. doPreRequest = true;
  6896. } else if (components.length === 1 && components[0] === target) {
  6897. doPreRequest = true;
  6898. } else if (components.length >= 2 && components[0].id === 'author-photo' && (targetDollar || 0)['author-photo'] === components[0]) {
  6899. doPreRequest = true;
  6900. }
  6901. if (doPreRequest === false) {
  6902. console.log('doPreRequest = fasle on showContextMenu', components);
  6903. return;
  6904. }
  6905.  
  6906. if (typeof targetCnt.__getCachedEndpointData__ !== 'function' || targetCnt.__getCachedEndpointData__(endpoint)) return;
  6907.  
  6908. if ((typeof targetCnt.__showContextMenu_mutex_unlock_isEmpty__ === 'function') && !targetCnt.__showContextMenu_mutex_unlock_isEmpty__()) {
  6909. console.log('preRequest on showContextMenu aborted due to stacked network request');
  6910. return;
  6911. }
  6912.  
  6913.  
  6914. const onSuccess = (a) => {
  6915. /*
  6916.  
  6917. dQ() && (a = a.response);
  6918. a.liveChatItemContextMenuSupportedRenderers && a.liveChatItemContextMenuSupportedRenderers.menuRenderer && this.showContextMenu_(a.liveChatItemContextMenuSupportedRenderers.menuRenderer);
  6919. a.actions && Eu(this.hostElement, "yt-live-chat-actions", [a.actions])
  6920.  
  6921. */
  6922.  
  6923. a = a.response || a;
  6924.  
  6925. if (!a) {
  6926. console.log('unexpected error in prerequest for showContextMenu.onSuccess');
  6927. return;
  6928. }
  6929.  
  6930. let z = null;
  6931. a.liveChatItemContextMenuSupportedRenderers && a.liveChatItemContextMenuSupportedRenderers.menuRenderer && (z = a.liveChatItemContextMenuSupportedRenderers.menuRenderer);
  6932.  
  6933. if (z) {
  6934. a = z;
  6935. targetCnt.__cacheResolvedEndpointData__(endpoint, a, true);
  6936. }
  6937.  
  6938. };
  6939. const onFailure = (a) => {
  6940.  
  6941. /*
  6942.  
  6943. if (a instanceof Error || a instanceof Object || a instanceof String)
  6944. var b = a;
  6945. hq(new xm("Error encountered calling GetLiveChatItemContextMenu",b))
  6946.  
  6947. */
  6948.  
  6949. targetCnt.__cacheResolvedEndpointData__(endpoint, null);
  6950. // console.log('onFailure', a)
  6951.  
  6952. };
  6953.  
  6954. if (doPreRequest) {
  6955.  
  6956. let propertyCounter = 0;
  6957. const pm1 = __showContextMenu_assign_lock_with_external_unlock_(targetCnt);
  6958. const p1Timeout = 800;
  6959. const proxyKey = '__$$__proxy_to_this__$$__' + Date.now();
  6960.  
  6961. try {
  6962.  
  6963. const onSuccessHelperFn = function () {
  6964. pm1.p1unlock();
  6965. if (propertyCounter !== 5) {
  6966. console.log('Error in prerequest for showContextMenu.onSuccessHelperFn')
  6967. return;
  6968. }
  6969. if (this[proxyKey] !== targetCnt) {
  6970. console.log('Error in prerequest for showContextMenu.this');
  6971. return;
  6972. }
  6973. onSuccess(...arguments);
  6974. };
  6975. const onFailureHelperFn = function () {
  6976. pm1.p1unlock();
  6977. if (propertyCounter !== 5) {
  6978. console.log('Error in prerequest for showContextMenu.onFailureHelperFn')
  6979. return;
  6980. }
  6981. if (this[proxyKey] !== targetCnt) {
  6982. console.log('Error in prerequest for showContextMenu.this');
  6983. return;
  6984. }
  6985. onFailure(...arguments);
  6986.  
  6987. }
  6988. const fakeTargetCnt = new Proxy({
  6989. __showContextMenu_forceNativeRequest__: 1,
  6990. __showContextMenu_sync_mode_request__: 1,
  6991. get handleGetContextMenuResponse_() {
  6992. propertyCounter += 2;
  6993. return onSuccessHelperFn;
  6994. },
  6995. get handleGetContextMenuError() {
  6996. propertyCounter += 3;
  6997. return onFailureHelperFn;
  6998. }
  6999. }, {
  7000. get(_, key, receiver) {
  7001. if (key in _) return _[key];
  7002. if (key === proxyKey) return targetCnt;
  7003.  
  7004. let giveNative = false;
  7005. if (key in targetCnt) {
  7006. if (key === 'data') giveNative = true;
  7007. else if (typeof targetCnt[key] === 'function') giveNative = true;
  7008. }
  7009. if (giveNative) return targetCnt[key];
  7010. }
  7011. });
  7012.  
  7013. const fakeEvent = (() => {
  7014. const { target, bubbles, cancelable, cancelBubble, srcElement, timeStamp, defaultPrevented, currentTarget, composed } = evt;
  7015. const nf = function () { }
  7016. const [stopPropagation, stopImmediatePropagation, preventDefault] = [nf, nf, nf];
  7017.  
  7018. return {
  7019. type: 'tap',
  7020. eventPhase: 0,
  7021. isTrusted: false,
  7022. __composed: true,
  7023. bubbles, cancelable, cancelBubble, timeStamp,
  7024. target, srcElement, defaultPrevented, currentTarget, composed,
  7025. stopPropagation, stopImmediatePropagation, preventDefault
  7026. };
  7027. })(evt);
  7028. targetCnt.showContextMenu.call(fakeTargetCnt, fakeEvent);
  7029.  
  7030.  
  7031. } catch (e) {
  7032. console.warn(e);
  7033. propertyCounter = 7;
  7034.  
  7035. }
  7036. if (propertyCounter !== 5) {
  7037. console.log('Error in prerequest for showContextMenu', propertyCounter);
  7038. return;
  7039. }
  7040.  
  7041. pm1.assignLock(targetCnt, p1Timeout);
  7042.  
  7043. }
  7044.  
  7045.  
  7046.  
  7047.  
  7048.  
  7049.  
  7050. }, true);
  7051.  
  7052.  
  7053. }
  7054.  
  7055.  
  7056.  
  7057. /*
  7058.  
  7059. const w=new Set(); for(const a of document.getElementsByTagName('*')) if(a.showContextMenu && a.showContextMenu_) w.add(a.is||''); console.log([...w.keys()])
  7060.  
  7061. */
  7062.  
  7063. whenDefinedMultiple([
  7064. "yt-live-chat-ticker-sponsor-item-renderer",
  7065. "yt-live-chat-banner-header-renderer",
  7066. "yt-live-chat-text-message-renderer",
  7067. "ytd-sponsorships-live-chat-gift-purchase-announcement-renderer",
  7068. "ytd-sponsorships-live-chat-header-renderer",
  7069. "ytd-sponsorships-live-chat-gift-redemption-announcement-renderer",
  7070.  
  7071. "yt-live-chat-paid-sticker-renderer",
  7072. "yt-live-chat-viewer-engagement-message-renderer",
  7073. "yt-live-chat-paid-message-renderer"
  7074.  
  7075.  
  7076.  
  7077.  
  7078. ]).then(sTags => {
  7079.  
  7080. mightFirstCheckOnYtInit();
  7081. groupCollapsed("YouTube Super Fast Chat", " | fixShowContextMenu");
  7082. console.log("[Begin]");
  7083.  
  7084.  
  7085. const __showContextMenu_mutex__ = new Mutex();
  7086. let __showContextMenu_mutex_unlock__ = null;
  7087. let lastShowMenuTarget = null;
  7088.  
  7089.  
  7090.  
  7091.  
  7092. const wm37 = new WeakMap();
  7093.  
  7094. const dProto = {
  7095.  
  7096.  
  7097. // CACHE_SHOW_CONTEXT_MENU_FOR_REOPEN
  7098.  
  7099. __cacheResolvedEndpointData__: (endpoint, a, doDeepCopy) => {
  7100. if (a) {
  7101. if (doDeepCopy) a = deepCopy(a);
  7102. wm37.set(endpoint, a);
  7103. } else {
  7104. wm37.remove(endpoint);
  7105. }
  7106. },
  7107. __getCachedEndpointData__: function (endpoint) {
  7108. endpoint = endpoint || (this.data || 0).contextMenuEndpoint || 0;
  7109. if (endpoint) return wm37.get(endpoint);
  7110. return null;
  7111. },
  7112. /** @type {(resolvedEndpoint: any) => void 0} */
  7113. __showCachedContextMenu__: function (resolvedEndpoint) { // non-null
  7114.  
  7115. resolvedEndpoint = deepCopy(resolvedEndpoint);
  7116. // let b = deepCopy(resolvedEndpoint, ['trackingParams', 'clickTrackingParams'])
  7117. Promise.resolve(resolvedEndpoint).then(() => {
  7118. this.__showContextMenu_skip_cacheResolvedEndpointData__ = 1;
  7119. this.showContextMenu_(resolvedEndpoint);
  7120. this.__showContextMenu_skip_cacheResolvedEndpointData__ = 0;
  7121. });
  7122.  
  7123.  
  7124. },
  7125.  
  7126.  
  7127.  
  7128. showContextMenuForCacheReopen: function (a) {
  7129. if (!this.__showContextMenu_forceNativeRequest__) {
  7130. const endpoint = (this.data || 0).contextMenuEndpoint || 0;
  7131. if (endpoint) {
  7132. const resolvedEndpoint = this.__getCachedEndpointData__(endpoint);
  7133. if (resolvedEndpoint) {
  7134. this.__showCachedContextMenu__(resolvedEndpoint);
  7135. a && a.stopPropagation()
  7136. return;
  7137. }
  7138. }
  7139. }
  7140. return this.showContextMenu37(a);
  7141. },
  7142.  
  7143. showContextMenuForCacheReopen_: function (a) {
  7144. if (!this.__showContextMenu_skip_cacheResolvedEndpointData__) {
  7145. const endpoint = (this.data || 0).contextMenuEndpoint || 0;
  7146. if (endpoint) {
  7147. const f = this.__cacheResolvedEndpointData__;
  7148. if (typeof f === 'function') f(endpoint, a, true);
  7149. }
  7150. }
  7151. return this.showContextMenu37_(a);
  7152. },
  7153.  
  7154. // ADVANCED_NOT_ALLOW_SCROLL_FOR_SHOW_CONTEXT_MENU
  7155.  
  7156. showContextMenuWithDisableScroll: function (a) {
  7157.  
  7158. const endpoint = (this.data || 0).contextMenuEndpoint || 0;
  7159. if (endpoint && typeof this.is === 'string' && this.menuVisible === false && this.menuOpen === false) {
  7160.  
  7161. const parentComponent = this.parentComponent;
  7162. if (parentComponent && parentComponent.is === 'yt-live-chat-item-list-renderer' && parentComponent.contextMenuOpen === false && parentComponent.allowScroll === true) {
  7163. parentComponent.allowScroll = false;
  7164. }
  7165. }
  7166.  
  7167. return this.showContextMenu48.apply(this, arguments);
  7168.  
  7169. },
  7170.  
  7171. // ENABLE_MUTEX_FOR_SHOW_CONTEXT_MENU
  7172.  
  7173. __showContextMenu_mutex_unlock_isEmpty__: () => {
  7174. return __showContextMenu_mutex_unlock__ === null;
  7175. },
  7176.  
  7177. __showContextMenu_assign_lock__: function (p) {
  7178.  
  7179. const mutex = __showContextMenu_mutex__;
  7180.  
  7181. mutex.lockWith(unlock => {
  7182. p.then(unlock);
  7183. });
  7184.  
  7185. },
  7186.  
  7187. showContextMenuWithMutex: function (a) {
  7188. lastShowMenuTarget = this;
  7189.  
  7190. if (this.__showContextMenu_sync_mode_request__) {
  7191.  
  7192. return this.showContextMenu47(a);
  7193. } else {
  7194.  
  7195. const mutex = __showContextMenu_mutex__;
  7196.  
  7197. mutex.lockWith(unlock => {
  7198. if (lastShowMenuTarget !== this) {
  7199. unlock();
  7200. return;
  7201. }
  7202.  
  7203. setTimeout(unlock, 800); // in case network failure
  7204. __showContextMenu_mutex_unlock__ = unlock;
  7205. try {
  7206. this.showContextMenu47(a);
  7207. } catch (e) {
  7208. console.warn(e);
  7209. unlock(); // in case function script error
  7210. }
  7211.  
  7212. });
  7213.  
  7214. }
  7215.  
  7216.  
  7217. },
  7218.  
  7219. showContextMenuWithMutex_: function (a) {
  7220.  
  7221. if (__showContextMenu_mutex_unlock__ && this === lastShowMenuTarget) {
  7222. __showContextMenu_mutex_unlock__();
  7223. __showContextMenu_mutex_unlock__ = null;
  7224. }
  7225. return this.showContextMenu47_(a);
  7226.  
  7227. }
  7228.  
  7229. }
  7230.  
  7231. for (const tag of sTags) { // ##tag##
  7232.  
  7233.  
  7234.  
  7235. (() => {
  7236.  
  7237. const dummy = document.createElement(tag);
  7238.  
  7239. const cProto = getProto(dummy);
  7240. if (!cProto || !cProto.attached) {
  7241. console.warn(`proto.attached for ${tag} is unavailable.`);
  7242. return;
  7243. }
  7244.  
  7245.  
  7246.  
  7247.  
  7248. if (CACHE_SHOW_CONTEXT_MENU_FOR_REOPEN && typeof cProto.showContextMenu === 'function' && typeof cProto.showContextMenu_ === 'function' && !cProto.showContextMenu37 && !cProto.showContextMenu37_ && cProto.showContextMenu.length === 1 && cProto.showContextMenu_.length === 1) {
  7249.  
  7250. cProto.showContextMenu37_ = cProto.showContextMenu_;
  7251. cProto.showContextMenu37 = cProto.showContextMenu;
  7252.  
  7253. cProto.__showContextMenu_forceNativeRequest__ = 0;
  7254. cProto.__cacheResolvedEndpointData__ = dProto.__cacheResolvedEndpointData__
  7255. cProto.__getCachedEndpointData__ = dProto.__getCachedEndpointData__
  7256. cProto.__showCachedContextMenu__ = dProto.__showCachedContextMenu__
  7257.  
  7258. cProto.showContextMenu = dProto.showContextMenuForCacheReopen;
  7259.  
  7260. cProto.showContextMenu_ = dProto.showContextMenuForCacheReopen_;
  7261.  
  7262.  
  7263. console.log("CACHE_SHOW_CONTEXT_MENU_FOR_REOPEN - OK", tag);
  7264.  
  7265.  
  7266.  
  7267. } else {
  7268.  
  7269. console.log("CACHE_SHOW_CONTEXT_MENU_FOR_REOPEN - NG", tag);
  7270.  
  7271. }
  7272.  
  7273.  
  7274.  
  7275. if (ADVANCED_NOT_ALLOW_SCROLL_FOR_SHOW_CONTEXT_MENU && typeof cProto.showContextMenu === 'function' && typeof cProto.showContextMenu_ === 'function' && !cProto.showContextMenu48 && !cProto.showContextMenu48_ && cProto.showContextMenu.length === 1 && cProto.showContextMenu_.length === 1) {
  7276.  
  7277.  
  7278. cProto.showContextMenu48 = cProto.showContextMenu;
  7279.  
  7280.  
  7281. cProto.showContextMenu = dProto.showContextMenuWithDisableScroll;
  7282.  
  7283.  
  7284.  
  7285. console.log("ADVANCED_NOT_ALLOW_SCROLL_FOR_SHOW_CONTEXT_MENU - OK", tag);
  7286.  
  7287.  
  7288.  
  7289. } else {
  7290.  
  7291. console.log("ADVANCED_NOT_ALLOW_SCROLL_FOR_SHOW_CONTEXT_MENU - NG", tag);
  7292.  
  7293. }
  7294.  
  7295.  
  7296.  
  7297.  
  7298.  
  7299. if (ENABLE_MUTEX_FOR_SHOW_CONTEXT_MENU && typeof cProto.showContextMenu === 'function' && typeof cProto.showContextMenu_ === 'function' && !cProto.showContextMenu47 && !cProto.showContextMenu47_ && cProto.showContextMenu.length === 1 && cProto.showContextMenu_.length === 1) {
  7300.  
  7301. cProto.showContextMenu47_ = cProto.showContextMenu_;
  7302. cProto.showContextMenu47 = cProto.showContextMenu;
  7303.  
  7304. cProto.__showContextMenu_mutex_unlock_isEmpty__ = dProto.__showContextMenu_mutex_unlock_isEmpty__;
  7305. cProto.__showContextMenu_assign_lock__ = dProto.__showContextMenu_assign_lock__;
  7306. cProto.showContextMenu = dProto.showContextMenuWithMutex;
  7307. cProto.showContextMenu_ = dProto.showContextMenuWithMutex_;
  7308.  
  7309. console.log("ENABLE_MUTEX_FOR_SHOW_CONTEXT_MENU - OK", tag);
  7310.  
  7311.  
  7312.  
  7313. } else {
  7314.  
  7315. console.log("ENABLE_MUTEX_FOR_SHOW_CONTEXT_MENU - NG", tag);
  7316.  
  7317. }
  7318.  
  7319.  
  7320.  
  7321.  
  7322. })();
  7323.  
  7324. }
  7325.  
  7326.  
  7327.  
  7328. console.log("[End]");
  7329.  
  7330. console.groupEnd();
  7331.  
  7332. }).catch(console.warn);
  7333.  
  7334.  
  7335.  
  7336. customElements.whenDefined('tp-yt-iron-dropdown').then(() => {
  7337.  
  7338. mightFirstCheckOnYtInit();
  7339. groupCollapsed("YouTube Super Fast Chat", " | tp-yt-iron-dropdown hacks");
  7340. console.log("[Begin]");
  7341. (() => {
  7342.  
  7343. const tag = "tp-yt-iron-dropdown";
  7344. const dummy = document.createElement(tag);
  7345.  
  7346. const cProto = getProto(dummy);
  7347. if (!cProto || !cProto.attached) {
  7348. console.warn(`proto.attached for ${tag} is unavailable.`);
  7349. return;
  7350. }
  7351.  
  7352.  
  7353. if (USE_VANILLA_DEREF && typeof cProto.__deraf === 'function' && cProto.__deraf.length === 2 && !cProto.__deraf34 && fnIntegrity(cProto.__deraf) === '2.42.24') {
  7354. cProto.__deraf_hn__ = function (sId, fn) {
  7355. const rhKey = `_rafHandler_${sId}`;
  7356. const m = this[rhKey] || (this[rhKey] = new WeakMap());
  7357. if (m.has(fn)) return m.get(fn);
  7358. const resFn = () => {
  7359. this.__rafs[sId] = null;
  7360. fn.call(this)
  7361. };
  7362. m.set(fn, resFn);
  7363. m.set(resFn, resFn);
  7364. return resFn;
  7365. };
  7366. cProto.__deraf34 = cProto.__deraf;
  7367. cProto.__deraf = function (a, b) { // sId, fn
  7368. let c = this.__rafs;
  7369. null !== c[a] && cancelAnimationFrame(c[a]);
  7370. c[a] = requestAnimationFrame(this.__deraf_hn__(a, b));
  7371. };
  7372. console.log("USE_VANILLA_DEREF - OK");
  7373. } else {
  7374. console.log("USE_VANILLA_DEREF - NG");
  7375. }
  7376.  
  7377. if (FIX_DROPDOWN_DERAF && typeof cProto.__deraf === 'function' && cProto.__deraf.length === 2 && !cProto.__deraf66) {
  7378. cProto.__deraf66 = cProto.__deraf;
  7379. cProto.__deraf = function (sId, fn) {
  7380. if (this.__byPassRAF__) {
  7381. Promise.resolve().then(() => {
  7382. fn.call(this);
  7383. });
  7384. }
  7385. let r = this.__deraf66.apply(this, arguments);
  7386. return r;
  7387. }
  7388. console.log("FIX_DROPDOWN_DERAF - OK");
  7389. } else {
  7390. console.log("FIX_DROPDOWN_DERAF - NG");
  7391. }
  7392.  
  7393.  
  7394. if (BOOST_MENU_OPENCHANGED_RENDERING && typeof cProto.__openedChanged === 'function' && !cProto.__mtChanged__ && fnIntegrity(cProto.__openedChanged) === '0.46.20') {
  7395.  
  7396. let lastClose = null;
  7397. let lastOpen = null;
  7398. let cid = 0;
  7399.  
  7400. cProto.__mtChanged__ = function (b) {
  7401.  
  7402. Promise.resolve().then(() => {
  7403. this._applyFocus();
  7404. }).then(() => {
  7405. b ? this._renderOpened() : this._renderClosed();
  7406. }).catch(console.warn);
  7407.  
  7408. };
  7409.  
  7410. const __moChanged__ = () => {
  7411. if (!cid) return;
  7412. // console.log(553, !!lastOpen, !!lastClose);
  7413. cid = 0;
  7414. if (lastOpen && !lastClose && lastOpen.isAttached) {
  7415. lastOpen.__mtChanged__(1)
  7416. } else if (lastClose && !lastOpen && lastClose.isAttached) {
  7417. lastClose.__mtChanged__(0);
  7418. }
  7419. lastOpen = null;
  7420. lastClose = null;
  7421. };
  7422.  
  7423.  
  7424. if (typeof cProto._openedChanged === 'function' && !cProto._openedChanged66) {
  7425. cProto._openedChanged66 = cProto._openedChanged;
  7426. cProto._openedChanged = function () {
  7427. // this.__byPassRAF__ = !lastOpen ? true : false; // or just true?
  7428. this.__byPassRAF__ = true;
  7429. let r = this._openedChanged66.apply(this, arguments);
  7430. this.__byPassRAF__ = false;
  7431. return r;
  7432. }
  7433. }
  7434.  
  7435. const pSetGet = (key, pdThis, pdBase) => {
  7436. // note: this is not really a standard way for the getOwnPropertyDescriptors; but it is sufficient to make the job done
  7437. return {
  7438. get: (pdThis[key] || 0).get || (pdBase[key] || 0).get,
  7439. set: (pdThis[key] || 0).set || (pdBase[key] || 0).set
  7440. };
  7441. };
  7442.  
  7443. cProto.__modifiedMenuPropsFn__ = function () {
  7444. const pdThis = Object.getOwnPropertyDescriptors(this.constructor.prototype)
  7445. const pdBase = Object.getOwnPropertyDescriptors(this)
  7446.  
  7447. const pdAutoFitOnAttach = pSetGet('autoFitOnAttach', pdThis, pdBase);
  7448. const pdExpandSizingTargetForScrollbars = pSetGet('expandSizingTargetForScrollbars', pdThis, pdBase);
  7449. const pdAllowOutsideScroll = pSetGet('allowOutsideScroll', pdThis, pdBase);
  7450.  
  7451. if (pdAutoFitOnAttach.get || pdAutoFitOnAttach.set) {
  7452. console.warn('there is setter/getter for autoFitOnAttach');
  7453. return;
  7454. }
  7455. if (pdExpandSizingTargetForScrollbars.get || pdExpandSizingTargetForScrollbars.set) {
  7456. console.warn('there is setter/getter for expandSizingTargetForScrollbars');
  7457. return;
  7458. }
  7459. if (!pdAllowOutsideScroll.get || !pdAllowOutsideScroll.set) {
  7460. console.warn('there is NO setter-getter for allowOutsideScroll');
  7461. return;
  7462. }
  7463.  
  7464. let { autoFitOnAttach, expandSizingTargetForScrollbars, allowOutsideScroll } = this;
  7465.  
  7466. this.__AllowOutsideScrollPD__ = pdAllowOutsideScroll;
  7467.  
  7468. const fitEnable = CHAT_MENU_REFIT_ALONG_SCROLLING === 2;
  7469.  
  7470. Object.defineProperties(this, {
  7471. autoFitOnAttach: {
  7472. get() {
  7473. if (fitEnable && this._modifiedMenuPropOn062__) return true;
  7474. return autoFitOnAttach;
  7475. },
  7476. set(nv) {
  7477. autoFitOnAttach = nv;
  7478. return true;
  7479. },
  7480. enumerable: true,
  7481. configurable: true
  7482. }, expandSizingTargetForScrollbars: {
  7483. get() {
  7484. if (fitEnable && this._modifiedMenuPropOn062__) return true;
  7485. return expandSizingTargetForScrollbars;
  7486. },
  7487. set(nv) {
  7488. expandSizingTargetForScrollbars = nv;
  7489. return true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. }, allowOutsideScroll: {
  7494. get() {
  7495. if (this._modifiedMenuPropOn062__) return true;
  7496. return allowOutsideScroll;
  7497. },
  7498. set(nv) {
  7499. allowOutsideScroll = nv;
  7500. this.__AllowOutsideScrollPD__.set.call(this, nv);
  7501. return true;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. }
  7506. })
  7507. };
  7508.  
  7509. /*
  7510. // ***** position() to be changed. *****
  7511. tp-yt-iron-dropdown[class], tp-yt-iron-dropdown[class] #contentWrapper, tp-yt-iron-dropdown[class] ytd-menu-popup-renderer[class] {
  7512.  
  7513. overflow: visible !important;
  7514. min-width: max-content !important;
  7515. max-width: max-content !important;
  7516. max-height: max-content !important;
  7517. min-height: max-content !important;
  7518. white-space: nowrap;
  7519. }
  7520.  
  7521. */
  7522. if (FIX_MENU_POSITION_N_SIZING_ON_SHOWN && typeof cProto.position === 'function' && !cProto.position34 && typeof cProto.refit === 'function') {
  7523.  
  7524. let m34 = 0;
  7525. cProto.__refitByPosition__ = function () {
  7526. m34++;
  7527. if (m34 <= 0) m34 = 0;
  7528. if (m34 !== 1) return;
  7529. const hostElement = this.hostElement || this;
  7530. if (document.visibilityState === 'visible') {
  7531. const sizingTarget = this.sizingTarget;
  7532. if (!sizingTarget) {
  7533. m34 = 0;
  7534. return;
  7535. }
  7536.  
  7537. /*
  7538. let useVisibilityCollapse = true;
  7539. if (HTMLElement.prototype.querySelector.call(sizingTarget, 'yt-icon:empty')) {
  7540. useVisibilityCollapse = false;
  7541. }
  7542.  
  7543. if (useVisibilityCollapse) {
  7544. hostElement.style.visibility = 'collapse';
  7545. sizingTarget.style.visibility = 'collapse';
  7546. } else {
  7547. hostElement.setAttribute('rNgzQ', '');
  7548. sizingTarget.setAttribute('rNgzQ', '');
  7549. }
  7550. */
  7551. hostElement.setAttribute('rNgzQ', '');
  7552. sizingTarget.setAttribute('rNgzQ', '');
  7553.  
  7554. const gn = () => {
  7555. /*
  7556. if (useVisibilityCollapse) {
  7557. hostElement.style.visibility = '';
  7558. sizingTarget.style.visibility = '';
  7559. } else {
  7560. hostElement.removeAttribute('rNgzQ');
  7561. sizingTarget.removeAttribute('rNgzQ');
  7562. }
  7563. */
  7564. hostElement.removeAttribute('rNgzQ');
  7565. sizingTarget.removeAttribute('rNgzQ');
  7566. }
  7567.  
  7568. const an = async () => {
  7569. while (m34 >= 1) {
  7570. await renderReadyPn(sizingTarget);
  7571. if (this.opened && this.isAttached && sizingTarget.isConnected === true && sizingTarget === this.sizingTarget) {
  7572. if (sizingTarget.matches('ytd-menu-popup-renderer[slot="dropdown-content"].yt-live-chat-app')) this.refit();
  7573. }
  7574. m34--;
  7575. }
  7576. m34 = 0;
  7577. Promise.resolve().then(gn);
  7578. }
  7579. setTimeout(an, 4); // wait those resizing function calls
  7580.  
  7581.  
  7582. } else {
  7583. m34 = 0;
  7584. }
  7585. }
  7586. cProto.position34 = cProto.position
  7587. cProto.position = function () {
  7588. if (this._positionInitialize_) {
  7589. this._positionInitialize_ = 0;
  7590. this.__refitByPosition__();
  7591. }
  7592. let r = cProto.position34.apply(this, arguments);
  7593. return r;
  7594. }
  7595. console.log("FIX_MENU_POSITION_ON_SHOWN - OK");
  7596.  
  7597. } else {
  7598.  
  7599. console.log("FIX_MENU_POSITION_ON_SHOWN - NG");
  7600.  
  7601. }
  7602.  
  7603.  
  7604.  
  7605. cProto.__openedChanged = function () {
  7606. this._positionInitialize_ = 1;
  7607. // this.removeAttribute('horizontal-align')
  7608. // this.removeAttribute('vertical-align')
  7609. if (typeof this.__menuTypeCheck__ !== 'boolean') {
  7610. this.__menuTypeCheck__ = true;
  7611. if (CHAT_MENU_SCROLL_UNLOCKING) {
  7612. this._modifiedMenuPropOn062__ = false;
  7613. // console.log(513, this.positionTarget && this.positionTarget.classList.contains('yt-live-chat-text-message-renderer'))
  7614. // this.autoFitOnAttach = true;
  7615. // this.expandSizingTargetForScrollbars = true;
  7616. // this.allowOutsideScroll = true;
  7617. // console.log(519,Object.getOwnPropertyDescriptors(this.constructor.prototype))
  7618. this.__modifiedMenuPropsFn__();
  7619. // this.constrain= function(){}
  7620. // this.position= function(){}
  7621.  
  7622. // this.autoFitOnAttach = true;
  7623. // this.expandSizingTargetForScrollbars = true;
  7624. // this.allowOutsideScroll = true;
  7625. }
  7626. }
  7627. if (CHAT_MENU_SCROLL_UNLOCKING && this.opened) {
  7628. let newValue = null;
  7629. const positionTarget = this.positionTarget;
  7630. if (positionTarget && positionTarget.classList.contains('yt-live-chat-text-message-renderer')) {
  7631. if (this._modifiedMenuPropOn062__ === false) {
  7632. newValue = true;
  7633. }
  7634. } else if (this._modifiedMenuPropOn062__ === true) {
  7635. newValue = false;
  7636. }
  7637. if (newValue !== null) {
  7638. const beforeAllowOutsideScroll = this.allowOutsideScroll;
  7639. this._modifiedMenuPropOn062__ = newValue;
  7640. const afterAllowOutsideScroll = this.allowOutsideScroll;
  7641. if (beforeAllowOutsideScroll !== afterAllowOutsideScroll) this.__AllowOutsideScrollPD__.set.call(this, afterAllowOutsideScroll);
  7642. }
  7643. }
  7644.  
  7645. if (this.opened) {
  7646.  
  7647. Promise.resolve().then(() => {
  7648.  
  7649. this._prepareRenderOpened();
  7650. }).then(() => {
  7651. this._manager.addOverlay(this);
  7652. if (this._manager._overlays.length === 1) {
  7653. lastOpen = this;
  7654. lastClose = null;
  7655. } else {
  7656. return 1;
  7657. }
  7658. // if (cid) {
  7659. // clearTimeout(cid);
  7660. // cid = -1;
  7661. // this.__moChanged__();
  7662. // cid = 0;
  7663. // } else {
  7664. // cid = -1;
  7665. // this.__moChanged__();
  7666. // cid = 0;
  7667. // }
  7668. // cid = cid > 0 ? clearTimeout(cid) : 0;
  7669. // console.log(580, this.positionTarget && this.positionTarget.classList.contains('yt-live-chat-text-message-renderer'))
  7670. // cid = cid || setTimeout(__moChanged__, delay1);
  7671. cid = cid || requestAnimationFrame(__moChanged__);
  7672. }).then((r) => {
  7673.  
  7674. if (r) this.__mtChanged__(1);
  7675. }).catch(console.warn);
  7676.  
  7677. } else {
  7678. Promise.resolve().then(() => {
  7679. this._manager.removeOverlay(this);
  7680. if (this._manager._overlays.length === 0) {
  7681. lastClose = this;
  7682. lastOpen = null;
  7683. } else {
  7684. return 1;
  7685. }
  7686. // cid = cid > 0 ? clearTimeout(cid) : 0;
  7687. // console.log(581, this.positionTarget && this.positionTarget.classList.contains('yt-live-chat-text-message-renderer'))
  7688. // cid = cid || setTimeout(__moChanged__, delay1);
  7689. cid = cid || requestAnimationFrame(__moChanged__);
  7690. }).then((r) => {
  7691. if (r) this.__mtChanged__(0);
  7692. }).catch(console.warn);
  7693.  
  7694. }
  7695.  
  7696. }
  7697. console.log("BOOST_MENU_OPENCHANGED_RENDERING - OK");
  7698.  
  7699. } else {
  7700.  
  7701. assertor(() => fnIntegrity(cProto.__openedChanged, '0.46.20'));
  7702. console.log("FIX_MENU_REOPEN_RENDER_PERFORMANC_1 - NG");
  7703.  
  7704. }
  7705.  
  7706.  
  7707. if (FIX_CLICKING_MESSAGE_MENU_DISPLAY_ON_MOUSE_CLICK && typeof cProto.__openedChanged === 'function' && !cProto.__openedChanged82) {
  7708.  
  7709. cProto.__openedChanged82 = cProto.__openedChanged;
  7710.  
  7711.  
  7712. cProto.__openedChanged = function () {
  7713.  
  7714. // currentMenuPivotWR = null;
  7715. // console.log(1480, '__openedChanged.A', this.positionTarget)
  7716.  
  7717.  
  7718.  
  7719. // if (this.opened && this.positionTarget) {
  7720.  
  7721. // const positionTarget = this.positionTarget;
  7722. // console.log(1480, '__openedChanged.B', positionTarget)
  7723. // currentMenuPivotWR = mWeakRef(positionTarget);
  7724.  
  7725. // }
  7726.  
  7727. const positionTarget = this.positionTarget;
  7728. currentMenuPivotWR = positionTarget ? mWeakRef(positionTarget) : null;
  7729. return this.__openedChanged82.apply(this, arguments);
  7730. }
  7731. }
  7732.  
  7733.  
  7734. // if(FIX_MENU_CAPTURE_SCROLL && typeof cProto.__onCaptureScroll === 'function' && !cProto.__onCaptureScroll66){
  7735.  
  7736. // cProto.__onCaptureScroll66 = cProto.__onCaptureScroll;
  7737.  
  7738. // cProto.__onCaptureScroll = function(a){
  7739.  
  7740. // const q = true;
  7741. // if(this.scrollAction === 'lock' && q && this.opened){
  7742.  
  7743. // // console.log(9107, this.scrollAction, this.__isAnimating, this.opened, a); // lock; __isAnimating = false
  7744. // async function af() {
  7745. // this.__isAnimating && this._finishRenderOpened();
  7746. // if (!this.opened) return;
  7747. // this.__restoreScrollPosition();
  7748. // await new Promise(r => requestAnimationFrame(r));
  7749. // if (!this.opened) return;
  7750. // this.opened && this.__isAnimating && this._finishRenderOpened();
  7751. // if (!this.opened) return;
  7752. // this.__restoreScrollPosition();
  7753. // await new Promise(r => requestAnimationFrame(r));
  7754. // if (!this.opened) return;
  7755. // this.opened && this.__isAnimating && this._finishRenderOpened();
  7756. // if (!this.opened) return;
  7757. // this.opened && !this.__isAnimating && this.refit();
  7758. // }
  7759. // Promise.resolve().then(af);
  7760.  
  7761. // return cProto.__onCaptureScroll66.apply(this, arguments);
  7762. // }else{
  7763.  
  7764. // // console.log(9102, this.scrollAction, this.__isAnimating, this.opened, a); // lock
  7765.  
  7766. // return cProto.__onCaptureScroll66.apply(this, arguments);
  7767. // }
  7768. // }
  7769. // console.log("FIX_MENU_CAPTURE_SCROLL - OK");
  7770. // }else{
  7771. // console.log("FIX_MENU_CAPTURE_SCROLL - NG");
  7772.  
  7773. // }
  7774.  
  7775.  
  7776. })();
  7777.  
  7778. console.log("[End]");
  7779.  
  7780. console.groupEnd();
  7781.  
  7782. }).catch(console.warn);
  7783.  
  7784.  
  7785.  
  7786.  
  7787.  
  7788.  
  7789.  
  7790.  
  7791. /*
  7792.  
  7793.  
  7794.  
  7795.  
  7796.  
  7797. var FU = function() {
  7798. var a = this;
  7799. this.nextHandle_ = 1;
  7800. this.clients_ = {};
  7801. this.JSC$10323_callbacks_ = {};
  7802. this.unsubscribeAsyncHandles_ = {};
  7803. this.subscribe = vl(function(b, c, d) {
  7804. var e = Geb(b);
  7805. if (e in a.clients_)
  7806. e in a.unsubscribeAsyncHandles_ && Jq.cancel(a.unsubscribeAsyncHandles_[e]);
  7807. else {
  7808. a: {
  7809. var h = Geb(b), l;
  7810. for (l in a.unsubscribeAsyncHandles_) {
  7811. var m = a.clients_[l];
  7812. if (m instanceof KO) {
  7813. delete a.clients_[l];
  7814. delete a.JSC$10323_callbacks_[l];
  7815. Jq.cancel(a.unsubscribeAsyncHandles_[l]);
  7816. delete a.unsubscribeAsyncHandles_[l];
  7817. i6a(m);
  7818. m.objectId_ = new FQa(h);
  7819. m.register();
  7820. d = m;
  7821. break a
  7822. }
  7823. }
  7824. d.objectSource = b.invalidationId.objectSource;
  7825. d.objectId = h;
  7826. if (b = b.webAuthConfigurationData)
  7827. b.multiUserSessionIndex && (d.sessionIndex = parseInt(b.multiUserSessionIndex, 10)),
  7828. b.pageId && (d.pageId = b.pageId);
  7829. d = new KO(d,a.handleInvalidationData_.bind(a));
  7830. d.register()
  7831. }
  7832. a.clients_[e] = d;
  7833. a.JSC$10323_callbacks_[e] = {}
  7834. }
  7835. d = a.nextHandle_++;
  7836. a.JSC$10323_callbacks_[e][d] = c;
  7837. return d
  7838. })
  7839. };
  7840. FU.prototype.unsubscribe = function(a, b) {
  7841. var c = Geb(a);
  7842. if (c in this.JSC$10323_callbacks_ && (delete this.JSC$10323_callbacks_[c][b],
  7843. !this.JSC$10323_callbacks_[c].length)) {
  7844. var d = this.clients_[c];
  7845. b = Jq.run(function() {
  7846. ei(d);
  7847. delete this.clients_[c];
  7848. delete this.unsubscribeAsyncHandles_[c]
  7849. }
  7850. .bind(this));
  7851. this.unsubscribeAsyncHandles_[c] = b
  7852. }
  7853. }
  7854. ;
  7855.  
  7856.  
  7857. */
  7858.  
  7859.  
  7860.  
  7861.  
  7862. const onManagerFound = (dummyManager) => {
  7863. if (!dummyManager || typeof dummyManager !== 'object') return;
  7864.  
  7865. const mgrProto = dummyManager.constructor.prototype;
  7866.  
  7867. let keyCallbackStore = '';
  7868. for (const [key, v] of Object.entries(dummyManager)) {
  7869. if (key.includes('_callbacks_')) keyCallbackStore = key;
  7870. }
  7871.  
  7872. if (!keyCallbackStore || typeof mgrProto.unsubscribe !== 'function' || mgrProto.unsubscribe.length !== 2) return;
  7873.  
  7874. if (mgrProto.unsubscribe16) return;
  7875.  
  7876. mgrProto.unsubscribe16 = mgrProto.unsubscribe;
  7877.  
  7878. groupCollapsed("YouTube Super Fast Chat", " | *live-chat-manager* hacks");
  7879. console.log("[Begin]");
  7880.  
  7881.  
  7882. // const isEmptyObject = (a) => Object.keys(a).length === 0;
  7883. const isEmptyObject = ((obj) => (firstKey(obj) === null));
  7884.  
  7885. const idMapper = new Map();
  7886.  
  7887. const convertId = function (objectId) {
  7888. if (!objectId || typeof objectId !== 'string') return null;
  7889.  
  7890. let result = idMapper.get(objectId)
  7891. if (result) return result;
  7892. result = atob(objectId.replace(/-/g, "+").replace(/_/g, "/"));
  7893. idMapper.set(objectId, result)
  7894. return result;
  7895. }
  7896.  
  7897.  
  7898. const rafHandleHolder = [];
  7899.  
  7900. let pzw = 0;
  7901. let lza = 0;
  7902. const rafHandlerFn = () => {
  7903. pzw = 0;
  7904. if (rafHandleHolder.length === 1) {
  7905. const f = rafHandleHolder[0];
  7906. rafHandleHolder.length = 0;
  7907. f();
  7908. } else if (rafHandleHolder.length > 1) {
  7909. const arr = rafHandleHolder.slice(0);
  7910. rafHandleHolder.length = 0;
  7911. for (const fn of arr) fn();
  7912. }
  7913. };
  7914.  
  7915.  
  7916. if (CHANGE_MANAGER_UNSUBSCRIBE) {
  7917.  
  7918. const checkIntegrityForSubscribe = (mgr) => {
  7919. if (mgr
  7920. && typeof mgr.unsubscribe16 === 'function' && mgr.unsubscribe16.length === 2
  7921. && typeof mgr.subscribe18 === 'function' && (mgr.subscribe18.length === 0 || mgr.subscribe18.length === 3)) {
  7922.  
  7923. const ns = new Set(Object.keys(mgr));
  7924. const ms = new Set(Object.keys(mgr.constructor.prototype));
  7925.  
  7926. if (ns.size >= 6 && ms.size >= 4) {
  7927. // including 'subscribe18'
  7928. // 'unsubscribe16', 'subscribe19'
  7929.  
  7930. let r = 0;
  7931. for (const k of ['nextHandle_', 'clients_', keyCallbackStore, 'unsubscribeAsyncHandles_', 'subscribe', 'subscribe18']) {
  7932. r += ns.has(k) ? 1 : 0;
  7933. }
  7934. for (const k of ['unsubscribe', 'handleInvalidationData_', 'unsubscribe16', 'subscribe19']) {
  7935. r += ms.has(k) ? 1 : 0;
  7936. }
  7937. if (r === 10) {
  7938. const isObject = (c) => (c || 0).constructor === Object;
  7939.  
  7940. if (isObject(mgr['clients_']) && isObject(mgr[keyCallbackStore]) && isObject(mgr['unsubscribeAsyncHandles_'])) {
  7941.  
  7942. return true;
  7943. }
  7944.  
  7945.  
  7946. }
  7947.  
  7948. }
  7949.  
  7950.  
  7951. }
  7952. return false;
  7953. }
  7954.  
  7955. mgrProto.subscribe19 = function (o, f, opts) {
  7956.  
  7957. const ct_clients_ = this.clients_ || 0;
  7958. const ct_handles_ = this.unsubscribeAsyncHandles_ || 0;
  7959.  
  7960. if (this.__doCustomSubscribe__ !== true || !ct_clients_ || !ct_handles_) return this.subscribe18.apply(this, arguments);
  7961.  
  7962. let objectId = ((o || 0).invalidationId || 0).objectId;
  7963. if (!objectId) return this.subscribe18.apply(this, arguments);
  7964. objectId = convertId(objectId);
  7965.  
  7966. // console.log('subscribe', objectId, ct_clients_[objectId], arguments);
  7967.  
  7968. if (ct_clients_[objectId]) {
  7969. if (ct_handles_[objectId] < 0) delete ct_handles_[objectId];
  7970. }
  7971.  
  7972. return this.subscribe18.apply(this, arguments);
  7973. }
  7974.  
  7975. mgrProto.unsubscribe = function (o, d) {
  7976. if (!this.subscribe18 && typeof this.subscribe === 'function') {
  7977. this.subscribe18 = this.subscribe;
  7978. this.subscribe = this.subscribe19;
  7979. this.__doCustomSubscribe__ = checkIntegrityForSubscribe(this);
  7980. }
  7981. const ct_clients_ = this.clients_;
  7982. const ct_handles_ = this.unsubscribeAsyncHandles_;
  7983. if (this.__doCustomSubscribe__ !== true || !ct_clients_ || !ct_handles_) return this.unsubscribe16.apply(this, arguments);
  7984.  
  7985. let objectId = ((o || 0).invalidationId || 0).objectId;
  7986. if (!objectId) return this.unsubscribe16.apply(this, arguments);
  7987.  
  7988. objectId = convertId(objectId);
  7989.  
  7990.  
  7991. // console.log('unsubscribe', objectId, ct_clients_[objectId], arguments);
  7992.  
  7993. const callbacks = this[keyCallbackStore] || 0;
  7994. const callbackObj = callbacks[objectId] || 0;
  7995.  
  7996.  
  7997. if (callbackObj && (delete callbackObj[d], isEmptyObject(callbackObj))) {
  7998. const w = ct_clients_[objectId];
  7999. --lza;
  8000. if (lza < -1e9) lza = -1;
  8001. const qta = lza;
  8002. rafHandleHolder.push(() => {
  8003. if (qta === ct_handles_[objectId]) {
  8004. const o = {
  8005. callbacks, callbackObj,
  8006. client: ct_clients_[objectId],
  8007. handle: ct_handles_[objectId]
  8008. };
  8009. let p = 0;
  8010. try {
  8011. if (ct_clients_[objectId] === w) {
  8012. w && "function" === typeof w.dispose && w.dispose();
  8013. delete ct_clients_[objectId];
  8014. delete ct_handles_[objectId];
  8015. p = 1;
  8016. } else {
  8017. // w && "function" === typeof w.dispose && w.dispose();
  8018. // delete ct_clients_[objectId];
  8019. // delete ct_handles_[objectId];
  8020. p = 2;
  8021. }
  8022. } catch (e) {
  8023. console.warn(e);
  8024. }
  8025. console.log(`unsubscribed: ${p}`, this, o);
  8026. }
  8027. });
  8028. ct_handles_[objectId] = qta;
  8029. if (pzw === 0) {
  8030. pzw = requestAnimationFrame(rafHandlerFn);
  8031. }
  8032. }
  8033. }
  8034.  
  8035.  
  8036. console.log("CHANGE_MANAGER_UNSUBSCRIBE - OK")
  8037.  
  8038. } else {
  8039.  
  8040. console.log("CHANGE_MANAGER_UNSUBSCRIBE - NG")
  8041. }
  8042.  
  8043. console.log("[End]");
  8044.  
  8045. console.groupEnd();
  8046.  
  8047. }
  8048.  
  8049.  
  8050.  
  8051. /*
  8052.  
  8053.  
  8054. a.prototype.async = function(e, h) {
  8055. return 0 < h ? Iq.run(e.bind(this), h) : ~Kq.run(e.bind(this))
  8056. }
  8057. ;
  8058. a.prototype.cancelAsync = function(e) {
  8059. 0 > e ? Kq.cancel(~e) : Iq.cancel(e)
  8060. }
  8061.  
  8062. */
  8063.  
  8064.  
  8065. (FASTER_ICON_RENDERING && Promise.all(
  8066. [
  8067. customElements.whenDefined("yt-icon-shape"),
  8068. customElements.whenDefined("yt-icon")
  8069. // document.createElement('icon-shape'),
  8070. ]
  8071. )).then(() => {
  8072. let cq = 0;
  8073. let dummys = [document.createElement('yt-icon-shape'), document.createElement('yt-icon')]
  8074. for (const dummy of dummys) {
  8075. let cProto = getProto(dummy);
  8076. if (cProto && typeof cProto.shouldRenderIconShape === 'function' && !cProto.shouldRenderIconShape571 && cProto.shouldRenderIconShape.length === 1) {
  8077. assertor(() => fnIntegrity(cProto.shouldRenderIconShape, '1.70.38'));
  8078. cq++;
  8079. cProto.shouldRenderIconShape571 = cProto.shouldRenderIconShape;
  8080. cProto.shouldRenderIconShape = function (a) {
  8081. if (this.isAnimatedIcon) return this.shouldRenderIconShape571(a);
  8082. if (!this.iconType || !this.iconShapeData) return this.shouldRenderIconShape571(a);
  8083. if (!this.iconName) return this.shouldRenderIconShape571(a);
  8084. return false;
  8085. // console.log(1051, this.iconType)
  8086. // console.log(1052, this.iconShapeData)
  8087. // console.log(1053, this.isAnimatedIcon)
  8088. }
  8089. }
  8090. // if(cProto && cProto.switchTemplateAtRegistration){
  8091. // cProto.switchTemplateAtRegistration = false;
  8092. // }
  8093. }
  8094. if (cq === 1) {
  8095. console.log("modified shouldRenderIconShape - Y")
  8096. } else {
  8097. console.log("modified shouldRenderIconShape - N", cq)
  8098. }
  8099. });
  8100.  
  8101. customElements.whenDefined("yt-invalidation-continuation").then(() => {
  8102.  
  8103. let __dummyManager__ = null;
  8104.  
  8105. mightFirstCheckOnYtInit();
  8106. groupCollapsed("YouTube Super Fast Chat", " | yt-invalidation-continuation hacks");
  8107. console.log("[Begin]");
  8108. (() => {
  8109.  
  8110. const tag = "yt-invalidation-continuation"
  8111. const dummy = document.createElement(tag);
  8112.  
  8113. const cProto = getProto(dummy);
  8114. if (!cProto || !cProto.attached) {
  8115. console.warn(`proto.attached for ${tag} is unavailable.`);
  8116. return;
  8117. }
  8118.  
  8119. const dummyManager = insp(dummy).manager_ || 0;
  8120. __dummyManager__ = dummyManager;
  8121.  
  8122. if (CHANGE_DATA_FLUSH_ASYNC && typeof cProto.async === 'function' && !cProto.async71 && cProto.async.length === 2 && typeof cProto.cancelAsync === 'function' && !cProto.cancelAsync71 && cProto.cancelAsync.length === 1) {
  8123.  
  8124.  
  8125. const rafHub = new RAFHub();
  8126.  
  8127. rafHub.keepRAF = true;
  8128. cProto.async71 = cProto.async;
  8129. cProto.cancelAsync71 = cProto.cancelAsync;
  8130.  
  8131. // mostly for subscription timeoutMs 10000ms
  8132. let mcw = 1; // 1, 3, 5, ...
  8133. let arr = new Map();
  8134.  
  8135. let __asyncInited__ = 0;
  8136. let __timeoutStartId__ = null;
  8137. const __asyncInit__ = () => {
  8138.  
  8139. if (__asyncInited__) return;
  8140. __asyncInited__ = 1;
  8141.  
  8142. __timeoutStartId__ = setTimeout(() => { });
  8143. mcw = __timeoutStartId__ * 2 + 1;
  8144.  
  8145. setInterval(() => {
  8146.  
  8147. if (!arr.length) return;
  8148.  
  8149. const p = Date.now();
  8150. let deleteKeys = [];
  8151. arr.forEach((entry, key) => {
  8152.  
  8153.  
  8154. if (entry.cid === -1) {
  8155. entry.cid = -2;
  8156. } else if (entry.cid === -2) {
  8157.  
  8158. let offset = p - entry.add
  8159. if (offset < 0) offset = 0;
  8160. let delay2 = entry.delay - offset;
  8161. if (delay2 < 0) delay2 = 0;
  8162. entry.cid = setTimeout(entry.q(), delay2);
  8163. entry.q = null;
  8164.  
  8165. } else if (entry.add + entry.delay < p) {
  8166. deleteKeys.push(key);
  8167.  
  8168. }
  8169.  
  8170. })
  8171.  
  8172. for (const key of deleteKeys) arr.delete(key);
  8173.  
  8174. }, 2000)
  8175.  
  8176. }
  8177.  
  8178.  
  8179.  
  8180.  
  8181. cProto.async = function (e, h) {
  8182.  
  8183. if (!(0 < h)) return this.async71(e, h); // unknown timing Fn
  8184.  
  8185. if (h < 8000) return this.async71(e, h) * 2; // native setTimeout
  8186.  
  8187. if (typeof h !== 'number') return this.async71(e, h); // exceptional case
  8188.  
  8189.  
  8190. if (!this.__asyncInited__) {
  8191. this.__asyncInited__ = 1;
  8192. __asyncInit__();
  8193. }
  8194. mcw += 2; // 2K+3, 2K+4, ...
  8195. if (mcw > 1e9) mcw = mcw % 1e4;
  8196. const cid = mcw;
  8197. const q = () => {
  8198. return () => {
  8199. console.log('async h > 8000');
  8200. e.call(this);
  8201. }
  8202. }
  8203. // setTimeout(q, delay)
  8204. arr.set(cid, {
  8205. cid: -1, // -1 -> -2 -> cid
  8206. add: Date.now(),
  8207. q,
  8208. delay: h
  8209. });
  8210. // console.log('cid-async', cid)
  8211. return cid;
  8212.  
  8213. }
  8214.  
  8215.  
  8216. cProto.cancelAsync = function (e) {
  8217.  
  8218. if (typeof e !== 'number') return this.cancelAsync71(e); // exceptional case
  8219.  
  8220. // console.log('cid-unasync', e)
  8221.  
  8222. if (0 > e) return this.cancelAsync71(e); // unknown timing fn
  8223.  
  8224. if (e > __timeoutStartId__ * 2) { // __timeoutStartId__ is recorded and min is 2K+1
  8225.  
  8226. if ((e % 2) === 0) return this.cancelAsync71(e / 2); // 2(K+1), 2(K+2), ...
  8227.  
  8228. if (!arr.has(e)) return; // duplciated cancel
  8229.  
  8230. const entry = arr.get(e);
  8231. if (entry.cid < 0) {
  8232. entry.cid = 0;
  8233. arr.delete(e);
  8234. } else {
  8235. clearTimeout(entry.cid); // cid >= 1
  8236. entry.cid = 0;
  8237. arr.delete(e);
  8238. }
  8239.  
  8240. } else {
  8241.  
  8242. return this.cancelAsync71(e);
  8243.  
  8244. }
  8245.  
  8246. }
  8247.  
  8248. console.log("CHANGE_DATA_FLUSH_ASYNC - OK");
  8249.  
  8250. } else {
  8251. console.log("CHANGE_DATA_FLUSH_ASYNC - NG");
  8252.  
  8253. }
  8254.  
  8255. })();
  8256.  
  8257. console.log("[End]");
  8258.  
  8259. console.groupEnd();
  8260.  
  8261.  
  8262.  
  8263. onManagerFound(__dummyManager__);
  8264.  
  8265. }).catch(console.warn);
  8266.  
  8267.  
  8268.  
  8269.  
  8270. if (INTERACTIVITY_BACKGROUND_ANIMATION >= 1) {
  8271.  
  8272.  
  8273. customElements.whenDefined("yt-live-interactivity-component-background").then(() => {
  8274.  
  8275.  
  8276. mightFirstCheckOnYtInit();
  8277. groupCollapsed("YouTube Super Fast Chat", " | yt-live-interactivity-component-background hacks");
  8278. console.log("[Begin]");
  8279. (() => {
  8280.  
  8281. const tag = "yt-live-interactivity-component-background"
  8282. const dummy = document.createElement(tag);
  8283.  
  8284. const cProto = getProto(dummy);
  8285. if (!cProto || !cProto.attached) {
  8286. console.warn(`proto.attached for ${tag} is unavailable.`);
  8287. return;
  8288. }
  8289.  
  8290.  
  8291. cProto.__toStopAfterRun__ = function (hostElement) {
  8292. let mo = new MutationObserver(() => {
  8293. mo.disconnect();
  8294. mo.takeRecords();
  8295. mo = null;
  8296. this.lottieAnimation && this.lottieAnimation.stop(); // primary
  8297. foregroundPromiseFn().then(() => { // if the lottieAnimation is started with rAf triggering
  8298. this.lottieAnimation && this.lottieAnimation.stop(); // fallback
  8299. });
  8300. });
  8301. mo.observe(hostElement, { subtree: true, childList: true });
  8302. }
  8303.  
  8304. if (INTERACTIVITY_BACKGROUND_ANIMATION >= 1 && typeof cProto.maybeLoadAnimationBackground === 'function' && !cProto.maybeLoadAnimationBackground77 && cProto.maybeLoadAnimationBackground.length === 0) {
  8305.  
  8306. cProto.maybeLoadAnimationBackground77 = cProto.maybeLoadAnimationBackground;
  8307. cProto.maybeLoadAnimationBackground = function () {
  8308. let toRun = true;
  8309. let stopAfterRun = false;
  8310. if (!this.__bypassDisableAnimationBackground__) {
  8311. let doFix = false;
  8312. if (INTERACTIVITY_BACKGROUND_ANIMATION === 1) {
  8313. if (!this.lottieAnimation) {
  8314. doFix = true;
  8315. }
  8316. } else if (INTERACTIVITY_BACKGROUND_ANIMATION === 2) {
  8317. doFix = true;
  8318. }
  8319. if (doFix) {
  8320. if (this.useAnimationBackground === true) {
  8321. console.log('DISABLE_INTERACTIVITY_BACKGROUND_ANIMATION', this.lottieAnimation);
  8322. }
  8323. toRun = true;
  8324. stopAfterRun = true;
  8325. }
  8326. }
  8327. if (toRun) {
  8328. if (stopAfterRun && (this.hostElement instanceof HTMLElement)) {
  8329. this.__toStopAfterRun__(this.hostElement); // primary
  8330. }
  8331. const r = this.maybeLoadAnimationBackground77.apply(this, arguments);
  8332. if (stopAfterRun && this.lottieAnimation) {
  8333. this.lottieAnimation.stop(); // fallback if no mutation
  8334. }
  8335. return r;
  8336. }
  8337. }
  8338.  
  8339. console.log(`INTERACTIVITY_BACKGROUND_ANIMATION${INTERACTIVITY_BACKGROUND_ANIMATION} - OK`);
  8340.  
  8341. } else {
  8342. console.log(`INTERACTIVITY_BACKGROUND_ANIMATION${INTERACTIVITY_BACKGROUND_ANIMATION} - NG`);
  8343.  
  8344. }
  8345.  
  8346. })();
  8347.  
  8348. console.log("[End]");
  8349.  
  8350. console.groupEnd();
  8351.  
  8352.  
  8353. }).catch(console.warn);
  8354.  
  8355. }
  8356.  
  8357.  
  8358. }
  8359.  
  8360.  
  8361.  
  8362.  
  8363. promiseForCustomYtElementsReady.then(onRegistryReadyForDOMOperations);
  8364.  
  8365. const fixJsonParse = () => {
  8366.  
  8367. let p1 = window.onerror;
  8368.  
  8369. try {
  8370. JSON.parse("{}");
  8371. } catch (e) {
  8372. console.warn(e);
  8373. }
  8374.  
  8375. let p2 = window.onerror;
  8376.  
  8377. if (p1 !== p2) {
  8378.  
  8379.  
  8380. console.groupCollapsed(`%c${"YouTube Super Fast Chat"}%c${" | JS Engine Issue Found"}`,
  8381. "background-color: #010502; color: #fe806a; font-weight: 700; padding: 2px;",
  8382. "background-color: #010502; color: #fe806a; font-weight: 300; padding: 2px;"
  8383. );
  8384.  
  8385. console.warn("\nJSON.parse is hacked (e.g. Brave's script injection) which causes window.onerror changes on every JSON.parse call.\nPlease install https://greasyfork.org/scripts/473972-youtube-js-engine-tamer to fix the issue.\n");
  8386.  
  8387. console.groupEnd();
  8388.  
  8389. }
  8390.  
  8391. }
  8392.  
  8393. if (CHECK_JSONPRUNE) {
  8394. promiseForCustomYtElementsReady.then(fixJsonParse);
  8395. }
  8396.  
  8397. });
  8398.  
  8399.  
  8400.  
  8401. })({ IntersectionObserver });