siteEvents.ts 7.0 KB

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