1
0

SelectorObserver.ts 8.3 KB

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