1
0

SelectorObserver.ts 11 KB

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