SelectorObserver.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import { debounce } from "./misc.js";
  2. let domLoaded = false;
  3. document.addEventListener("DOMContentLoaded", () => domLoaded = true);
  4. /** Options for the `onSelector()` method of {@linkcode SelectorObserver} */
  5. export type SelectorListenerOptions<TElem extends Element = HTMLElement> = SelectorOptionsOne<TElem> | SelectorOptionsAll<TElem>;
  6. type SelectorOptionsOne<TElem extends Element> = SelectorOptionsCommon & {
  7. /** Whether to use `querySelectorAll()` instead - default is false */
  8. all?: false;
  9. /** Gets called whenever the selector was found in the DOM */
  10. listener: (element: TElem) => void;
  11. };
  12. type SelectorOptionsAll<TElem extends Element> = SelectorOptionsCommon & {
  13. /** Whether to use `querySelectorAll()` instead - default is false */
  14. all: true;
  15. /** Gets called whenever the selector was found in the DOM */
  16. listener: (elements: NodeListOf<TElem>) => void;
  17. };
  18. type SelectorOptionsCommon = {
  19. /** Whether to call the listener continuously instead of once - default is false */
  20. continuous?: boolean;
  21. /** Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default) */
  22. debounce?: number;
  23. /** Whether to call the function at the very first call ("rising" edge) or the very last call ("falling" edge, default) */
  24. debounceEdge?: "rising" | "falling";
  25. };
  26. export type SelectorObserverOptions = {
  27. /** If set, applies this debounce in milliseconds to all listeners that don't have their own debounce set */
  28. defaultDebounce?: number;
  29. /**
  30. * If set, applies this debounce edge to all listeners that don't have their own set.
  31. * Edge = Whether to call the function at the very first call ("rising" edge) or the very last call ("falling" edge, default)
  32. */
  33. defaultDebounceEdge?: "rising" | "falling";
  34. /** Whether to disable the observer when no listeners are present - default is true */
  35. disableOnNoListeners?: boolean;
  36. /** Whether to ensure the observer is enabled when a new listener is added - default is true */
  37. enableOnAddListener?: boolean;
  38. /** If set to a number, the checks will be run on interval instead of on mutation events - in that case all MutationObserverInit props will be ignored */
  39. checkInterval?: number;
  40. };
  41. export type SelectorObserverConstructorOptions = MutationObserverInit & SelectorObserverOptions;
  42. /** Observes the children of the given element for changes */
  43. export class SelectorObserver {
  44. private enabled = false;
  45. private baseElement: Element | string;
  46. private observer?: MutationObserver;
  47. private observerOptions: MutationObserverInit;
  48. private customOptions: SelectorObserverOptions;
  49. private listenerMap: Map<string, SelectorListenerOptions[]>;
  50. /**
  51. * Creates a new SelectorObserver that will observe the children of the given base element selector for changes (only creation and deletion of elements by default)
  52. * @param baseElementSelector The selector of the element to observe
  53. * @param options Fine-tune what triggers the MutationObserver's checking function - `subtree` and `childList` are set to true by default
  54. */
  55. constructor(baseElementSelector: string, options?: SelectorObserverConstructorOptions)
  56. /**
  57. * Creates a new SelectorObserver that will observe the children of the given base element for changes (only creation and deletion of elements by default)
  58. * @param baseElement The element to observe
  59. * @param options Fine-tune what triggers the MutationObserver's checking function - `subtree` and `childList` are set to true by default
  60. */
  61. constructor(baseElement: Element, options?: SelectorObserverConstructorOptions)
  62. constructor(baseElement: Element | string, options: SelectorObserverConstructorOptions = {}) {
  63. this.baseElement = baseElement;
  64. this.listenerMap = new Map<string, SelectorListenerOptions[]>();
  65. const {
  66. defaultDebounce,
  67. defaultDebounceEdge,
  68. disableOnNoListeners,
  69. enableOnAddListener,
  70. ...observerOptions
  71. } = options;
  72. this.observerOptions = {
  73. childList: true,
  74. subtree: true,
  75. ...observerOptions,
  76. };
  77. this.customOptions = {
  78. defaultDebounce: defaultDebounce ?? 0,
  79. defaultDebounceEdge: defaultDebounceEdge ?? "rising",
  80. disableOnNoListeners: disableOnNoListeners ?? false,
  81. enableOnAddListener: enableOnAddListener ?? true,
  82. };
  83. if(typeof this.customOptions.checkInterval !== "number") {
  84. // if the arrow func isn't there, `this` will be undefined in the callback
  85. this.observer = new MutationObserver(() => this.checkAllSelectors());
  86. }
  87. else {
  88. this.checkAllSelectors();
  89. setInterval(() => this.checkAllSelectors(), this.customOptions.checkInterval);
  90. }
  91. }
  92. private checkAllSelectors(): void {
  93. if(!this.enabled || !domLoaded)
  94. return;
  95. for(const [selector, listeners] of this.listenerMap.entries())
  96. this.checkSelector(selector, listeners);
  97. }
  98. private checkSelector(selector: string, listeners: SelectorListenerOptions[]): void {
  99. if(!this.enabled)
  100. return;
  101. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  102. if(!baseElement)
  103. return;
  104. const all = listeners.some(listener => listener.all);
  105. const one = listeners.some(listener => !listener.all);
  106. const allElements = all ? baseElement.querySelectorAll<HTMLElement>(selector) : null;
  107. const oneElement = one ? baseElement.querySelector<HTMLElement>(selector) : null;
  108. for(const options of listeners) {
  109. if(options.all) {
  110. if(allElements && allElements.length > 0) {
  111. options.listener(allElements);
  112. if(!options.continuous)
  113. this.removeListener(selector, options);
  114. }
  115. }
  116. else {
  117. if(oneElement) {
  118. options.listener(oneElement);
  119. if(!options.continuous)
  120. this.removeListener(selector, options);
  121. }
  122. }
  123. if(this.listenerMap.get(selector)?.length === 0)
  124. this.listenerMap.delete(selector);
  125. if(this.listenerMap.size === 0 && this.customOptions.disableOnNoListeners)
  126. this.disable();
  127. }
  128. }
  129. private debounce<TArgs>(func: (...args: TArgs[]) => void, time: number, edge: "falling" | "rising" = "falling"): (...args: TArgs[]) => void {
  130. return debounce(func, time, edge);
  131. }
  132. /**
  133. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  134. * @param selector The selector to observe
  135. * @param options Options for the selector observation
  136. * @param options.listener Gets called whenever the selector was found in the DOM
  137. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  138. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  139. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  140. */
  141. public addListener<TElem extends Element = HTMLElement>(selector: string, options: SelectorListenerOptions<TElem>): void {
  142. options = { all: false, continuous: false, debounce: 0, ...options };
  143. if((options.debounce && options.debounce > 0) || (this.customOptions.defaultDebounce && this.customOptions.defaultDebounce > 0)) {
  144. options.listener = this.debounce(
  145. options.listener as ((arg: NodeListOf<Element> | Element) => void),
  146. (options.debounce || this.customOptions.defaultDebounce)!,
  147. (options.debounceEdge || this.customOptions.defaultDebounceEdge),
  148. );
  149. }
  150. if(this.listenerMap.has(selector))
  151. this.listenerMap.get(selector)!.push(options as SelectorListenerOptions<Element>);
  152. else
  153. this.listenerMap.set(selector, [options as SelectorListenerOptions<Element>]);
  154. if(this.enabled === false && this.customOptions.enableOnAddListener)
  155. this.enable();
  156. this.checkSelector(selector, [options as SelectorListenerOptions<Element>]);
  157. }
  158. /** Disables the observation of the child elements */
  159. public disable(): void {
  160. if(!this.enabled)
  161. return;
  162. this.enabled = false;
  163. this.observer?.disconnect();
  164. }
  165. /**
  166. * Enables or reenables the observation of the child elements.
  167. * @param immediatelyCheckSelectors Whether to immediately check if all previously registered selectors exist (default is true)
  168. * @returns Returns true when the observation was enabled, false otherwise (e.g. when the base element wasn't found)
  169. */
  170. public enable(immediatelyCheckSelectors = true): boolean {
  171. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  172. if(this.enabled || !baseElement)
  173. return false;
  174. this.enabled = true;
  175. this.observer?.observe(baseElement, this.observerOptions);
  176. if(immediatelyCheckSelectors)
  177. this.checkAllSelectors();
  178. return true;
  179. }
  180. /** Returns whether the observation of the child elements is currently enabled */
  181. public isEnabled(): boolean {
  182. return this.enabled;
  183. }
  184. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  185. public clearListeners(): void {
  186. this.listenerMap.clear();
  187. }
  188. /**
  189. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  190. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  191. */
  192. public removeAllListeners(selector: string): boolean {
  193. return this.listenerMap.delete(selector);
  194. }
  195. /**
  196. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  197. * @returns Returns true when the listener was found and removed, false otherwise
  198. */
  199. public removeListener(selector: string, options: SelectorListenerOptions): boolean {
  200. const listeners = this.listenerMap.get(selector);
  201. if(!listeners)
  202. return false;
  203. const index = listeners.indexOf(options);
  204. if(index > -1) {
  205. listeners.splice(index, 1);
  206. return true;
  207. }
  208. return false;
  209. }
  210. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  211. public getAllListeners(): Map<string, SelectorListenerOptions<HTMLElement>[]> {
  212. return this.listenerMap;
  213. }
  214. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  215. public getListeners(selector: string): SelectorListenerOptions<HTMLElement>[] | undefined {
  216. return this.listenerMap.get(selector);
  217. }
  218. }