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 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 | 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 488x 488x 161x 327x 290x 290x 81x 246x 246x 246x 13x 233x 19x 19x 19x 19x 214x 214x 214x 214x 214x 214x 246x 209x 209x 66x 66x 246x 94x 28x 28x 36x 10x 18x 94x 32x 32x 32x 18x 14x 94x 64x 60x 60x 60x 2x 1x 59x 59x 3x 2x 59x 59x 59x 2x 4x 2x 57x 57x 114x 59x 118x 59x 59x 58x 59x 57x 114x 265x 59x 59x 59x 94x 143x 94x 14x 94x 7x 94x 3x 94x 380x 94x 380x 94x 2x 94x 63x 63x 94x 21x 94x 51x 51x 94x 109x 109x 94x 94x 316x 94x 94x 110x 94x 94x 94x 94x 319x 94x 94x 760x 94x 316x 270x 46x 45x 1x 94x 96x 94x 64x 64x 60x 60x 94x 319x 319x 319x 319x 94x 73x 73x 12x 2x 10x 10x 10x 61x 2x 2x 1x 1x 59x 1x 58x 94x 59x 59x 65x 65x 59x 59x 59x 59x 59x 6x 6x 59x 94x 65x 65x 57x 21x 36x 65x 56x 18x 38x 65x 65x 65x 65x 65x 65x 65x 65x 65x 94x 59x 59x 59x 59x 59x 59x 59x 59x 59x 324x 324x 59x 265x 265x 5x 5x 260x 520x 520x 520x 260x 260x 260x 54x 260x 260x 54x 54x 54x 94x 94x 208x 94x 94x 94x 94x 94x 94x 94x 1x 93x 1x 92x 6x 208x 94x 94x | /** * @module Utils */ import * as MC from "@lisn/globals/minification-constants"; import * as MH from "@lisn/globals/minification-helpers"; import { settings } from "@lisn/globals/settings"; import { ScrollDirection, ScrollTarget, TargetCoordinates, CoordinateOffset, ScrollPosition, Anchor, } from "@lisn/globals/types"; import { newAnimationFrameIterator, ElapsedTimes, } from "@lisn/utils/animations"; import { getComputedStylePropNow } from "@lisn/utils/css-alter"; import { SCROLL_DIRECTIONS } from "@lisn/utils/directions"; import { waitForInteractive, waitForElementOrInteractive, } from "@lisn/utils/dom-events"; import { waitForMeasureTime } from "@lisn/utils/dom-optimize"; import { addEventListenerTo, removeEventListenerFrom } from "@lisn/utils/event"; import { logError, logWarn } from "@lisn/utils/log"; import { maxAbs, criticallyDamped } from "@lisn/utils/math"; import { randId, formatAsString } from "@lisn/utils/text"; import { isValidStrList } from "@lisn/utils/validation"; import { newXMap } from "@lisn/modules/x-map"; import debug from "@lisn/debug/debug"; /** * @category Scrolling */ export type ScrollAction = { cancel: () => boolean; /** * Will reject if the scroll is cancelled. */ waitFor: () => Promise<ScrollPosition>; }; /** * @category Scrolling * @interface */ export type ScrollToOptions = { /** * The element that should be scrolled. * * @defaultValue If `document.body` is scrollable, will use that; otherwise `document.scrollingElement` */ scrollable?: Element; /** * Offset the target coordinates by the given amount(s). * * E.g. if the final target coordinates are computed to be * `{top: 100, left: 0}` and you specify offset as `{top: 10, left: 20}`, it * will scroll to `{top: 110, left: 20}`. * * @defaultValue undefined */ offset?: CoordinateOffset; // TODO maybe support fixed average velocity as an alternative to fixed duration? /** * The duration of the scroll animation in milliseconds. If not given, it is * instant. * * @defaultValue 0 */ duration?: number; /** * Whether another request to us to scroll the same target can interrupt this * scroll before it finishes. * * @defaultValue false */ weCanInterrupt?: boolean; /** * Whether a user attempt to scroll the target can interrupt this before it * finishes. * * @defaultValue false */ userCanInterrupt?: boolean; /** * If the scrolling element is already at the given coordinates (or strictly * speaking we allow for 5 pixels difference), then if `altTarget` is given, * this will become the target to scroll to. * * @defaultValue undefined */ altTarget?: TargetCoordinates | Element | string; /** * Offset the target coordinates by the given amount(s) when `altTarget` is used. * * See {@link ScrollToOptions.offset}. * * @defaultValue undefined */ altOffset?: CoordinateOffset; }; // ---------- /** * Returns true if the given element is scrollable in the given direction, or * in either direction (if `axis` is not given). * * It first checks whether the current scroll offset on the target along the * given axis is non-0, and if so returns true immediately. Otherwise it will * attempt to determine if it's scrollable using one of these methods * (controlled by `options.active`): * - passive check (default): Will examine `clientWidth/Height`, * `scrollWidth/Height` as well as the computed `overflow` CSS property to try * to determine if the target is scrollable. This is not 100% reliable but is * safer than the active check * - active check: Will attempt to scroll the target by 1px and examine if the * scroll offset had changed, then revert it back to 0. This is a more * reliable check, however it can cause issues in certain contexts. In * particular, if a scroll on the target had just been initiated (but it's * scroll offset was still 0), the scroll may be cancelled. Never use that * inside scroll-based handlers. * * **NOTE:** If the layout has been invalidated and not yet recalculated, this * will cause a forced layout, so always {@link waitForMeasureTime} before * calling this function when possible. * * @param [options.axis] One of "x" or "y" for horizontal or vertical scroll * respectively. If not given, it checks both. * @param [options.active] If true, then if the target's current scroll offset * is 0, it will attempt to scroll it rather than * looking at its overflow. * @param [options.noCache] By default the result of a check is cached for 1s * and if there's already a cached result for this * element, it is returned. Set this to true to disable * checking the cache and also saving the result into * the cache. * * @category Scrolling */ export const isScrollable = ( element: Element, options?: { axis?: "x" | "y"; active?: boolean; noCache?: boolean; }, ): boolean => { const { axis, active, noCache } = options ?? {}; if (!axis) { return ( isScrollable(element, { axis: "y", active, noCache }) || isScrollable(element, { axis: "x", active, noCache }) ); } if (!noCache) { const cachedResult = isScrollableCache.get(element)?.get(axis); if (!MH.isNullish(cachedResult)) { return cachedResult; } } const offset = axis === "x" ? "Left" : "Top"; let result = false; if (element[`scroll${offset}`]) { result = true; } else if (active) { // Use scrollTo with explicit behavior set to instant instead of setting // the scrollTop/Left properties since the latter doesn't work with // scroll-behavior smooth. MH.elScrollTo(element, { [MH.toLowerCase(offset)]: 1 }); const canScroll = element[`scroll${offset}`] > 0; MH.elScrollTo(element, { [MH.toLowerCase(offset)]: 0 }); result = canScroll; } else { const dimension = axis === "x" ? "Width" : "Height"; const isDocScrollable = element === MH.getDocScrollingElement(); const hasOverflow = element[`scroll${dimension}`] > element[`client${dimension}`]; const overflowProp = getComputedStylePropNow(element, "overflow"); const scrollingOverflows = [ MC.S_SCROLL, MC.S_AUTO, ...(isDocScrollable ? [MC.S_VISIBLE] : []), ]; result = hasOverflow && MH.includes(scrollingOverflows, overflowProp); } if (!noCache) { isScrollableCache.sGet(element).set(axis, result); MH.setTimer(() => { MH.deleteKey(isScrollableCache.get(element), axis); isScrollableCache.prune(element); }, IS_SCROLLABLE_CACHE_TIMEOUT); } return result; }; /** * Returns the closest scrollable ancestor of the given element, _not including * it_. * * @param options See {@link isScrollable} * * @returns `null` if no scrollable ancestors are found. * * @category Scrolling */ export const getClosestScrollable = ( element: Element, options?: { axis?: "x" | "y"; active?: boolean; noCache?: boolean; }, ) => { // Walk up the tree, starting at the element in question but excluding it. let ancestor: Element | null | undefined = element; while ((ancestor = MH.parentOf(ancestor))) { if (isScrollable(ancestor, options)) { return ancestor; } } return null; }; /** * Returns the current {@link ScrollAction} if any. * * @category Scrolling */ export const getCurrentScrollAction = ( scrollable?: Element, ): ScrollAction | null => { scrollable = toScrollableOrDefault(scrollable); const info = currentScrollInfos.get(scrollable); if (info) { return MH.copyObject(info._action); } return null; }; /** * Scrolls the given scrollable element to the given `to` target. * * Returns `null` if there's an ongoing scroll that is not cancellable. * * Note that if `to` is an element or a query selector string, then it _must_ be * a descendant of the scrollable element. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the target coordinates are invalid. * * @param to If this is an element, then its top-left position is used as * the target coordinates. If it is a string, then it is treated * as a selector for an element using `querySelector`. * * @returns `null` if there's an ongoing scroll that is not cancellable, * otherwise a {@link ScrollAction}. * * @category Scrolling */ export const scrollTo = ( to: TargetCoordinates | Element | string, userOptions?: ScrollToOptions, ): ScrollAction | null => { const options = getOptions(to, userOptions); const scrollable = options._scrollable; // cancel current scroll action if any const info = currentScrollInfos.get(scrollable); if (info) { if (!info._action.cancel()) { // current scroll action is not cancellable by us return null; } } let isCancelled = false; const cancelFn = options._weCanInterrupt ? () => (isCancelled = true) : () => false; const scrollEvents = ["touchmove", "wheel"]; // don't bother with keyboard let preventScrollHandler: EventListener | null = null; if (options._userCanInterrupt) { for (const eventType of scrollEvents) { addEventListenerTo( scrollable, eventType, () => { isCancelled = true; }, { once: true }, ); } } else { preventScrollHandler = MH.preventDefault; for (const eventType of scrollEvents) { addEventListenerTo(scrollable, eventType, preventScrollHandler, { passive: false, }); } } const thisInfo: ScrollInfo = { _action: { waitFor: () => scrollActionPromise, cancel: cancelFn, }, }; const cleanup = () => { if (currentScrollInfos.get(scrollable)?._action === thisInfo._action) { MH.deleteKey(currentScrollInfos, scrollable); } if (preventScrollHandler) { for (const eventType of scrollEvents) { removeEventListenerFrom(scrollable, eventType, preventScrollHandler, { passive: false, }); } } }; const scrollActionPromise = initiateScroll(options, () => isCancelled); thisInfo._action.waitFor().then(cleanup).catch(cleanup); updateCurrentScrollInfo(scrollable, thisInfo); return thisInfo._action; }; /** * Returns true if the given string is a valid scroll direction. * * @category Validation */ export const isValidScrollDirection = ( direction: string, ): direction is ScrollDirection => MH.includes(SCROLL_DIRECTIONS, direction); /** * Returns true if the given string or array is a list of valid scroll * directions. * * @category Validation */ export const isValidScrollDirectionList = (directions: string | string[]) => isValidStrList(directions, isValidScrollDirection, false); /** * @ignore * @internal */ export const mapScrollable = (original: Element, actualScrollable: Element) => mappedScrollables.set(original, actualScrollable); /** * @ignore * @internal */ export const unmapScrollable = (original: Element) => MH.deleteKey(mappedScrollables, original); /** * @ignore * @internal */ export const getClientWidthNow = (element: Element) => isScrollableBodyInQuirks(element) ? element.offsetWidth - getBorderWidth(element, MC.S_LEFT) - getBorderWidth(element, MC.S_RIGHT) : element[MC.S_CLIENT_WIDTH]; /** * @ignore * @internal */ export const getClientHeightNow = (element: Element) => isScrollableBodyInQuirks(element) ? element.offsetHeight - getBorderWidth(element, MC.S_TOP) - getBorderWidth(element, MC.S_BOTTOM) : element[MC.S_CLIENT_HEIGHT]; /** * @ignore * @internal */ export const tryGetMainContentElement = (): HTMLElement | null => mainContentElement ?? null; /** * @ignore * @internal * * Exposed via ScrollWatcher */ export const fetchMainContentElement = async (): Promise<HTMLElement> => { await init(); return mainContentElement; }; /** * @ignore * @internal */ export const tryGetMainScrollableElement = (): HTMLElement | null => mainScrollableElement ?? null; /** * @ignore * @internal * * Exposed via ScrollWatcher */ export const fetchMainScrollableElement = async (): Promise<HTMLElement> => { await init(); return mainScrollableElement; }; /** * @ignore * @internal */ export const getDefaultScrollingElement = () => { const body = MH.getBody(); return isScrollable(body) ? body : (MH.getDocScrollingElement() ?? body); }; /** * @ignore * @internal */ export const tryGetScrollableElement = ( target: ScrollTarget | null | undefined, ): Element | null => toScrollableOrMain(target, tryGetMainScrollableElement); /** * @ignore * @internal */ export const fetchScrollableElement = async ( target: ScrollTarget | null | undefined, ): Promise<Element> => toScrollableOrMain(target, fetchMainScrollableElement); // ---------------------------------------- type ScrollToOptionsInternal = { _target: TargetCoordinates; _offset: CoordinateOffset | null; _altTarget: TargetCoordinates | null; _altOffset: CoordinateOffset | null; _scrollable: Element; _duration: number; _weCanInterrupt: boolean; _userCanInterrupt: boolean; }; type Velocity = { top: number; left: number }; type ScrollInfo = { _action: ScrollAction; _position?: ScrollPosition; _velocity?: Velocity; _elapsed?: ElapsedTimes; }; const IS_SCROLLABLE_CACHE_TIMEOUT = 1000; const isScrollableCache = newXMap<Element, Map<"x" | "y", boolean>>(() => MH.newMap(), ); const mappedScrollables = MH.newMap<Element, Element>(); const currentScrollInfos = MH.newMap<Element, ScrollInfo>(); const DIFF_THRESHOLD = 5; const arePositionsDifferent = ( start: ScrollPosition, end: ScrollPosition, threshold = DIFF_THRESHOLD, ) => maxAbs(start.top - end.top, start.left - end.left) > threshold; // must be called in "measure time" const getBorderWidth = (element: Element, side: Anchor) => MH.ceil(MH.parseFloat(getComputedStylePropNow(element, `border-${side}`))); const isScrollableBodyInQuirks = (element: Element): element is HTMLElement => element === MH.getBody() && MH.getDocScrollingElement() === null; const toScrollableOrMain = <R>( target: ScrollTarget | null | undefined, getMain: () => R, ): Element | R => { if (MH.isElement(target)) { return mappedScrollables.get(target) ?? target; } if (!target || target === MH.getWindow() || target === MH.getDoc()) { return getMain(); } throw MH.usageError("Unsupported scroll target"); }; const toScrollableOrDefault = (scrollable: Element | undefined): Element => scrollable ?? getDefaultScrollingElement(); const getOptions = ( to: TargetCoordinates | Element | string, options: ScrollToOptions | undefined, ): ScrollToOptionsInternal => { const scrollable = toScrollableOrDefault(options?.scrollable); const target = getTargetCoordinates(scrollable, to); const altTarget = options?.altTarget ? getTargetCoordinates(scrollable, options?.altTarget) : null; return { _target: target, _offset: options?.offset ?? null, _altTarget: altTarget, _altOffset: options?.altOffset ?? null, _scrollable: scrollable, _duration: options?.duration ?? 0, _weCanInterrupt: options?.weCanInterrupt ?? false, _userCanInterrupt: options?.userCanInterrupt ?? false, }; }; const updateCurrentScrollInfo = ( scrollable: Element, newInfo: Partial<ScrollInfo>, ) => { const existingScrollInfo = currentScrollInfos.get(scrollable); const _action = newInfo._action ?? existingScrollInfo?._action; if (_action) { currentScrollInfos.set( scrollable, MH.merge(existingScrollInfo, newInfo, { _action }), ); } }; const getTargetCoordinates = ( scrollable: Element, target: TargetCoordinates | Element | string, ): TargetCoordinates => { const isDocScrollingElement = scrollable === MH.getDocScrollingElement(); if (MH.isElement(target)) { if (scrollable === target || !scrollable.contains(target)) { throw MH.usageError("Target must be a descendant of the scrollable one"); } return { top: () => MH.getBoundingClientRect(target).top - MH.getBoundingClientRect(scrollable).top + (isDocScrollingElement ? 0 : scrollable[MC.S_SCROLL_TOP]), left: () => MH.getBoundingClientRect(target).left - MH.getBoundingClientRect(scrollable).left + (isDocScrollingElement ? 0 : scrollable[MC.S_SCROLL_LEFT]), }; } if (MH.isString(target)) { const targetEl = MH.docQuerySelector(target); if (!targetEl) { throw MH.usageError(`No match for '${target}'`); } return getTargetCoordinates(scrollable, targetEl); } if (!MH.isObject(target) || !("top" in target || "left" in target)) { throw MH.usageError("Invalid coordinates"); } return target; }; const getStartEndPosition = async ( options: ScrollToOptionsInternal, ): Promise<{ _start: ScrollPosition; _end: ScrollPosition }> => { await waitForMeasureTime(); const applyOffset = ( position: ScrollPosition, offset: CoordinateOffset | null, ) => { position.top += offset?.top ?? 0; position.left += offset?.left ?? 0; }; const scrollable = options._scrollable; const start = { top: scrollable[MC.S_SCROLL_TOP], left: scrollable[MC.S_SCROLL_LEFT], }; let end = getEndPosition(scrollable, start, options._target); applyOffset(end, options._offset); if (!arePositionsDifferent(start, end) && options._altTarget) { end = getEndPosition(scrollable, start, options._altTarget); applyOffset(end, options._altOffset); } return { _start: start, _end: end }; }; // must be called in "measure time" const getEndPosition = ( scrollable: Element, startPosition: ScrollPosition, targetCoordinates: TargetCoordinates, ): ScrollPosition => { // by default no change in scroll top or left const endPosition = MH.copyObject(startPosition); if (!MH.isNullish(targetCoordinates?.top)) { if (MH.isFunction(targetCoordinates.top)) { endPosition.top = targetCoordinates.top(scrollable); } else { endPosition.top = targetCoordinates.top; } } if (!MH.isNullish(targetCoordinates?.left)) { if (MH.isFunction(targetCoordinates.left)) { endPosition.left = targetCoordinates.left(scrollable); } else { endPosition.left = targetCoordinates.left; } } // Set boundaries const scrollH = scrollable[MC.S_SCROLL_HEIGHT]; const scrollW = scrollable[MC.S_SCROLL_WIDTH]; const clientH = getClientHeightNow(scrollable); const clientW = getClientWidthNow(scrollable); endPosition.top = MH.min(scrollH - clientH, endPosition.top); endPosition.top = MH.max(0, endPosition.top); endPosition.left = MH.min(scrollW - clientW, endPosition.left); endPosition.left = MH.max(0, endPosition.left); return endPosition; }; const initiateScroll = async ( options: ScrollToOptionsInternal, isCancelled: () => boolean, ) => { const position = await getStartEndPosition(options); const duration = options._duration; const scrollable = options._scrollable; const existingScrollInfo = currentScrollInfos.get(scrollable); const currentPosition = existingScrollInfo?._position ?? position._start; const currentVelocity = existingScrollInfo?._velocity ?? { [MC.S_TOP]: 0, [MC.S_LEFT]: 0, }; let elapsed = existingScrollInfo?._elapsed; const logger = debug ? new debug.Logger({ name: `scroll-${formatAsString(scrollable)}-${randId()}`, logAtCreation: { options, position, elapsed, currentPosition: MH.copyObject(currentPosition), currentVelocity: MH.copyObject(currentVelocity), }, }) : null; for await (elapsed of newAnimationFrameIterator(elapsed)) { const deltaTime = elapsed.sinceLast; if (deltaTime === 0) { // First time continue; } // Element.scrollTo equates to a measurement and needs to run after // painting to avoid forced layout. await waitForMeasureTime(); if (isCancelled()) { // Reject the promise logger?.debug8("Cancelled"); throw currentPosition; } for (const s of [MC.S_LEFT, MC.S_TOP] as const) { const { l, v } = criticallyDamped({ l: currentPosition[s], v: currentVelocity[s], lTarget: position._end[s], dt: deltaTime, lag: duration, }); currentPosition[s] = l; currentVelocity[s] = v; } updateCurrentScrollInfo(scrollable, { _position: currentPosition, _velocity: currentVelocity, _elapsed: elapsed, }); const isDone = !arePositionsDifferent(currentPosition, position._end, 0.5); if (isDone) { MH.assign(currentPosition, position._end); // use exact final coordinates } MH.elScrollTo(scrollable, currentPosition); if (isDone) { logger?.debug8("Done"); break; } } return currentPosition; }; // ------------------------------ let mainContentElement: HTMLElement; let mainScrollableElement: HTMLElement; let initPromise: Promise<void> | null = null; const init = (): Promise<void> => { if (!initPromise) { initPromise = (async () => { const mainScrollableElementSelector = settings.mainScrollableElementSelector; const contentElement = await waitForElementOrInteractive(() => { return mainScrollableElementSelector ? MH.docQuerySelector(mainScrollableElementSelector) : MH.getBody(); // default if no selector }); // defaults mainScrollableElement = getDefaultScrollingElement(); mainContentElement = MH.getBody(); if (!contentElement) { logError( MH.usageError( `No match for '${mainScrollableElementSelector}'. ` + "Scroll tracking/capturing may not work as intended.", ), ); } else if (!MH.isHTMLElement(contentElement)) { logWarn("mainScrollableElementSelector should point to an HTMLElement"); } else if (contentElement !== mainContentElement) { mainScrollableElement = mainContentElement = contentElement; } })(); } return initPromise; }; // Try to find the main scrollable/content elements asap so that tryGetMain* // can return them if called before fetchMain* if (MH.hasDOM()) { waitForInteractive().then(init); } |