SelectorObserver.ts 11 KB

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