All files / src/dom dom-watcher.ts

50% Statements 25/50
47.5% Branches 19/40
47.36% Functions 9/19
50% Lines 25/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          25x                   32x               32x                 32x     155x     155x       32x     32x 2x     30x 16x 153x   16x 16x     14x                     14x                                         14x             14x 4x               32x                                                 3x 6x 6x   3x                                                                             3x      
import * as bom from '../dom/bom';
 
type MediaQueryListListener = (
  this: MediaQueryList,
  ev: MediaQueryListEventMap[keyof MediaQueryListEventMap]
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
) => any;
type ResizeObserverListener = (a: ResizeObserverEntry[]) => void;
type MutationObserverListener = (a: MutationRecord[]) => void;
 
export interface DomWatcherConfig {
  // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  // The default event listerner options including passive, once etc.
  eventOptions?: Object | undefined;
 
  /**
   * The element to Watch
   */
  element: HTMLElement | Window | Document | MediaQueryList;
 
  /**
   * The name of the event to watch.
   */
  on: string | string[];
 
  /**
   * The callback to execute.
   */
  callback: Function;
 
  /**
   * A condition in which the function should run.
   * For example, you may want to limit execution of the callback
   * to just mobile.
   */
  runWhen?: Function;
 
  /**
   * Pass an id to this lister
   */
  id?: string;
 
  /**
   * The actual listener that gets attached to the element.
   * This gets created by DomWatcher.
   */
  listener?: EventListenerOrEventListenerObject;
 
  /**
   * A function that removes the listener.  Generated by DomWatcher.
   */
  remover?: Function;
}
 
