1
0

SelectorObserver.ts 11 KB

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