All files / watchers size-watcher.ts

98.74% Statements 157/159
92.15% Branches 47/51
100% Functions 24/24
98.7% Lines 152/154

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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632        94x 94x       94x 94x 94x 94x               94x   94x         94x 94x   94x                     94x                                                                                                                                                                               38x                     147x 147x   147x 147x 22x 22x     147x             61x 1x     60x       60x   60x     144x       60x 81x 89x         60x       60x     254x 254x 254x 30x     224x   224x 224x 224x 224x     224x 224x                         60x     193x 193x 1x     192x 192x 1x     191x                           60x       175x 175x   175x 175x 175x 41x     175x 175x 175x         60x       178x 175x           175x 175x 175x   175x 9x     166x 166x             166x   166x 119x   119x           60x       15x 15x 15x 15x 14x   14x   3x             60x       41x 41x 41x   41x 38x       38x 38x           60x   89x   89x 89x   89x   89x 115x           115x 25x 25x     90x   90x           60x       60x 15x 15x     15x         60x 4x 4x     4x         60x       60x 11x                                                                                                                                                                                                                                                                           94x 94x   94x     185x 185x                 94x         115x           115x 144x 12x     132x 206x 17x     189x 189x 90x         25x     94x 313x 313x   313x           94x       20x 20x   1x 1x     20x           20x     94x     445x 420x     25x 17x     8x 7x     1x     94x       209x  
/**
 * @module Watchers/SizeWatcher
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { Box, Dimension, Size, SizeTarget } from "@lisn/globals/types";
 
import { setNumericStyleJsVars } from "@lisn/utils/css-alter";
import { logError } from "@lisn/utils/log";
import { toNonNegNum } from "@lisn/utils/math";
import {
  isValidBox,
  isValidDimension,
  getEntryBorderBox,
  getEntryContentBox,
  tryGetViewportOverlay,
  fetchViewportOverlay,
} from "@lisn/utils/size";
import { objToStrKey } from "@lisn/utils/text";
 
import {
  CallbackHandler,
  Callback,
  wrapCallback,
} from "@lisn/modules/callback";
import { newXWeakMap } from "@lisn/modules/x-map";
import { XResizeObserver } from "@lisn/modules/x-resize-observer";
 
import debug from "@lisn/debug/debug";
 
/**
 * {@link SizeWatcher} monitors the size of a given target. It's built on top
 * of {@link https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver | ResizeObserver}.
 *
 * It manages registered callbacks globally and reuses ResizeObservers.
 *
 * Each instance of SizeWatcher manages up to two ResizeObservers: one
 * for content-box size changes and one for border-box size changes.
 */
export class SizeWatcher {
  /**
   * Call the given handler whenever the target's size changes.
   *
   * Unless {@link OnResizeOptions.skipInitial} is true, the handler is also
   * called (almost) immediately with the latest size data.
   *
   * **IMPORTANT:** The same handler can _not_ be added multiple times for the
   * same target, even if the options differ. If the handler has already been
   * added for this target, either using {@link onResize} or {@link trackSize},
   * then it will be removed and re-added with the current options.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the target or options are invalid.
   */
  readonly onResize: (
    handler: OnResizeHandler,
    options?: OnResizeOptions,
  ) => Promise<void>;
 
  /**
   * Removes a previously added handler.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the target is invalid.
   */
  readonly offResize: (handler: OnResizeHandler, target?: SizeTarget) => void;
 