/**
 * A class that helps with DOM events.  The main usecase for this class is
 * to be able to watch the dom and then later remove a group of events
 * all at once.
 *
 * Basic Usage
 * ```ts
 * let watcher = new DomWatcher();
 *
 * var scrollCallback = (event, done)=> {
 *   // on scroll events.
 * };
 * watcher.add({
 *   element: window,
 *   on: 'scroll',
 *   callback: scrollCallback,
 *   eventOptions: { passive: true }
 * })
 *
 * watcher.add({
 *   element: element,
 *   on: 'click',
 *   callback: ()=> {},
 * );
 *
 *
 * # Add multiple events
 * watcher.add({
 *   element: element,
 *   on: ['click', 'mousemove'],
 *   callback: ()=> {},
 * );
 *
 *
 * // Removes all watchers.
 * watcher.removeAll();
 * ```
 *
 *
 * Advanced Usage
 * ```ts
 * let new watcher = new DomWatcher();
 *
 * // Removes by Id
 * watcher.add({
 *   element: element,
 *   on: 'click',
 *   callback: ()=> {},
 *   id: 'abc'
 * );
 *
 *
 * // Runs the callback associated with abc.  NOTE this is just dry running it
 * // so it's not an actual browser event (hence no event data is provided).
 * watcher.run('abc');
 *
 * watcher.removeById('abc');
 *
 *
 * // Ids actually don't need to be unique.
 * watcher.add({ element: element, on: 'click', callback: ()=> {}, id: 'group1');
 * watcher.add({ element: anotherElement, on: 'mousemove', callback: ()=> {}, id: 'group1');
 * watcher.removeById('group1');
 *
 * // Conditional execution
 * watcher.add({
 *    element: window
 *    callback: ()=> {
 *      console.log('called only on mobile');
 *    }
 *    eventOptions: { passive: true }
 *    on: 'scroll',
 *    runWhen: window.innerWidth < 600
 * });
 *
 *
 * watcher.add({
 *    element: submitElement
 *    callback: ()=> {
 *      console.log('submitted');
 *    }
 *    on: 'click',
 *    runWhen: ()=> { return this.validate()}
 * });
 *
 * ```
 *
 * #### ResizeObserver
 * https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
 * DomWatcher supports resizeObserver.  To use it simply, watch the resize
 * of an element that isn't the window.  Using window will use the standard
 * window resize events.
 *
 * ```ts
 *     watcher.add({
 *         element: myElement,
 *         on: 'resize',
 *         callback: (entries) => {
 *            ....
 *         },
 *     });
 * ```
 *
 * #### MutationObserver
 * https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
 * DomWatcher supports mutation observers. You can pass mutation config
 * to the event options.
 *
 * ```ts
 *
 * const watchMutations = ()=> {
 *     watcher.add({
 *         element: myElement,
 *         id: 'mutations',
 *         on: 'mutation',
 *         callback: (mutationList) => {
 *            ....
 *         },
 *         { childList: true }
 *     });
 * }
 *
 * // Temporarily stop watching mutations.
 * this.watcher.removeById('mutations');
 * ... (update dom, do something)
 * // Rewatch mutations.
 * watchMutations();
 *
 * ```
 *
 *
 * #### Debouncing
 *
 * ```ts
 * // Add debouncing.
 *     watcher.add({
 *         element: document.body,
 *         on: 'mousemove',
 *         callback: func.debounce((event) => {
 *             console.log('movemove!!');
 *         }, 500),
 *     });
 *
 * ```
 *
 * #### SmartResize
 * How can I use this with bom.smartResize?
 * Just use the 'smartResize' event instead.
 *
 * ```ts
 *
 *     watcher.add({
 *         element: window,
 *         on: 'smartResize',
 *         callback: (event) => {
 *             console.log('smart resizing');
 *         },
 *     });
 *
 * ```
 *
 *
 * Culling events only when an element is inview.
 * See example/scroll-demo for actual example.
 *
 * ```ts
 *   let ev = elementVisibility.inview(element, {});
 *   let watcher = new DomWatcher();
 *   watcher.add({
 *      element: window,
 *      on: 'scroll',
 *      eventOptions: { passive: true },
 *      callback: ()=> {
 *         // Runs only when this element is inview.
 *      },
 *      // Tells to run scroll ONLY when the element is inview.
 *      runWhen: ()=> { return ev.state().inview; }
 *   });
 *
 *
 *   // Later
 *   ev.dispose();
 *   watcher.dispose();
 *
 * ```
 *
 * #### MatchMedia
 * https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
 * DomWatcher supports MediaQueryLists that result from calls to matchMedia.
 * That way DomWatcher can be configured to watch for changes across any/all
 * breakpoints a site is designed around.
 *
 * ```ts
 * const mediaQueries = new Map([
 *   [
 *     'desktop',
 *     window.matchMedia('(min-width: 1440px)')],
 *   [
 *     'laptop',
 *     window.matchMedia('(min-width: 1024px) and (max-width: 1439px)')],
 *   [
 *     'tablet',
 *     window.matchMedia('(min-width: 600px) and (max-width: 1023px)')],
 *   [
 *     'mobile',
 *     window.matchMedia('(max-width: 599px)')],
 * ]);
 * const watchBreakpoints = () => {
 *     Array.from(mediaQueries.entries())
 *       .forEach(([breakpoint, mediaQuery]) => {
 *         watcher.add({
 *           element: mediaQuery,
 *           on: 'change',
 *           callback: (e) => {
 *              if (e.matches) {
 *                // Handle the breakpoint
 *              }
 *           },
 *         });
 *       });
 * }
 * ```
 *
 */
export class DomWatcher {
  /**
   * All internal watcher configs.
   */
  private watcherConfigs: Array<DomWatcherConfig>;
 
  constructor() {
    this.watcherConfigs = [];
  }
 
  /**
   * Adds a watcher and immediately begins watching.
   * @param config
   */
  add(config: DomWatcherConfig) {
    // Check whether config.on is a array with multiple events such
    // as ['click', 'mousemove'] or is a single event.
    Iif (Array.isArray(config.on)) {
      const events = config.on as string[];
      events.forEach((eventName: string) => {
        const clone = Object.assign({}, config);
        clone.on = eventName;
        this.addSingleEvent(clone);
      });
    } else {
      this.addSingleEvent(config);
    }
  }
 
