siteEvents.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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, globserversReady } from "./observers.js";
  5. export interface SiteEventsMap {
  6. //#region misc:
  7. /** Emitted whenever the feature config is changed - initialization is not counted */
  8. configChanged: (newConfig: FeatureConfig) => void;
  9. /** Emitted whenever a config option is changed - contains the old and new value */
  10. configOptionChanged: <TFeatKey extends keyof FeatureConfig>(key: TFeatKey, oldValue: FeatureConfig[TFeatKey], newValue: FeatureConfig[TFeatKey]) => void;
  11. /** Emitted whenever the config menu should be rebuilt, like when a config was imported */
  12. rebuildCfgMenu: (newConfig: FeatureConfig) => void;
  13. /** Emitted whenever the config menu should be unmounted and recreated in the DOM */
  14. recreateCfgMenu: () => 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. //#region 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. * Uses the DOM element `yt-formatted-string.title` to detect changes and emit instantaneously.
  29. * If `oldTitle` is `null`, this is the first song played in the session.
  30. */
  31. songTitleChanged: (newTitle: string, oldTitle: string | null) => void;
  32. /**
  33. * Emitted whenever the current song's watch ID changes.
  34. * If `oldId` is `null`, this is the first song played in the session.
  35. */
  36. watchIdChanged: (newId: string, oldId: string | null) => void;
  37. /**
  38. * Emitted whenever the URL path (`location.pathname`) changes.
  39. * If `oldPath` is `null`, this is the first path in the session.
  40. */
  41. pathChanged: (newPath: string, oldPath: string | null) => void;
  42. /** Emitted whenever the player enters or exits fullscreen mode */
  43. fullscreenToggled: (isFullscreen: boolean) => void;
  44. //#region features:
  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 various changes to the site and userscript */
  66. export const siteEvents = new NanoEmitter<SiteEventsMap>({
  67. publicEmit: true,
  68. });
  69. let observers: MutationObserver[] = [];
  70. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  71. export function removeAllObservers() {
  72. observers.forEach((ob) => ob.disconnect());
  73. observers = [];
  74. }
  75. let lastWatchId: string | null = null;
  76. let lastPathname: string | null = null;
  77. let lastFullscreen: boolean;
  78. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  79. export async function initSiteEvents() {
  80. try {
  81. if(getDomain() === "ytm") {
  82. //#region queue
  83. // the queue container always exists so it doesn't need an extra init function
  84. const queueObs = new MutationObserver(([ { addedNodes, removedNodes, target } ]) => {
  85. if(addedNodes.length > 0 || removedNodes.length > 0) {
  86. info(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  87. emitSiteEvent("queueChanged", target as HTMLElement);
  88. }
  89. });
  90. // only observe added or removed elements
  91. addSelectorListener("sidePanel", "#contents.ytmusic-player-queue", {
  92. listener: (el) => {
  93. queueObs.observe(el, {
  94. childList: true,
  95. });
  96. },
  97. });
  98. const autoplayObs = new MutationObserver(([ { addedNodes, removedNodes, target } ]) => {
  99. if(addedNodes.length > 0 || removedNodes.length > 0) {
  100. info(`Detected autoplay queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  101. emitSiteEvent("autoplayQueueChanged", target as HTMLElement);
  102. }
  103. });
  104. addSelectorListener("sidePanel", "ytmusic-player-queue #automix-contents", {
  105. listener: (el) => {
  106. autoplayObs.observe(el, {
  107. childList: true,
  108. });
  109. },
  110. });
  111. //#region player bar
  112. let lastTitle: string | null = null;
  113. addSelectorListener("playerBarInfo", "yt-formatted-string.title", {
  114. continuous: true,
  115. listener: (titleElem) => {
  116. const oldTitle = lastTitle;
  117. const newTitle = titleElem.textContent;
  118. if(newTitle === lastTitle || !newTitle)
  119. return;
  120. lastTitle = newTitle;
  121. info(`Detected song change - old title: "${oldTitle}" - new title: "${newTitle}"`);
  122. emitSiteEvent("songTitleChanged", newTitle, oldTitle);
  123. runIntervalChecks();
  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. if(getDomain() === "ytm") {
  140. const registerFullScreenObs = () => addSelectorListener("mainPanel", "ytmusic-player#player", {
  141. listener: (el) => {
  142. playerFullscreenObs.observe(el, {
  143. attributeFilter: ["player-ui-state"],
  144. });
  145. },
  146. });
  147. if(globserversReady)
  148. registerFullScreenObs();
  149. else
  150. window.addEventListener("bytm:observersReady", registerFullScreenObs, { once: true });
  151. }
  152. }
  153. window.addEventListener("bytm:ready", () => {
  154. runIntervalChecks();
  155. setInterval(runIntervalChecks, 100);
  156. if(getDomain() === "ytm") {
  157. addSelectorListener<HTMLAnchorElement>("mainPanel", "ytmusic-player #song-video #movie_player .ytp-title-text > a", {
  158. listener(el) {
  159. const urlRefObs = new MutationObserver(([ { target } ]) => {
  160. if(!target || !(target as HTMLAnchorElement)?.href?.includes("/watch"))
  161. return;
  162. const watchId = new URL((target as HTMLAnchorElement).href).searchParams.get("v");
  163. checkWatchIdChange(watchId);
  164. });
  165. urlRefObs.observe(el, {
  166. attributeFilter: ["href"],
  167. });
  168. }
  169. });
  170. }
  171. if(getDomain() === "ytm") {
  172. setInterval(checkWatchIdChange, 250);
  173. checkWatchIdChange();
  174. }
  175. }, {
  176. once: true,
  177. });
  178. }
  179. catch(err) {
  180. error("Couldn't initialize site event observers due to an error:\n", err);
  181. }
  182. }
  183. let bytmReady = false;
  184. window.addEventListener("bytm:ready", () => bytmReady = true, { once: true });
  185. /** 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 */
  186. export function emitSiteEvent<TKey extends keyof SiteEventsMap>(key: TKey, ...args: Parameters<SiteEventsMap[TKey]>) {
  187. try {
  188. if(!bytmReady) {
  189. window.addEventListener("bytm:ready", () => {
  190. bytmReady = true;
  191. emitSiteEvent(key, ...args);
  192. }, { once: true });
  193. return;
  194. }
  195. siteEvents.emit(key, ...args);
  196. emitInterface(`bytm:siteEvent:${key}`, args as unknown as undefined);
  197. }
  198. catch(err) {
  199. error(`Couldn't emit site event "${key}" due to an error:\n`, err);
  200. }
  201. }
  202. //#region other
  203. /** Checks if the watch ID has changed and emits a `watchIdChanged` siteEvent if it has */
  204. function checkWatchIdChange(newId?: string | null) {
  205. const newWatchId = newId ?? new URL(location.href).searchParams.get("v");
  206. if(newWatchId && newWatchId !== lastWatchId) {
  207. lastWatchId = newWatchId;
  208. info(`Detected watch ID change - old ID: "${lastWatchId}" - new ID: "${newWatchId}"`);
  209. emitSiteEvent("watchIdChanged", newWatchId, lastWatchId);
  210. }
  211. }
  212. /** Periodically called to check for changes in the URL and emit associated siteEvents */
  213. export function runIntervalChecks() {
  214. if(!lastWatchId)
  215. checkWatchIdChange();
  216. if(location.pathname !== lastPathname) {
  217. emitSiteEvent("pathChanged", String(location.pathname), lastPathname);
  218. lastPathname = String(location.pathname);
  219. }
  220. };