  /**
   * This is the same as {@link onResize} except that if `handler` is not given,
   * then it defaults to an  handler that updates a set of CSS variables on the
   * target's style:
   *
   * - If {@link OnResizeOptions.target | options.target} is not given, or is
   *   `window`, the following CSS variables are set on the root (`html`)
   *   element and represent the viewport size:
   *   - `--lisn-js--window-border-width`
   *   - `--lisn-js--window-border-height`
   *   - `--lisn-js--window-content-width`
   *   - `--lisn-js--window-content-height`
   *
   * - Otherwise, the following variables are set on the target itself and
   *   represent its visible size:
   *   - `--lisn-js--border-width`
   *   - `--lisn-js--border-height`
   *   - `--lisn-js--content-width`
   *   - `--lisn-js--content-height`
   *
   * If `target` is `document`, then it will use `document.documentElement`.
   *
   * **IMPORTANT:** The same handler can _not_ be added multiple times for the
   * same target, even if the options differ. If the handler has already been
   * added for this target, either using {@link onResize} or {@link trackSize},
   * then it will be removed and re-added with the current options.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the target or options are invalid.
   */
  readonly trackSize: (
    handler?: OnResizeHandler | null,
    options?: OnResizeOptions,
  ) => Promise<void>;
 
  /**
   * Removes a previously added handler for {@link trackSize}.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the target is invalid.
   */
  readonly noTrackSize: (
    handler?: OnResizeHandler | null,
    target?: SizeTarget,
  ) => void;
 
  /**
   * Get the size of the given target. It will get the size from a
   * ResizeObserverEntry and so it's always delayed by one frame at least.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the target is invalid.
   */
  readonly fetchCurrentSize: (target?: SizeTarget) => Promise<SizeData>;
 
  /**
   * Creates a new instance of SizeWatcher with the given
   * {@link SizeWatcherConfig}. It does not save it for future reuse.
   */
  static create(config?: SizeWatcherConfig) {
    return new SizeWatcher(getConfig(config), CONSTRUCTOR_KEY);
  }
 
  /**
   * Returns an existing instance of SizeWatcher with the given
   * {@link SizeWatcherConfig}, or creates a new one.
   *
   * **NOTE:** It saves it for future reuse, so don't use this for temporary
   * short-lived watchers.
   */
  static reuse(config?: SizeWatcherConfig) {
    const myConfig = getConfig(config);
    const configStrKey = objToStrKey(myConfig);
 
    let instance = instances.get(configStrKey);
    if (!instance) {
      instance = new SizeWatcher(myConfig, CONSTRUCTOR_KEY);
      instances.set(configStrKey, instance);
    }
 
    return instance;
  }
 
