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 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 | 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 5x 6x 68x 168x 168x 168x 168x 18x 18x 168x 87x 1x 86x 86x 86x 86x 74x 86x 313x 313x 313x 142x 313x 86x 159x 159x 159x 159x 159x 25x 159x 159x 159x 86x 163x 159x 159x 159x 159x 159x 159x 9x 150x 150x 150x 23x 150x 150x 66x 66x 66x 66x 150x 122x 150x 150x 50x 50x 86x 15x 15x 15x 15x 14x 14x 3x 86x 25x 25x 25x 25x 25x 25x 13x 25x 21x 21x 21x 21x 86x 23x 23x 23x 23x 23x 23x 23x 63x 63x 63x 39x 24x 24x 23x 23x 23x 49x 23x 6x 6x 6x 17x 17x 17x 17x 11x 11x 6x 7x 7x 17x 17x 6x 6x 6x 4x 2x 2x 17x 17x 86x 82x 82x 82x 82x 82x 82x 82x 223x 223x 223x 22x 22x 201x 201x 201x 114x 114x 87x 86x 9x 9x 86x 17x 1x 16x 16x 16x 16x 16x 4x 2x 2x 12x 4x 2x 2x 8x 1x 7x 4x 3x 15x 15x 86x 32x 86x 18x 18x 86x 86x 26x 13x 26x 86x 7x 4x 7x 86x 137x 86x 8x 94x 94x 94x 94x 236x 236x 94x 94x 94x 178x 175x 174x 94x 270x 94x 286x 286x 286x 286x 286x 286x 286x 286x 158x 128x 84x 128x 63x 286x 94x 313x 120x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 94x 13x 13x 4x 4x 13x 13x 13x 94x 174x 21x 153x 94x 161x | /** * @module Watchers/ScrollWatcher */ import * as MC from "@lisn/globals/minification-constants"; import * as MH from "@lisn/globals/minification-helpers"; import { XYDirection, ScrollDirection, SizeTarget } from "@lisn/globals/types"; import { ScrollTarget, TargetCoordinate, TargetCoordinates, CommaSeparatedStr, } from "@lisn/globals/types"; import { setNumericStyleJsVars } from "@lisn/utils/css-alter"; import { getMaxDeltaDirection } from "@lisn/utils/directions"; import { moveElement, tryWrapContent } from "@lisn/utils/dom-alter"; import { waitForMeasureTime } from "@lisn/utils/dom-optimize"; import { addEventListenerTo, removeEventListenerFrom } from "@lisn/utils/event"; import { logError } from "@lisn/utils/log"; import { toNonNegNum, maxAbs } from "@lisn/utils/math"; import { scrollTo, getCurrentScrollAction, getClientWidthNow, getClientHeightNow, tryGetMainScrollableElement, fetchMainContentElement, fetchMainScrollableElement, fetchScrollableElement, isValidScrollDirection, ScrollAction, ScrollToOptions, } from "@lisn/utils/scroll"; import { objToStrKey } from "@lisn/utils/text"; import { validateStrList } from "@lisn/utils/validation"; import { CallbackHandler, Callback, wrapCallback, } from "@lisn/modules/callback"; import { newXWeakMap } from "@lisn/modules/x-map"; import { MutationOperation, DOMWatcher } from "@lisn/watchers/dom-watcher"; import { SizeWatcher } from "@lisn/watchers/size-watcher"; import debug from "@lisn/debug/debug"; // re-export for convenience export type { ScrollAction, ScrollToOptions } from "@lisn/utils/scroll"; /** * {@link ScrollWatcher} listens for scroll events in any direction. * * It manages registered callbacks globally and reuses event listeners for more * efficient performance. */ export class ScrollWatcher { /** * Call the given handler whenever the given scrollable is scrolled. * * Unless {@link OnScrollOptions.skipInitial} is true, the handler is also * called (almost) immediately with the latest scroll data. If a scroll has * not yet been observed on the scrollable and its `scrollTop` and * `scrollLeft` are 0, then the direction is {@link Types.NoDirection} and * the handler is only called if {@link Types.NoDirection} is part of the * supplied {@link OnScrollOptions.directions | options.directions} (or * {@link OnScrollOptions.directions | options.directions} is not given). * * **IMPORTANT:** The same handler can _not_ be added multiple times for the * same scrollable, even if the options differ. If the handler has already * been added for this scrollable, either using {@link trackScroll} or using * {@link onScroll}, then it will be removed and re-added with the current * options. So if previously it was also tracking content size changes using * {@link trackScroll}, it will no longer do so. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the options are invalid. */ readonly onScroll: ( handler: OnScrollHandler, options?: OnScrollOptions, ) => Promise<void>; /** * Removes a previously added handler. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the scrollable is invalid. */ readonly offScroll: ( handler: OnScrollHandler, scrollable?: ScrollTarget, ) => void; /** * This everything that {@link onScroll} does plus more: * * In addition to a scroll event, the handler is also called when either the * offset size or scroll (content) size of the scrollable changes as that * would affect its `scrollTopFraction` and `scrollLeftFraction` and possibly * the `scrollTop` and `scrollLeft` as well. * * **IMPORTANT:** The same handler can _not_ be added multiple times for the * same scrollable, even if the options differ. If the handler has already * been added for this scrollable, either using {@link trackScroll} or using * {@link onScroll}, then it will be removed and re-added with the current * options. * * ------ * * If `handler` is not given, then it defaults to an internal handler that * updates a set of CSS variables on the scrollable element's style: * * - If {@link OnScrollOptions.scrollable | options.scrollable} is not given, * or is `null`, `window` or `document`, the following CSS variables are * set on the root (`html`) element and represent the scroll of the * {@link Settings.settings.mainScrollableElementSelector | the main scrolling element}: * - `--lisn-js--page-scroll-top` * - `--lisn-js--page-scroll-top-fraction` * - `--lisn-js--page-scroll-left` * - `--lisn-js--page-scroll-left-fraction` * - `--lisn-js--page-scroll-width` * - `--lisn-js--page-scroll-height` * * - Otherwise, the following variables are set on the scrollable itself, * and represent its scroll offset: * - `--lisn-js--scroll-top` * - `--lisn-js--scroll-top-fraction` * - `--lisn-js--scroll-left` * - `--lisn-js--scroll-left-fraction` * - `--lisn-js--scroll-width` * - `--lisn-js--scroll-height` * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the options are invalid. */ readonly trackScroll: ( handler?: OnScrollHandler | null, options?: OnScrollOptions, ) => Promise<void>; /** * Removes a previously added handler for {@link trackScroll}. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the scrollable is invalid. */ readonly noTrackScroll: ( handler?: OnScrollHandler | null, scrollable?: ScrollTarget, ) => void; /** * Get the scroll offset of the given scrollable. By default, it will * {@link waitForMeasureTime} and so will be delayed by one frame. * * @param realtime If true, it will not {@link waitForMeasureTime}. Use * this only when doing realtime scroll-based animations * as it may cause a forced layout. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the scrollable is invalid. */ readonly fetchCurrentScroll: ( scrollable?: ScrollTarget, realtime?: boolean, ) => Promise<ScrollData>; /** * Scrolls the given scrollable element to in the given direction. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the direction or options are invalid. */ readonly scroll: ( direction: XYDirection, options?: ScrollOptions, ) => Promise<ScrollAction | null>; /** * Scrolls the given scrollable element to the given `to` scrollable. * * Returns `null` if there's an ongoing scroll that is not cancellable. * * Note that if `to` is an element or a selector, then it _must_ be a * descendant of the scrollable element. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the "to" coordinates or options 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`. * @param [options.scrollable] * If not given, it defaults to * {@link Settings.settings.mainScrollableElementSelector | the main scrolling element}. * * @returns `null` if there's an ongoing scroll that is not cancellable, * otherwise a {@link ScrollAction}. */ readonly scrollTo: ( to: TargetCoordinates | Element | string, options?: ScrollToOptions, ) => Promise<ScrollAction | null>; /** * Returns the current {@link ScrollAction} if any. * * @param scrollable If not given, it defaults to * {@link Settings.settings.mainScrollableElementSelector | the main scrolling element} * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the scrollable is invalid. */ readonly fetchCurrentScrollAction: ( scrollable?: Element, ) => Promise<ScrollAction | null>; /** * Cancels the ongoing scroll that's resulting from smooth scrolling * triggered in the past. Does not interrupt or prevent further scrolling. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the scrollable is invalid. * * @param [options.immediate] If true, then it will not use * {@link waitForMeasureTime} or * {@link Utils.waitForMutateTime | waitForMutateTime}. * Warning: this will likely result in forced layout. */ readonly stopUserScrolling: (options?: { scrollable?: ScrollTarget; immediate?: boolean; }) => Promise<void>; /** * Returns the element that holds the main page content. By default it's * `document.body` but is overridden by * {@link Settings.settings.mainScrollableElementSelector}. * * It will wait for the element to be available if not already. */ static fetchMainContentElement(): Promise<HTMLElement> { return fetchMainContentElement(); } /** * Returns the scrollable element that holds the wrapper around the main page * content. By default it's `document.scrollable` (unless `document.body` is * actually scrollable, in which case it will be used) but it will be * different if {@link Settings.settings.mainScrollableElementSelector} is set. * * It will wait for the element to be available if not already. */ static fetchMainScrollableElement(): Promise<HTMLElement> { return fetchMainScrollableElement(); } /** * Creates a new instance of ScrollWatcher with the given * {@link ScrollWatcherConfig}. It does not save it for future reuse. */ static create(config?: ScrollWatcherConfig) { return new ScrollWatcher(getConfig(config), CONSTRUCTOR_KEY); } /** * Returns an existing instance of ScrollWatcher with the given * {@link ScrollWatcherConfig}, 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?: ScrollWatcherConfig) { const myConfig = getConfig(config); const configStrKey = objToStrKey(myConfig); let instance = instances.get(configStrKey); if (!instance) { instance = new ScrollWatcher(myConfig, CONSTRUCTOR_KEY); instances.set(configStrKey, instance); } return instance; } private constructor( config: ScrollWatcherConfigInternal, key: typeof CONSTRUCTOR_KEY, ) { if (key !== CONSTRUCTOR_KEY) { throw MH.illegalConstructorError("ScrollWatcher.create"); } const logger = debug ? new debug.Logger({ name: "ScrollWatcher", logAtCreation: config }) : null; const allScrollData = MH.newWeakMap<Element, ScrollData>(); const activeListeners = MH.newWeakMap< ScrollTarget, { _nRealtime: number } >(); const allCallbacks = newXWeakMap< Element, Map<OnScrollHandler, CallbackEntry> >(() => MH.newMap()); // ---------- const fetchCurrentScroll = async ( element: Element, realtime = false, isScrollEvent = false, ): Promise<ScrollData> => { // The scroll data can change event without a scroll event, e.g. by the // element changing size, so always get the latest here. const previousEventData = allScrollData.get(element); const latestData = await fetchScrollData( element, previousEventData, realtime, ); // If there hasn't been a scroll event, use the old scroll direction if (!isScrollEvent && previousEventData) { latestData.direction = previousEventData.direction; } return latestData; }; // ---------- const createCallback = ( handler: OnScrollHandler, options: OnScrollOptionsInternal, trackType: TrackType, ): 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, _trackType: trackType, _options: options, }; allCallbacks.sGet(element).set(handler, entry); return entry; }; // ---------- const setupOnScroll = async ( handler: OnScrollHandler, userOptions: OnScrollOptions | undefined, trackType: TrackType, ) => { const options = await fetchOnScrollOptions(config, userOptions ?? {}); const element = options._element; // Don't await for the scroll data before creating the callback so that // setupOnScroll and removeOnScroll have the same "timing" and therefore // calling onScroll and offScroll immediately without awaiting removes the // callback. const entry = createCallback(handler, options, trackType); const callback = entry._callback; const eventTarget = options._eventTarget; const scrollData = await fetchCurrentScroll( element, options._debounceWindow === 0, ); if (callback.isRemoved()) { return; } entry._data = scrollData; allScrollData.set(element, scrollData); if (trackType === TRACK_FULL) { await setupSizeTrack(entry); } let listenerOptions = activeListeners.get(eventTarget); if (!listenerOptions) { debug: logger?.debug4("Adding scroll listener", eventTarget); listenerOptions = { _nRealtime: 0 }; activeListeners.set(eventTarget, listenerOptions); // Don't debounce the scroll handler, only the callbacks. addEventListenerTo(eventTarget, MC.S_SCROLL, scrollHandler); } if (options._debounceWindow === 0) { listenerOptions._nRealtime++; } const directions = options._directions; if ( !callback.isRemoved() && !userOptions?.skipInitial && directionMatches(directions, scrollData.direction) ) { debug: logger?.debug5("Calling initially with", element, scrollData); // Use a one-off callback that's not debounced for the initial call. await invokeCallback(wrapCallback(handler), element, scrollData); } }; // ---------- const removeOnScroll = async ( handler: OnScrollHandler, scrollable: ScrollTarget | undefined, trackType: TrackType, ) => { const options = await fetchOnScrollOptions(config, { scrollable }); const element = options._element; const currEntry = allCallbacks.get(element)?.get(handler); if (currEntry?._trackType === trackType) { MH.remove(currEntry._callback); if (handler === setScrollCssProps) { // delete the properties setScrollCssProps(element, null); } } }; // ---------- const deleteHandler = ( handler: OnScrollHandler, options: OnScrollOptionsInternal, ) => { const element = options._element; const eventTarget = options._eventTarget; MH.deleteKey(allCallbacks.get(element), handler); allCallbacks.prune(element); const listenerOptions = activeListeners.get(eventTarget); if (listenerOptions && options._debounceWindow === 0) { listenerOptions._nRealtime--; } if (!allCallbacks.has(element)) { debug: logger?.debug4( "No more callbacks for scrollable; removing listener", element, ); MH.deleteKey(allScrollData, element); removeEventListenerFrom(eventTarget, MC.S_SCROLL, scrollHandler); MH.deleteKey(activeListeners, eventTarget); // TODO: Should we unwrap children if previously WE wrapped them? } }; // ---------- const setupSizeTrack = async (entry: CallbackEntry) => { const options = entry._options; const element = options._element; const scrollCallback = entry._callback; debug: logger?.debug8("Setting up size tracking", element); const doc = MH.getDoc(); const docScrollingElement = MH.getDocScrollingElement(); const resizeCallback = wrapCallback(async () => { // Get the latest scroll data for the scrollable // Currently, the resize callback is already delayed by a frame due to // the SizeWatcher, so we don't need to treat this as realtime. const latestData = await fetchCurrentScroll(element); const thresholdsExceeded = hasExceededThreshold( options, latestData, entry._data, ); if (!thresholdsExceeded) { debug: logger?.debug9( "Threshold not exceeded", options, latestData, entry._data, ); } else if (!scrollCallback.isRemoved()) { await invokeCallback(scrollCallback, element, latestData); } }); scrollCallback.onRemove(resizeCallback.remove); // Don't use default instance as it has a high threshold. const sizeWatcher = SizeWatcher.reuse(); const setupOnResize = (target?: SizeTarget) => sizeWatcher.onResize(resizeCallback, { target, [MC.S_DEBOUNCE_WINDOW]: options._debounceWindow, // TODO maybe accepts resizeThreshold option threshold: options._threshold, }); if (element === docScrollingElement) { // In case we're tracking the main document scroll, then we only need to // observe the viewport size and the size of the documentElement (which is // the content size). setupOnResize(); // viewport size setupOnResize(doc); // content size return; } // ResizeObserver only detects changes in offset width/height which is // the visible size of the scrolling element, and that is not affected by the // size of its content. // But we also need to detect changes in the scroll width/height which is // the size of the content. // We also need to keep track of elements being added to the scrollable element. const observedElements = MH.newSet<Element>([element]); // Observe the scrolling element setupOnResize(element); // And also its children (if possible, a single wrapper around them const wrapper = await tryWrapContent(element, { _classNames: [ MC.PREFIX_WRAPPER, MC.PREFIX_WRAPPER_CONTENT, PREFIX_WRAPPER, ], }); if (wrapper) { setupOnResize(wrapper); observedElements.add(wrapper); // } else { for (const child of MH.childrenOf(element)) { setupOnResize(child); observedElements.add(child); } } // Watch for newly added elements const domWatcher = DOMWatcher.create({ root: element, // only direct children subtree: false, }); const onAddedCallback = wrapCallback((operation: MutationOperation) => { const child = MH.currentTargetOf(operation); // If we've just added the wrapper, it will be in DOMWatcher's queue, // so check. if (child !== wrapper) { if (wrapper) { // Move this child into the wrapper. If this results in change of size // for wrapper, SizeWatcher will call us. moveElement(child, { to: wrapper, ignoreMove: true }); } else { // Track the size of this child. // Don't skip initial, call the callback now setupOnResize(child); observedElements.add(child); } } }); domWatcher.onMutation(onAddedCallback, { categories: [MC.S_ADDED] }); resizeCallback.onRemove(onAddedCallback.remove); }; // ---------- const scrollHandler = async (event: Event) => { // We cannot use event.currentTarget because scrollHandler is called inside // a setTimeout so by that time, currentTarget is null or something else. // // However, target and currentTarget only differ when the event is in the // bubbling or capturing phase. Because // // - the scroll event only bubbles when fired on document, and (it only // bubbles up to window) // - and we never attach the listener to the capturing phase // - and we always use document instead of window to listen for scroll on // document // // then event.target suffices. const scrollable = MH.targetOf(event); /* istanbul ignore next */ if (!scrollable || !(MH.isElement(scrollable) || MH.isDoc(scrollable))) { return; } const element = await fetchScrollableElement(scrollable); const realtime = (activeListeners.get(scrollable)?._nRealtime ?? 0) > 0; const latestData = await fetchCurrentScroll(element, realtime, true); allScrollData.set(element, latestData); debug: logger?.debug9("Scroll event", element, latestData); for (const entry of allCallbacks.get(element)?.values() || []) { // Consider the direction since the last scroll event and not the // direction based on the largest delta the last time the callback // was called. const options = entry._options; const thresholdsExceeded = hasExceededThreshold( options, latestData, entry._data, ); if (!thresholdsExceeded) { debug: logger?.debug9( "Threshold not exceeded", options, latestData, entry._data, ); continue; } // If threshold has been exceeded, always update the latest data for // this callback. const prevData = entry._data; entry._data = latestData; if (!directionMatches(options._directions, latestData.direction)) { debug: logger?.debug9( "Direction does not match", options, latestData, ); continue; } invokeCallback(entry._callback, element, latestData, prevData); } }; // ---------- this.fetchCurrentScroll = (scrollable?, realtime?) => fetchScrollableElement(scrollable).then((element) => fetchCurrentScroll(element, realtime), ); // ---------- this.scroll = (direction, options) => { if (!isValidScrollDirection(direction)) { throw MH.usageError(`Unknown scroll direction: '${direction}'`); } const isVertical = direction === MC.S_UP || direction === MC.S_DOWN; const sign = direction === MC.S_UP || direction === MC.S_LEFT ? -1 : 1; let targetCoordinate: TargetCoordinate; const amount = options?.amount ?? 100; const asFractionOf = options?.asFractionOf; if (asFractionOf === "visible") { targetCoordinate = isVertical ? (el) => el[MC.S_SCROLL_TOP] + (sign * amount * getClientHeightNow(el)) / 100 : (el) => el[MC.S_SCROLL_LEFT] + (sign * amount * getClientWidthNow(el)) / 100; // } else if (asFractionOf === "content") { targetCoordinate = isVertical ? (el) => el[MC.S_SCROLL_TOP] + (sign * amount * el[MC.S_SCROLL_HEIGHT]) / 100 : (el) => el[MC.S_SCROLL_LEFT] + (sign * amount * el[MC.S_SCROLL_WIDTH]) / 100; // } else if (asFractionOf !== undefined && asFractionOf !== "pixel") { throw MH.usageError( `Unknown 'asFractionOf' keyword: '${asFractionOf}'`, ); // } else { targetCoordinate = isVertical ? (el) => el[MC.S_SCROLL_TOP] + sign * amount : (el) => el[MC.S_SCROLL_LEFT] + sign * amount; } const target = isVertical ? { top: targetCoordinate } : { left: targetCoordinate }; return this.scrollTo(target, options); }; // ---------- this.scrollTo = async (to, options) => scrollTo( to, MH.merge(options, { duration: options?.duration ?? config._scrollDuration, // default scrollable: await fetchScrollableElement(options?.scrollable), // override }), ); // ---------- this.fetchCurrentScrollAction = (scrollable?) => fetchScrollableElement(scrollable).then((element) => getCurrentScrollAction(element), ); // ---------- this.stopUserScrolling = async (options) => { const element = await fetchScrollableElement(options?.scrollable); const stopScroll = () => MH.elScrollTo(element, { top: element[MC.S_SCROLL_TOP], left: element[MC.S_SCROLL_LEFT], }); if (options?.immediate) { stopScroll(); } else { waitForMeasureTime().then(stopScroll); } }; // ---------- this.trackScroll = (handler?, options?) => { if (!handler) { handler = setScrollCssProps; } return setupOnScroll(handler, options, TRACK_FULL); }; // ---------- this.noTrackScroll = (handler?, scrollable?) => { if (!handler) { handler = setScrollCssProps; } removeOnScroll(handler, scrollable, TRACK_FULL); // no need to await }; // ---------- this.onScroll = (handler, options?) => setupOnScroll(handler, options, TRACK_REGULAR); // ---------- this.offScroll = (handler, scrollable?) => { removeOnScroll(handler, scrollable, TRACK_REGULAR); // no need to await }; } } /** * @interface */ export type ScrollWatcherConfig = { /** * The default value for * {@link OnScrollOptions.debounceWindow | debounceWindow} in calls to * {@link ScrollWatcher.onScroll}. * * @defaultValue 75 */ debounceWindow?: number; /** * The default value for * {@link OnScrollOptions.threshold | threshold} in calls to * {@link ScrollWatcher.onScroll}. * * @defaultValue 50 */ scrollThreshold?: number; /** * The default value for * {@link ScrollOptions.duration | duration} in calls to * {@link ScrollWatcher.scroll} and {@link ScrollWatcher.scrollTo}. * * @defaultValue 1000 */ scrollDuration?: number; }; /** * @interface */ export type OnScrollOptions = { /** * If it is not given, or is `null`, `window` or `document`, then it will * track the scroll of the * {@link Settings.settings.mainScrollableElementSelector | the main scrolling element}. * * Other values must be an `Element` and are taken literally. * * @defaultValue undefined */ scrollable?: ScrollTarget; /** * If non-0, the scroll handler will only be called when the scrollable's * scroll offset in the observed direction has changed at least * `scrollThreshold` pixels since the last time the handler was called. * * @defaultValue {@link ScrollWatcherConfig.scrollThreshold} */ threshold?: number; /** * Specifies a list of {@link ScrollDirection}s to listen for. * * It can be a comma-separated list of direction names or an array of such * names. * * If not given, then it listens for scrolls in any direction, including * {@link Types.NoDirection} and {@link Types.AmbiguousDirection}. * * The {@link Types.NoDirection} occurs when the callback is called initially * (if `skipInitial` is not `true`) and there hasn't yet been a scroll * observed on the scrollable _and_ it's `scrollTop`/`scrollLeft` are 0. * * The {@link Types.AmbiguousDirection} occurs when the user scrolls * diagonally with close to equal deltas in both horizontal and vertical * direction. * * **IMPORTANT:** * * The direction of a scroll event is always based on comparing `deltaX` and * `deltaY` relative to the _last scroll event_ (within the `debounceWindow`, * and not to the scroll data for the last time the callback was called (in * case it was skipped because `threshold` was not exceeded or in case it was * debounced by a larger window than the watcher). * * I.e. if you have both `threshold` and `directions` restricted, or if the * callback has a larger debounce window than the watcher, it is possible for * there to be a change in the relevant `scrollTop`/`scrollLeft` offset that * exceeds the threshold, and for the callback to _not_ be called. * * For a callback to be called, both of these must be true: * - the change in `scrollTop`/`scrollLeft`, _compared to the last time the * callback was called_ must exceed the {@link threshold} * - the effective scroll direction, _compared to the last scroll event_ * prior to the _watcher's_ debounce window must be one of the given * {@link directions}. * * @defaultValue undefined */ directions?: CommaSeparatedStr<ScrollDirection> | ScrollDirection[]; /** * Do not call the handler until there's a future scroll of the element. * * By default we call the handler (almost) immediately if there's been a * scroll in one of the given directions, or if there has not been a scroll * but directions includes {@link Types.NoDirection}, but you can disable * this initial call here. * * @defaultValue false */ skipInitial?: boolean; /** * If non-0, the handler will be "debounced" so it's called at most * `debounceWindow` milliseconds. * * **IMPORTANT:** * If the debounce window is non-0 (default), then the callback is always * delayed by at least an animation frame following a scroll event to allow * for optimized `scrollTop`/`scrollLeft` measurements via * {@link waitForMeasureTime}. * * If you set this is 0, this indicates that the callback should be * "realtime" and will therefore skip {@link waitForMeasureTime}, which could * lead to forced re-layouts, but you probably need this when doing * scroll-based animations. * * @defaultValue {@link ScrollWatcherConfig.debounceWindow} */ debounceWindow?: number; }; /** * @interface */ export type ScrollOptions = ScrollToOptions & { /** * How much to scroll in the given direction. * * @defaultValue 100 */ amount?: number; /** * If set to "pixel" (default), `amount` is taken as absolute pixels. * * If set to "visible", `amount` is taken as percent of the element's visible * size in the scrolling direction (100 means full client width for * horizontal or height for vertical scroll). * * If set to "content", `amount` is taken as percent of the element's full * content size in the scrolling direction (100 means full scroll width for * horizontal or height for vertical scroll). * * @defaultValue "pixel" */ asFractionOf?: "pixel" | "visible" | "content"; }; /** * The handler is invoked with three arguments: * * - The element that has been resized. * - The latest {@link ScrollData} for the element. * - (since v1.3.0) The {@link ScrollData} for the element when the thresholds * for this callback were last exceeded. If the callback is called for any * scroll direction, then this will be the data when it was last invoked. Will * be `undefined` the first time. */ export type OnScrollHandlerArgs = [Element, ScrollData, ScrollData | undefined]; export type OnScrollCallback = Callback<OnScrollHandlerArgs>; export type OnScrollHandler = | CallbackHandler<OnScrollHandlerArgs> | OnScrollCallback; export type ScrollData = { clientWidth: number; clientHeight: number; scrollWidth: number; scrollHeight: number; scrollTop: number; /** * This is the `scrollTop` relative to the full `scrollHeight` minus the * `clientHeight`, ranging from 0 to 1. */ scrollTopFraction: number; scrollLeft: number; /** * This is the `scrollLeft` relative to the full `scrollWidth` minus the * `clientWidth`, ranging from 0 to 1. */ scrollLeftFraction: number; /** * This is the direction of the last scroll action, i.e. _compared to the * last scroll event_, not necessarily based on the deltas compared to the * last time this callback was called. */ direction: ScrollDirection; }; // ---------------------------------------- type ScrollWatcherConfigInternal = { _debounceWindow: number; _scrollThreshold: number; _scrollDuration: number; }; type OnScrollOptionsInternal = { _element: Element; _eventTarget: ScrollTarget; _directions: ScrollDirection[] | null; _threshold: number; _debounceWindow: number; }; type CallbackEntry = { _callback: OnScrollCallback; _trackType: TrackType; _options: OnScrollOptionsInternal; _data?: ScrollData; }; type TrackType = typeof TRACK_REGULAR | typeof TRACK_FULL; const CONSTRUCTOR_KEY: unique symbol = MC.SYMBOL() as typeof CONSTRUCTOR_KEY; const instances = MH.newMap<string, ScrollWatcher>(); const PREFIX_WRAPPER = MH.prefixName("scroll-watcher-wrapper"); const getConfig = ( config: ScrollWatcherConfig | undefined, ): ScrollWatcherConfigInternal => { config ??= {}; return { _debounceWindow: toNonNegNum(config[MC.S_DEBOUNCE_WINDOW], 75), // If threshold is 0, internally treat as 1 (pixel) _scrollThreshold: toNonNegNum(config.scrollThreshold, 50) || 1, _scrollDuration: toNonNegNum(config.scrollDuration, 1000), }; }; const TRACK_REGULAR = 1; // only scroll events const TRACK_FULL = 2; // scroll + resizing of content and/or wrapper // -------------------- const fetchOnScrollOptions = async ( config: ScrollWatcherConfigInternal, options: OnScrollOptions, ): Promise<OnScrollOptionsInternal> => { const directions = validateStrList("directions", options.directions, isValidScrollDirection) || null; const element = await fetchScrollableElement(options.scrollable); return { _element: element, _eventTarget: getEventTarget(element), _directions: directions, // If threshold is 0, internally treat as 1 (pixel) _threshold: toNonNegNum(options.threshold, config._scrollThreshold) || 1, _debounceWindow: options[MC.S_DEBOUNCE_WINDOW] ?? config._debounceWindow, }; }; const directionMatches = ( userDirections: ScrollDirection[] | null, latestDirection: ScrollDirection, ) => !userDirections || MH.includes(userDirections, latestDirection); const hasExceededThreshold = ( options: OnScrollOptionsInternal, latestData: ScrollData, lastThresholdData: ScrollData | undefined, ): boolean => { const directions = options._directions; const threshold = options._threshold; Iif (!lastThresholdData) { /* istanbul ignore */ return false; } const topDiff = maxAbs( latestData[MC.S_SCROLL_TOP] - lastThresholdData[MC.S_SCROLL_TOP], latestData[MC.S_SCROLL_HEIGHT] - lastThresholdData[MC.S_SCROLL_HEIGHT], latestData[MC.S_CLIENT_HEIGHT] - lastThresholdData[MC.S_CLIENT_HEIGHT], ); const leftDiff = maxAbs( latestData[MC.S_SCROLL_LEFT] - lastThresholdData[MC.S_SCROLL_LEFT], latestData[MC.S_SCROLL_WIDTH] - lastThresholdData[MC.S_SCROLL_WIDTH], latestData[MC.S_CLIENT_WIDTH] - lastThresholdData[MC.S_CLIENT_WIDTH], ); // If the callback is only interested in up/down, then only check the // scrollTop delta, and similarly for left/right. let checkTop = false, checkLeft = false; if ( !directions || MH.includes(directions, MC.S_NONE) || MH.includes(directions, MC.S_AMBIGUOUS) ) { checkTop = checkLeft = true; } else { if ( MH.includes(directions, MC.S_UP) || MH.includes(directions, MC.S_DOWN) ) { checkTop = true; } if ( MH.includes(directions, MC.S_LEFT) || MH.includes(directions, MC.S_RIGHT) ) { checkLeft = true; } } return ( (checkTop && topDiff >= threshold) || (checkLeft && leftDiff >= threshold) ); }; const fetchScrollData = async ( element: Element, previousEventData: ScrollData | undefined, realtime: boolean, ): Promise<ScrollData> => { if (!realtime) { await waitForMeasureTime(); } const scrollTop = MH.ceil(element[MC.S_SCROLL_TOP]); const scrollLeft = MH.ceil(element[MC.S_SCROLL_LEFT]); const scrollWidth = element[MC.S_SCROLL_WIDTH]; const scrollHeight = element[MC.S_SCROLL_HEIGHT]; const clientWidth = getClientWidthNow(element); const clientHeight = getClientHeightNow(element); const scrollTopFraction = MH.round(scrollTop) / (scrollHeight - clientHeight || MC.INFINITY); const scrollLeftFraction = MH.round(scrollLeft) / (scrollWidth - clientWidth || MC.INFINITY); const prevScrollTop = previousEventData?.scrollTop ?? 0; const prevScrollLeft = previousEventData?.scrollLeft ?? 0; const direction = getMaxDeltaDirection( scrollLeft - prevScrollLeft, scrollTop - prevScrollTop, ); return { direction, [MC.S_CLIENT_WIDTH]: clientWidth, [MC.S_CLIENT_HEIGHT]: clientHeight, [MC.S_SCROLL_WIDTH]: scrollWidth, [MC.S_SCROLL_HEIGHT]: scrollHeight, [MC.S_SCROLL_TOP]: scrollTop, [MC.S_SCROLL_TOP_FRACTION]: scrollTopFraction, [MC.S_SCROLL_LEFT]: scrollLeft, [MC.S_SCROLL_LEFT_FRACTION]: scrollLeftFraction, }; }; const setScrollCssProps = ( element: Element, scrollData: Partial<ScrollData> | undefined | null, ) => { let prefix = ""; if (element === tryGetMainScrollableElement()) { // Set the CSS vars on the root element element = MH.getDocElement(); prefix = "page-"; } scrollData ??= {}; const props = { [MC.S_SCROLL_TOP]: scrollData[MC.S_SCROLL_TOP], [MC.S_SCROLL_TOP_FRACTION]: scrollData[MC.S_SCROLL_TOP_FRACTION], [MC.S_SCROLL_LEFT]: scrollData[MC.S_SCROLL_LEFT], [MC.S_SCROLL_LEFT_FRACTION]: scrollData[MC.S_SCROLL_LEFT_FRACTION], [MC.S_SCROLL_WIDTH]: scrollData[MC.S_SCROLL_WIDTH], [MC.S_SCROLL_HEIGHT]: scrollData[MC.S_SCROLL_HEIGHT], }; setNumericStyleJsVars(element, props, { _prefix: prefix }); }; const getEventTarget = (element: Element): ScrollTarget => { if (element === MH.getDocScrollingElement()) { return MH.getDoc(); } return element; }; const invokeCallback = ( callback: OnScrollCallback, element: Element, scrollData: ScrollData, lastScrollData?: ScrollData, ) => callback .invoke( element, MH.copyObject(scrollData), lastScrollData, // no need to copy that one as it's not used again ) .catch(logError); |