siteEvents.ts 7.5 KB

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