siteEvents.ts 6.5 KB

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