siteEvents.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { NanoEmitter, error, getDomain, info } from "./utils/index.js";
  2. import { FeatureConfig } from "./types.js";
  3. import { emitInterface } from "./interface.js";
  4. import { addSelectorListener } from "./observers.js";
  5. export interface SiteEventsMap {
  6. // misc:
  7. /** Emitted whenever the feature config is changed - initialization is not counted */
  8. configChanged: (config: FeatureConfig) => void;
  9. // TODO: implement
  10. /** Emitted whenever a config option is changed - contains the old and new value */
  11. configOptionChanged: <TKey extends keyof FeatureConfig>(key: TKey, oldValue: FeatureConfig[TKey], newValue: FeatureConfig[TKey]) => void;
  12. /** Emitted whenever the config menu should be rebuilt, like when a config was imported */
  13. rebuildCfgMenu: (config: FeatureConfig) => void;
  14. /** Emitted whenever the config menu should be unmounted and recreated in the DOM */
  15. recreateCfgMenu: () => void;
  16. /** Emitted whenever the config menu is closed */
  17. cfgMenuClosed: () => void;
  18. /** Emitted when the welcome menu is closed */
  19. welcomeMenuClosed: () => void;
  20. /** Emitted whenever the user interacts with a hotkey input, used so other keyboard input event listeners don't get called while mid-input */
  21. hotkeyInputActive: (active: boolean) => void;
  22. // DOM:
  23. /** Emitted whenever child nodes are added to or removed from the song queue */
  24. queueChanged: (queueElement: HTMLElement) => void;
  25. /** Emitted whenever child nodes are added to or removed from the autoplay queue underneath the song queue */
  26. autoplayQueueChanged: (queueElement: HTMLElement) => void;
  27. /**
  28. * Emitted whenever the current song title changes.
  29. * Uses the DOM element `yt-formatted-string.title` to detect changes and emit instantaneously.
  30. * If `oldTitle` is `null`, this is the first song played in the session.
  31. */
  32. songTitleChanged: (newTitle: string, oldTitle: string | null) => void;
  33. /**
  34. * Emitted whenever the current song's watch ID changes.
  35. * If `oldId` is `null`, this is the first song played in the session.
  36. */
  37. watchIdChanged: (newId: string, oldId: string | null) => void;
  38. /**
  39. * Emitted whenever the URL path (`location.pathname`) changes.
  40. * If `oldPath` is `null`, this is the first path in the session.
  41. */
  42. pathChanged: (newPath: string, oldPath: string | null) => void;
  43. /** Emitted whenever the player enters or exits fullscreen mode */
  44. fullscreenToggled: (isFullscreen: boolean) => void;
  45. /** Emitted whenever a channel was added, edited or removed from the auto-like list */
  46. autoLikeChannelsUpdated: () => void;
  47. }
  48. /** Array of all site events */
  49. export const allSiteEvents = [
  50. "configChanged",
  51. "configOptionChanged",
  52. "rebuildCfgMenu",
  53. "recreateCfgMenu",
  54. "cfgMenuClosed",
  55. "welcomeMenuClosed",
  56. "hotkeyInputActive",
  57. "queueChanged",
  58. "autoplayQueueChanged",
  59. "songTitleChanged",
  60. "watchIdChanged",
  61. "pathChanged",
  62. "fullscreenToggled",
  63. "autoLikeChannelsUpdated",
  64. ] as const;
  65. /** EventEmitter instance that is used to detect changes to the site */
  66. export const siteEvents = new NanoEmitter<SiteEventsMap>({ publicEmit: true });
  67. let observers: MutationObserver[] = [];
  68. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  69. export function removeAllObservers() {
  70. observers.forEach((observer, i) => {
  71. observer.disconnect();
  72. delete observers[i];
  73. });
  74. observers = [];
  75. }
  76. let lastWatchId: string | null = null;
  77. let lastPathname: string | null = null;
  78. let lastFullscreen: boolean;
  79. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  80. export async function initSiteEvents() {
  81. try {
  82. if(getDomain() === "ytm") {
  83. //#region queue
  84. // the queue container always exists so it doesn't need an extra init function
  85. const queueObs = new MutationObserver(([ { addedNodes, removedNodes, target } ]) => {
  86. if(addedNodes.length > 0 || removedNodes.length > 0) {
  87. info(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  88. emitSiteEvent("queueChanged", target as HTMLElement);
  89. }
  90. });
  91. // only observe added or removed elements
  92. addSelectorListener("sidePanel", "#contents.ytmusic-player-queue", {
  93. listener: (el) => {
  94. queueObs.observe(el, {
  95. childList: true,
  96. });
  97. },
  98. });
  99. const autoplayObs = new MutationObserver(([ { addedNodes, removedNodes, target } ]) => {
  100. if(addedNodes.length > 0 || removedNodes.length > 0) {
  101. info(`Detected autoplay queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  102. emitSiteEvent("autoplayQueueChanged", target as HTMLElement);
  103. }
  104. });
  105. addSelectorListener("sidePanel", "ytmusic-player-queue #automix-contents", {
  106. listener: (el) => {
  107. autoplayObs.observe(el, {
  108. childList: true,
  109. });
  110. },
  111. });
  112. //#region player bar
  113. let lastTitle: string | null = null;
  114. addSelectorListener("playerBarInfo", "yt-formatted-string.title", {
  115. continuous: true,
  116. listener: (titleElem) => {
  117. const oldTitle = lastTitle;
  118. const newTitle = titleElem.textContent;
  119. if(newTitle === lastTitle || !newTitle)
  120. return;
  121. lastTitle = newTitle;
  122. info(`Detected song change - old title: "${oldTitle}" - new title: "${newTitle}"`);
  123. emitSiteEvent("songTitleChanged", newTitle, oldTitle);
  124. },
  125. });
  126. info("Successfully initialized SiteEvents observers");
  127. observers = observers.concat([
  128. queueObs,
  129. autoplayObs,
  130. ]);
  131. //#region player
  132. const playerFullscreenObs = new MutationObserver(([{ target }]) => {
  133. const isFullscreen = (target as HTMLElement).getAttribute("player-ui-state")?.toUpperCase() === "FULLSCREEN";
  134. if(lastFullscreen !== isFullscreen || typeof lastFullscreen === "undefined") {
  135. emitSiteEvent("fullscreenToggled", isFullscreen);
  136. lastFullscreen = isFullscreen;
  137. }
  138. });
  139. addSelectorListener("mainPanel", "ytmusic-player#player", {
  140. listener: (el) => {
  141. playerFullscreenObs.observe(el, {
  142. attributeFilter: ["player-ui-state"],
  143. });
  144. },
  145. });
  146. }
  147. //#region other
  148. const runIntervalChecks = () => {
  149. if(location.pathname.startsWith("/watch")) {
  150. const newWatchId = new URL(location.href).searchParams.get("v");
  151. if(newWatchId && newWatchId !== lastWatchId) {
  152. info(`Detected watch ID change - old ID: "${lastWatchId}" - new ID: "${newWatchId}"`);
  153. emitSiteEvent("watchIdChanged", newWatchId, lastWatchId);
  154. lastWatchId = newWatchId;
  155. }
  156. }
  157. if(location.pathname !== lastPathname) {
  158. emitSiteEvent("pathChanged", String(location.pathname), lastPathname);
  159. lastPathname = String(location.pathname);
  160. }
  161. };
  162. window.addEventListener("bytm:ready", () => {
  163. runIntervalChecks();
  164. setInterval(runIntervalChecks, 100);
  165. }, {
  166. once: true,
  167. });
  168. }
  169. catch(err) {
  170. error("Couldn't initialize SiteEvents observers due to an error:\n", err);
  171. }
  172. }
  173. let bytmReady = false;
  174. window.addEventListener("bytm:ready", () => bytmReady = true, { once: true });
  175. /** Emits a site event with the given key and arguments - if `bytm:ready` has not been emitted yet, all events will be queued until it is */
  176. export function emitSiteEvent<TKey extends keyof SiteEventsMap>(key: TKey, ...args: Parameters<SiteEventsMap[TKey]>) {
  177. if(!bytmReady) {
  178. window.addEventListener("bytm:ready", () => {
  179. bytmReady = true;
  180. emitSiteEvent(key, ...args);
  181. }, { once: true });
  182. return;
  183. }
  184. siteEvents.emit(key, ...args);
  185. emitInterface(`bytm:siteEvent:${key}`, args as unknown as undefined);
  186. }