SelectorObserver.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. }
  67. }
  68. }
  69. private debounce<TArgs>(func: (...args: TArgs[]) => void, time: number): (...args: TArgs[]) => void {
  70. let timeout: number;
  71. return function(...args: TArgs[]) {
  72. clearTimeout(timeout);
  73. timeout = setTimeout(() => func.apply(this, args), time) as unknown as number;
  74. };
  75. }
  76. /**
  77. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  78. * @param selector The selector to observe
  79. * @param options Options for the selector observation
  80. * @param options.listener Gets called whenever the selector was found in the DOM
  81. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  82. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  83. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  84. */
  85. public addListener<TElem extends Element = HTMLElement>(selector: string, options: SelectorListenerOptions<TElem>) {
  86. options = { all: false, continuous: false, debounce: 0, ...options };
  87. if(options.debounce && options.debounce > 0)
  88. options.listener = this.debounce(options.listener as ((arg: NodeListOf<Element> | Element) => void), options.debounce);
  89. if(this.listenerMap.has(selector))
  90. this.listenerMap.get(selector)!.push(options as SelectorListenerOptions<Element>);
  91. else
  92. this.listenerMap.set(selector, [options as SelectorListenerOptions<Element>]);
  93. this.checkSelectors();
  94. }
  95. /** Disables the observation of the child elements */
  96. public disable() {
  97. if(!this.enabled)
  98. return;
  99. this.enabled = false;
  100. this.observer.disconnect();
  101. }
  102. /** Reenables the observation of the child elements */
  103. public enable() {
  104. if(this.enabled)
  105. return;
  106. this.enabled = true;
  107. this.observer.observe(this.baseElement, this.observerOptions);
  108. }
  109. /** Returns whether the observation of the child elements is currently enabled */
  110. public isEnabled() {
  111. return this.enabled;
  112. }
  113. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  114. public clearListeners() {
  115. this.listenerMap.clear();
  116. }
  117. /**
  118. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  119. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  120. */
  121. public removeAllListeners(selector: string) {
  122. return this.listenerMap.delete(selector);
  123. }
  124. /**
  125. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  126. * @returns Returns true when the listener was found and removed, false otherwise
  127. */
  128. public removeListener(selector: string, options: SelectorListenerOptions) {
  129. const listeners = this.listenerMap.get(selector);
  130. if(!listeners)
  131. return false;
  132. const index = listeners.indexOf(options);
  133. if(index !== -1) {
  134. listeners.splice(index, 1);
  135. return true;
  136. }
  137. return false;
  138. }
  139. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  140. public getAllListeners() {
  141. return this.listenerMap;
  142. }
  143. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  144. public getListeners(selector: string) {
  145. return this.listenerMap.get(selector);
  146. }
  147. }