  private constructor(
    config: SizeWatcherConfigInternal,
    key: typeof CONSTRUCTOR_KEY,
  ) {
    if (key !== CONSTRUCTOR_KEY) {
      throw MH.illegalConstructorError("SizeWatcher.create");
    }
 
    const logger = debug
      ? new debug.Logger({ name: "SizeWatcher", logAtCreation: config })
      : null;
 
    const allSizeData = MH.newWeakMap<Element, SizeData>();
 
    const allCallbacks = newXWeakMap<
      Element,
      Map<OnResizeHandler, CallbackEntry>
    >(() => MH.newMap());
 
    // ----------
 
    const resizeHandler = (entries: ResizeObserverEntry[]) => {
      for (const entry of entries) {
        processEntry(entry);
      }
    };
 
    // Don't debounce the observer, only callbacks.
    const xObserver = new XResizeObserver(resizeHandler);
 
    // ----------
 
    const fetchCurrentSize = async (
      target: SizeTarget | undefined,
    ): Promise<SizeData> => {
      const element = await fetchElement(target);
      const sizeData = allSizeData.get(element);
      if (sizeData) {
        return MH.copyObject(sizeData);
      }
 
      return MH.newPromise((resolve) => {
        // Use a temp ResizeObserver
        const observer = MH.newResizeObserver((entries) => {
          const sizeData = getSizeData(entries[0]);
          observer?.disconnect();
          resolve(sizeData); // no need to copy or save it
        });
 
        if (observer) {
          observer.observe(element);
        } else E{
          // Warning would have already been logged by XResizeObserver
          resolve({
            border: { [MC.S_WIDTH]: 0, [MC.S_HEIGHT]: 0 },
            content: { [MC.S_WIDTH]: 0, [MC.S_HEIGHT]: 0 },
          });
        }
      });
    };
 
    // ----------
 
    const fetchOptions = async (
      options: OnResizeOptions,
    ): Promise<OnResizeOptionsInternal> => {
      const box = options.box ?? null;
      if (box && !isValidBox(box)) {
        throw MH.usageError(`Unknown box type: '${box}'`);
      }
 
      const dimension = options.dimension ?? null;
      if (dimension && !isValidDimension(dimension)) {
        throw MH.usageError(`Unknown dimension: '${dimension}'`);
      }
 
      return {
        _element: await fetchElement(MH.targetOf(options)),
        _box: box,
        _dimension: dimension,
        // If threshold is 0, internally treat as 1 (pixel)
        _threshold:
          toNonNegNum(options.threshold, config._resizeThreshold) || 1,
        _debounceWindow:
          options[MC.S_DEBOUNCE_WINDOW] ?? config._debounceWindow,
      };
    };
 
    // ----------
 
    const createCallback = (
      handler: OnResizeHandler,
      options: OnResizeOptionsInternal,
    ): CallbackEntry => {
      const element = options._element;
      MH.remove(allCallbacks.get(element)?.get(handler)?._callback);
 
      debug: logger?.debug5("Adding/updating handler", options);
      const callback = wrapCallback(handler, options._debounceWindow);
      callback.onRemove(() => {
        deleteHandler(handler, options);
      });
 
      const entry = { _callback: callback, _options: options };
      allCallbacks.sGet(element).set(handler, entry);
      return entry;
    };
 
    // ----------
 
    const setupOnResize = async (
      handler: OnResizeHandler,
      userOptions: OnResizeOptions | undefined,
    ) => {
      const options = await fetchOptions(userOptions ?? {});
      const element = options._element;
 
      // Don't await for the size data before creating the callback so that
      // setupOnResize and removeOnResize have the same "timing" and therefore
      // calling onResize and offResize immediately without awaiting removes the
      // callback.
      const entry = createCallback(handler, options);
      const callback = entry._callback;
      const sizeData = await fetchCurrentSize(element);
 
      if (callback.isRemoved()) {
        return;
      }
 
      entry._data = sizeData;
      allSizeData.set(element, sizeData);
 
      // Always use observeLater. This is because the initial call to callback
      // shouldn't be debounced, and so we call it manually here, regardless if
      // it's a new target or not. Therefore we don't want the observer to also
      // call it in case it _is_ a new target.
      // It's ok if already observed, won't do anything.
      xObserver.observeLater(element);
 
      if (!userOptions?.skipInitial) {
        debug: logger?.debug5("Calling initially with", element, sizeData);
        // Use a one-off callback that's not debounced for the initial call.
        await invokeCallback(wrapCallback(handler), element, sizeData);
      }
    };
 
    // ----------
 
    const removeOnResize = async (
      handler: OnResizeHandler,
      target: SizeTarget | undefined,
    ) => {
      const options = await fetchOptions({ target });
      const element = options._element;
      const currEntry = allCallbacks.get(element)?.get(handler);
      if (currEntry) {
        MH.remove(currEntry._callback);
 
        if (handler === setSizeCssProps) {
          // delete the properties
          setSizeCssProps(element, null);
        }
      }
    };
 
    // ----------
 
    const deleteHandler = (
      handler: OnResizeHandler,
      options: OnResizeOptionsInternal,
    ) => {
      const element = options._element;
      MH.deleteKey(allCallbacks.get(element), handler);
      allCallbacks.prune(element);
 
      if (!allCallbacks.has(element)) {
        debug: logger?.debug4(
          "No more callbacks for target; unobserving",
          element,
        );
        xObserver.unobserve(element);
        MH.deleteKey(allSizeData, element);
      }
    };
 
    // ----------
 
    const processEntry = (entry: ResizeObserverEntry) => {
      // In reality, it can't be just a base Element
      const element = MH.targetOf(entry);
 
      const latestData = getSizeData(entry);
      allSizeData.set(element, latestData);
 
      debug: logger?.debug9("New size data", element, latestData);
 
      for (const entry of allCallbacks.get(element)?.values() || []) {
        const thresholdsExceeded = hasExceededThreshold(
          entry._options,
          latestData,
          entry._data,
        );
 
        if (!thresholdsExceeded) {
          debug: logger?.debug9("Threshold not exceeded");
          continue;
        }
 
        entry._data = latestData;
 
        invokeCallback(entry._callback, element, latestData);
      }
    };
 
    // ----------
 
    this.fetchCurrentSize = fetchCurrentSize;
 
    // ----------
 
    this.trackSize = async (handler?, options?) => {
      if (!handler) {
        handler = setSizeCssProps;
      }
 
      return setupOnResize(handler, options);
    };
 
    // ----------
 
    this.noTrackSize = (handler?, target?) => {
      if (!handler) {
        handler = setSizeCssProps;
      }
 
      removeOnResize(handler, target); // no need to await
    };
 
    // ----------
 
    this.onResize = setupOnResize;
 
    // ----------
 
    this.offResize = (handler, target?) => {
      removeOnResize(handler, target); // no need to await
    };
  }
}
 
