SelectorObserver.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. /** Observes the children of the given element for changes */
  22. export class SelectorObserver {
  23. private enabled = true;
  24. private baseElement: Element;
  25. private observer: MutationObserver;
  26. private observerOptions: MutationObserverInit;
  27. private listenerMap = new Map<string, SelectorListenerOptions[]>();
  28. /**
  29. * Creates a new SelectorObserver that will observe the children of the given base element for changes (only creation and deletion of elements by default)
  30. * @param options Fine-tune what triggers the MutationObserver's checking function - `subtree` and `childList` are set to true by default
  31. */
  32. constructor(baseElement: Element, observerOptions?: MutationObserverInit) {
  33. this.baseElement = baseElement;
  34. this.observer = new MutationObserver(this.checkSelectors);
  35. this.observerOptions = {
  36. childList: true,
  37. subtree: true,
  38. ...observerOptions,
  39. };
  40. this.enable();
  41. }
  42. private checkSelectors() {
  43. for(const [selector, listeners] of this.listenerMap.entries()) {
  44. if(!this.enabled)
  45. return;
  46. const all = listeners.some(listener => listener.all);
  47. const one = listeners.some(listener => !listener.all);
  48. const allElements = all ? this.baseElement.querySelectorAll<HTMLElement>(selector) : null;
  49. const oneElement = one ? this.baseElement.querySelector<HTMLElement>(selector) : null;
  50. for(const options of listeners) {
  51. if(!this.enabled)
  52. return;
  53. if(options.all) {
  54. if(allElements && allElements.length > 0) {
  55. options.listener(allElements);
  56. if(!options.continuous)
  57. this.listenerMap.get(selector)!.splice(this.listenerMap.get(selector)!.indexOf(options), 1);
  58. }
  59. } else {
  60. if(oneElement) {
  61. options.listener(oneElement);
  62. if(!options.continuous)
  63. this.listenerMap.get(selector)!.splice(this.listenerMap.get(selector)!.indexOf(options), 1);
  64. }
  65. }
  66. if(this.listenerMap.get(selector)?.length === 0)
  67. this.listenerMap.delete(selector);
  68. }
  69. }
  70. }
  71. private debounce<TArgs>(func: (...args: TArgs[]) => void, time: number): (...args: TArgs[]) => void {
  72. let timeout: number;
  73. return function(...args: TArgs[]) {
  74. clearTimeout(timeout);
  75. timeout = setTimeout(() => func.apply(this, args), time) as unknown as number;
  76. };
  77. }
  78. /**
  79. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  80. * @param selector The selector to observe
  81. * @param options Options for the selector observation
  82. * @param options.listener Gets called whenever the selector was found in the DOM
  83. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  84. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  85. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  86. */
  87. public addListener<TElem extends Element = HTMLElement>(selector: string, options: SelectorListenerOptions<TElem>) {
  88. options = { all: false, continuous: false, debounce: 0, ...options };
  89. if(options.debounce && options.debounce > 0)
  90. options.listener = this.debounce(options.listener as ((arg: NodeListOf<Element> | Element) => void), options.debounce);
  91. if(this.listenerMap.has(selector))
  92. this.listenerMap.get(selector)!.push(options as SelectorListenerOptions<Element>);
  93. else
  94. this.listenerMap.set(selector, [options as SelectorListenerOptions<Element>]);
  95. this.checkSelectors();
  96. }
  97. /** Disables the observation of the child elements */
  98. public disable() {
  99. if(!this.enabled)
  100. return;
  101. this.enabled = false;
  102. this.observer.disconnect();
  103. }
  104. /** Reenables the observation of the child elements */
  105. public enable() {
  106. if(this.enabled)
  107. return;
  108. this.enabled = true;
  109. this.observer.observe(this.baseElement, this.observerOptions);
  110. }
  111. /** Returns whether the observation of the child elements is currently enabled */
  112. public isEnabled() {
  113. return this.enabled;
  114. }
  115. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  116. public clearListeners() {
  117. this.listenerMap.clear();
  118. }
  119. /**
  120. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  121. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  122. */
  123. public removeAllListeners(selector: string) {
  124. return this.listenerMap.delete(selector);
  125. }
  126. /**
  127. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  128. * @returns Returns true when the listener was found and removed, false otherwise
  129. */
  130. public removeListener(selector: string, options: SelectorListenerOptions) {
  131. const listeners = this.listenerMap.get(selector);
  132. if(!listeners)
  133. return false;
  134. const index = listeners.indexOf(options);
  135. if(index !== -1) {
  136. listeners.splice(index, 1);
  137. return true;
  138. }
  139. return false;
  140. }
  141. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  142. public getAllListeners() {
  143. return this.listenerMap;
  144. }
  145. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  146. public getListeners(selector: string) {
  147. return this.listenerMap.get(selector);
  148. }
  149. }