  /**
   * Adds a single event.
   * @param config
   */
  private addSingleEvent(config: DomWatcherConfig) {
    const listener = (
      event: Event | ResizeObserverEntry[] | MutationRecord[]
    ) => {
      Iif (config.runWhen) {
        config.runWhen() && config.callback(event);
      } else {
        config.callback(event);
      }
    };
 
    config.listener = listener;
 
    // If the on event is smartResize, wrap it with dom.smartResize.
    if (config.on === 'smartResize') {
      config.remover = bom.smartResize(listener, config.eventOptions || {});
    }
    // Use the resizeObserver if we want to listen to resizing of DOM elements.
    else if (config.on === 'resize' && config.element !== window) {
      const resizeObserver = new ResizeObserver((entries) => {
        (<ResizeObserverListener>listener)(entries);
      });
      resizeObserver.observe(config.element as HTMLElement);
      config.remover = () => {
        resizeObserver.unobserve(config.element as HTMLElement);
      };
    } else Iif (config.on === 'mutation') {
      const mutationObserver = new MutationObserver((mutationsList) => {
        (<MutationObserverListener>listener)(mutationsList);
      });
      mutationObserver.observe(
        config.element as HTMLElement,
        <MutationObserverInit | undefined>config.eventOptions
      );
      config.remover = () => {
        mutationObserver.disconnect();
      };
    } else Iif (
      typeof MediaQueryList !== 'undefined' &&
      config.element instanceof MediaQueryList
    ) {
      // Add listening.
      config.element.addEventListener(
        config.on as keyof MediaQueryListEventMap,
        <MediaQueryListListener>listener,
        <boolean | AddEventListenerOptions>config.eventOptions || {}
      );
 
      // Generate the remover.
      config.remover = () => {
        config.element.removeEventListener(
          config.on as keyof MediaQueryListEventMap,
          <MediaQueryListListener>listener,
          <boolean | EventListenerOptions>config.eventOptions || {}
        );
      };
    } else {
      // Add listening.
      config.element.addEventListener(
        config.on as string,
        listener,
        config.eventOptions || {}
      );
 
      // Generate the remover.
      config.remover = () => {
        config.element.removeEventListener(
          config.on as string,
          listener,
          config.eventOptions || {}
        );
      };
    }
 
    this.watcherConfigs.push(config);
  }
 
  /**
   * Removes a given watcher by id.
   * @param id The id of the watcher to remove.
   */
  removeById(id: string) {
    this.watcherConfigs = this.watcherConfigs.filter(
      (config: DomWatcherConfig) => {
        if (config.id && config.id === id) {
          // Save as var to avoid typescript null error.
          const remover = config.remover;
          remover && remover();
          return false;
        }
        return config;
      }
    );
  }
 
  /**
   * Removes all dom watchers.
   */
  removeAll() {
    this.watcherConfigs.forEach((config) => {
      const remover = config.remover;
      remover && remover();
    });
    this.watcherConfigs = [];
  }
 
  /**
   *
   * Dry runs a callback by id.  This just calls the callback and isn't the
   * actual browser event so no event data will be available when using
   * this method.
   *
   * ```ts
   * watcher.add({
   *    element: element,
   *    callback: ()=> {
   *      console.log('yo');
   *    }
   *    on: 'click',
   *    id: 'yo'
   * });
   *
   * watcher.run('yo');
   * ```
   * @param id
   */
  run(id: string) {
    const configsToRun = this.watcherConfigs.filter(
      (config: DomWatcherConfig) => {
        return config.id && config.id === id;
      }
    );
 
    configsToRun.forEach((config) => {
      config.callback() && config.callback();
    });
  }
 
  /**
   * Disposes of domWatcher.
   */
  dispose() {
    this.removeAll();
  }
}