/**
 * @interface
 */
export type SizeWatcherConfig = {
  /**
   * The default value for
   * {@link OnResizeOptions.debounceWindow | debounceWindow} in calls to
   * {@link SizeWatcher.onResize}.
   *
   * @defaultValue 75
   */
  debounceWindow?: number;
 
  /**
   * The default value for
   * {@link OnResizeOptions.threshold | threshold} in calls to
   * {@link SizeWatcher.onResize}.
   *
   * @defaultValue 50
   */
  resizeThreshold?: number;
};
 
/**
 * @interface
 */
export type OnResizeOptions = {
  /**
   * If it is not given, or is `null` or `window`, then it will track the size
   * of the viewport (akin to `clientHeight` on `documentElement`).
   *
   * If it is `document`, then it will use `document.documentElement`.
   *
   * Other values of target must be an `Element` and are taken literally.
   *
   * @defaultValue undefined
   */
  target?: SizeTarget;
 
  /**
   * Specifies whether to listen for changes in content box size or border box
   * size.
   *
   * If not given, then it listens for changes in either.
   *
   * @defaultValue undefined
   */
  box?: Box;
 
  /**
   * Specifies whether to listen for changes in width or height.
   *
   * If not given, then it listens for changes in either.
   *
   * @defaultValue undefined
   */
  dimension?: Dimension;
 
  /**
   * If non-0, the handler will only be called when the target's size in the
   * observed {@link OnResizeOptions.dimension} and {@link OnResizeOptions.box}
   * type has changed at least `threshold` pixels since the last time the
   * handler was called.
   *
   * Special case when `threshold` is 0 and at least one of
   * {@link OnResizeOptions.dimension} or {@link OnResizeOptions.box} is given:
   * if there's a resize event but the size in the observed dimensions/box
   * types has not changed, the callback is _not_ called.
   *
   * @defaultValue {@link SizeWatcherConfig.resizeThreshold}
   */
  threshold?: number;
 
  /**
   * Do not call the handler until there's a future resize of the element.
   *
   * By default we call the handler (almost) immediately with the current size
   * data for the target.
   *
   * @defaultValue false
   */
  skipInitial?: boolean;
 
  /**
   * If non-0, the handler will be "debounced" so it's called at most
   * `debounceWindow` milliseconds.
   *
   * @defaultValue {@link SizeWatcherConfig.debounceWindow}
   */
  debounceWindow?: number;
};
 
