SelectorObserver.ts 9.1 KB

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