/**
 * The handler is invoked with three arguments:
 *
 * - the element that has been resized: if the target you requested was the
 *   viewport, then this will be a fixed positioned overlay that tracks the
 *   size of the viewport
 * - the {@link SizeData} for the element
 */
export type OnResizeHandlerArgs = [Element, SizeData];
export type OnResizeCallback = Callback<OnResizeHandlerArgs>;
export type OnResizeHandler =
  | CallbackHandler<OnResizeHandlerArgs>
  | OnResizeCallback;
 
export type SizeData = Record<Box, Size>;
 
// ----------------------------------------
 
type SizeWatcherConfigInternal = {
  _debounceWindow: number;
  _resizeThreshold: number;
};
 
type OnResizeOptionsInternal = {
  _element: Element;
  _box: Box | null;
  _dimension: Dimension | null;
  _threshold: number;
  _debounceWindow: number;
};
 
type CallbackEntry = {
  _callback: OnResizeCallback;
  _options: OnResizeOptionsInternal;
  _data?: SizeData;
};
 
const CONSTRUCTOR_KEY: unique symbol = MC.SYMBOL() as typeof CONSTRUCTOR_KEY;
const instances = MH.newMap<string, SizeWatcher>();
 
const getConfig = (
  config: SizeWatcherConfig | undefined,
): SizeWatcherConfigInternal => {
  config ??= {};
  return {
    _debounceWindow: toNonNegNum(config[MC.S_DEBOUNCE_WINDOW], 75),
    // If threshold is 0, internally treat as 1 (pixel)
    _resizeThreshold: toNonNegNum(config.resizeThreshold, 50) || 1,
  };
};
 
// --------------------
 
const hasExceededThreshold = (
  options: OnResizeOptionsInternal,
  latestData: SizeData,
  lastThresholdData: SizeData | undefined,
): boolean => {
  Iif (!lastThresholdData) {
    /* istanbul ignore */
    return false;
  }
 
  let box: Box, dim: Dimension;
  for (box in latestData) {
    if (options._box && options._box !== box) {
      continue;
    }
 
    for (dim in latestData[box]) {
      if (options._dimension && options._dimension !== dim) {
        continue;
      }
 
      const diff = MH.abs(latestData[box][dim] - lastThresholdData[box][dim]);
      if (diff >= options._threshold) {
        return true;
      }
    }
  }
 
  return false;
};
 
const getSizeData = (entry: ResizeObserverEntry): SizeData => {
  const borderBox = getEntryBorderBox(entry, true);
  const contentBox = getEntryContentBox(entry);
 
  return {
    border: borderBox,
    content: contentBox,
  };
};
 
const setSizeCssProps = (
  element: Element,
  sizeData: SizeData | undefined | null,
) => {
  let prefix = "";
  if (element === tryGetViewportOverlay()) {
    // Set the CSS vars on the root element
    element = MH.getDocElement();
    prefix = "window-";
  }
 
  const props = {
    borderWidth: sizeData?.border[MC.S_WIDTH],
    borderHeight: sizeData?.border[MC.S_HEIGHT],
    contentWidth: sizeData?.content[MC.S_WIDTH],
    contentHeight: sizeData?.content[MC.S_HEIGHT],
  };
  setNumericStyleJsVars(element, props, { _prefix: prefix }); // don't await here
};
 
const fetchElement = async (
  target: SizeTarget | undefined,
): Promise<Element> => {
  if (MH.isElement(target)) {
    return target;
  }
 
  if (!target || target === MH.getWindow()) {
    return fetchViewportOverlay();
  }
 
  if (target === MH.getDoc()) {
    return MH.getDocElement();
  }
 
  throw MH.usageError("Unsupported resize target");
};
 
const invokeCallback = (
  callback: OnResizeCallback,
  element: Element,
  sizeData: SizeData,
) => callback.invoke(element, MH.copyObject(sizeData)).catch(logError);