All files / watchers gesture-watcher.ts

99.59% Statements 247/248
96.77% Branches 120/124
100% Functions 32/32
99.57% Lines 234/235

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        94x 94x                 94x         94x 94x           94x   94x   94x             94x 94x 94x 94x 94x 94x           94x 94x   94x         94x     94x                     94x                                                                                                                                   188x                     62x 62x   62x 62x 9x 9x     62x             198x 1x     197x       197x                   248x       197x     243x       197x         249x   249x 249x           249x   249x           249x             197x         258x 249x   249x 959x 959x 1x           958x           958x 958x     959x 959x 935x             197x         14x 14x   14x 41x 41x 41x 41x 41x     41x 40x         40x 40x               197x           480x   480x 480x 481x       480x         197x         958x 958x 958x   958x         238x   238x 720x 239x 233x     239x 228x 228x       958x           1474x 1474x 2018x 2018x             958x 966x   958x 250x           958x 210x   958x 48x   958x 210x 210x 210x     958x 480x 480x 8x 8x       958x   958x       40x 40x 9x     40x   40x 9x       40x 40x             197x 5x 5x   5x 20x                 5x         197x 2x 2x     2x 8x       2x         197x       197x 11x 11x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       94x 94x   94x     250x 250x                         94x                             94x                                                   94x             94x       258x       258x         258x                                                               94x         249x 249x 249x         249x   249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x         249x 249x           249x               249x             389x       389x 389x 389x 389x   389x     18x     18x     371x 371x   371x         371x         371x         371x         4x     367x 367x 367x   367x 367x   367x     367x                         367x         165x   202x                 249x           481x   481x               481x     647x     481x 467x           481x   76x 76x 405x   8x 8x 8x     397x     22x 22x 22x       397x           397x     249x     94x 379x 379x     94x 467x 467x   467x   467x             390x   390x   16x         94x       28x   28x 7x     21x   21x 7x                     14x                        
/**
 * @module Watchers/GestureWatcher
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import {
  Direction,
  GestureIntent,
  GestureDevice,
  CommaSeparatedStr,
} from "@lisn/globals/types";
 
import {
  addClasses,
  removeClasses,
  setNumericStyleJsVars,
} from "@lisn/utils/css-alter";
import { isValidDirection } from "@lisn/utils/directions";
import {
  addEventListenerTo,
  removeEventListenerFrom,
  preventSelect,
  undoPreventSelect,
} from "@lisn/utils/event";
import { getDebouncedHandler } from "@lisn/utils/tasks";
 
import { addDeltaZ } from "@lisn/utils/gesture";
 
import {
  isValidInputDevice,
  isValidIntent,
  GestureFragment,
  DEVICES,
  INTENTS,
} from "@lisn/utils/gesture";
import { getKeyGestureFragment } from "@lisn/utils/gesture-key";
import { getPointerGestureFragment } from "@lisn/utils/gesture-pointer";
import { getTouchGestureFragment } from "@lisn/utils/gesture-touch";
import { getWheelGestureFragment } from "@lisn/utils/gesture-wheel";
import { logError } from "@lisn/utils/log";
import {
  maxAbs,
  toNonNegNum,
  toPosNum,
  toNumWithBounds,
} from "@lisn/utils/math";
import { randId, 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 { LoggerInterface } from "@lisn/debug/types";
import debug from "@lisn/debug/debug";
 
/**
 * {@link GestureWatcher} listens for user gestures resulting from wheel,
 * pointer, touch or key input events.
 *
 * It supports scroll, zoom or drag type gestures.
 *
 * It manages registered callbacks globally and reuses event listeners for more
 * efficient performance.
 */
export class GestureWatcher {
  /**
   * Call the given handler whenever the user performs a gesture on the target
   * matching the given options.
   *
   * **IMPORTANT:** The same handler can _not_ be added multiple times for the
   * same event target, even if the options differ. If the handler has already
   * been added for this target, either using {@link onGesture} or
   * {@link trackGesture}, then it will be removed and re-added with the
   * current options.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the options are invalid.
   */
  readonly onGesture: (
    target: EventTarget,
    handler: OnGestureHandler,
    options?: OnGestureOptions,
  ) => Promise<void>;
 
  /**
   * Removes a previously added handler.
   */
  readonly offGesture: (target: EventTarget, handler: OnGestureHandler) => void;
 
  /**
   * This is the same as {@link onGesture} except that if `handler` is not
   * given, then it defaults to an internal handler that updates a set of CSS
   * variables on the target's style:
   *
   *   - `--lisn-js--<Intent>-delta-x`
   *   - `--lisn-js--<Intent>-delta-y`
   *   - `--lisn-js--<Intent>-delta-z`
   *
   * where and `<Intent>` is one of {@link GestureIntent} and the delta X, Y
   * and Z are the _total summed up_ `deltaX`, `deltaY` and `deltaZ` since the
   * callback was added, summed over all devices used (key, touch, etc).
   *
   * **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 trackGesture} or using
   * {@link onGesture}, then it will be removed and re-added with the current
   * options.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the options are invalid.
   */
  readonly trackGesture: (
    element: Element,
    handler?: OnGestureHandler | null,
    options?: OnGestureOptions,
  ) => Promise<void>;
 
  /**
   * Removes a previously added handler for {@link trackGesture}.
   */
  readonly noTrackGesture: (
    element: Element,
    handler?: OnGestureHandler | null,
  ) => void;
 
  /**
   * Creates a new instance of GestureWatcher with the given
   * {@link GestureWatcherConfig}. It does not save it for future reuse.
   */
  static create(config?: GestureWatcherConfig) {
    return new GestureWatcher(getConfig(config), CONSTRUCTOR_KEY);
  }
 
  /**
   * Returns an existing instance of GestureWatcher with the given
   * {@link GestureWatcherConfig}, 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?: GestureWatcherConfig) {
    const myConfig = getConfig(config);
    const configStrKey = objToStrKey(myConfig);
 
    let instance = instances.get(configStrKey);
    if (!instance) {
      instance = new GestureWatcher(myConfig, CONSTRUCTOR_KEY);
      instances.set(configStrKey, instance);
    }
 
    return instance;
  }
 
  private constructor(
    config: GestureWatcherConfigInternal,
    key: typeof CONSTRUCTOR_KEY,
  ) {
    if (key !== CONSTRUCTOR_KEY) {
      throw MH.illegalConstructorError("GestureWatcher.create");
    }
 
    const logger = debug
      ? new debug.Logger({ name: "GestureWatcher", logAtCreation: config })
      : null;
 
    const allCallbacks = newXWeakMap<
      EventTarget,
      Map<
        OnGestureHandler,
        {
          _callback: OnGestureCallback;
          _wrapper: OnGestureHandlerWrapper;
          _options: OnGestureOptionsInternal;
        }
      >
    >(() => MH.newMap());
 
    // For each target and event type, add only 1 global listener that will then
    // manage the event queues and callbacks.
    const allListeners = newXWeakMap<
      EventTarget,
      Map<GestureDevice, DeviceListeners>
    >(() => MH.newMap());
 
    // ----------
 
    const createCallback = (
      target: EventTarget,
      handler: OnGestureHandler,
      options: OnGestureOptionsInternal,
    ): OnGestureCallback => {
      MH.remove(allCallbacks.get(target)?.get(handler)?._callback);
 
      debug: logger?.debug5("Adding/updating handler for", options);
      const { _callback, _wrapper } = getCallbackAndWrapper(
        handler,
        options,
        logger,
      );
 
      _callback.onRemove(() => deleteHandler(target, handler, options));
 
      allCallbacks.sGet(target).set(handler, {
        _callback,
        _wrapper,
        _options: options,
      });
 
      return _callback;
    };
 
    // ----------
 
    // async for consistency with other watchers and future compatibility in
    // case of change needed
    const setupOnGesture = async (
      target: EventTarget,
      handler: OnGestureHandler,
      userOptions: OnGestureOptions | undefined,
    ) => {
      const options = getOptions(config, userOptions ?? {});
      createCallback(target, handler, options);
 
      for (const device of options._devices ?? DEVICES) {
        let listeners = allListeners.get(target)?.get(device);
        if (listeners) {
          debug: logger?.debug4(
            `Listeners already added for ${device}`,
            target,
            options,
          );
        } else {
          debug: logger?.debug4(
            `Adding listeners for ${device}`,
            target,
            options,
          );
 
          listeners = setupListeners(target, device, options);
          allListeners.sGet(target).set(device, listeners);
        }
 
        listeners._nCallbacks++;
        if (options._preventDefault) {
          listeners._nPreventDefault++;
        }
      }
    };
 
    // ----------
 
    const deleteHandler = (
      target: EventTarget,
      handler: OnGestureHandler,
      options: OnGestureOptionsInternal,
    ) => {
      MH.deleteKey(allCallbacks.get(target), handler);
      allCallbacks.prune(target);
 
      for (const device of options._devices ?? DEVICES) {
        const listeners = allListeners.get(target)?.get(device);
        if (listeners) {
          listeners._nCallbacks--;
          if (options._preventDefault) {
            listeners._nPreventDefault--;
          }
 
          if (!listeners._nCallbacks) {
            debug: logger?.debug4(
              `No more callbacks for target and device ${device}; removing listeners`,
              target,
            );
 
            MH.deleteKey(allListeners.get(target), device);
            listeners._remove();
          }
        }
      }
    };
 
    // ----------
 
    const invokeCallbacks = (
      target: EventTarget,
      device: GestureDevice,
      event: Event,
    ): boolean /* true if terminated */ => {
      const preventDefault =
        (allListeners.get(target)?.get(device)?._nPreventDefault ?? 0) > 0;
 
      let isTerminated = false;
      for (const { _wrapper } of allCallbacks.get(target)?.values() || []) {
        isTerminated =
          _wrapper(target, device, event, preventDefault) || isTerminated;
      }
 
      return isTerminated;
    };
 
    // ----------
 
    const setupListeners = (
      target: EventTarget,
      device: GestureDevice,
      options: OnGestureOptionsInternal,
    ): DeviceListeners => {
      const intents = options._intents;
      let hasAddedTabIndex = false;
      let hasPreventedSelect = false;
 
      if (
        device === MC.S_KEY &&
        MH.isElement(target) &&
        !MH.getTabIndex(target)
      ) {
        hasAddedTabIndex = true;
        // enable element to receive keydown events
        MH.setTabIndex(target);
      } else if (MH.isElement(target) && device === MC.S_TOUCH) {
        if (options._preventDefault) {
          addClasses(target, MC.PREFIX_NO_TOUCH_ACTION);
        }
 
        if (!intents || MH.includes(intents, MC.S_DRAG)) {
          hasPreventedSelect = true;
          preventSelect(target);
        }
      }
 
      const addOrRemoveListeners = (
        action: "add" | "remove",
        listener: EventListener,
        eventTypes: readonly (keyof GlobalEventHandlersEventMap)[],
      ) => {
        const method =
          action === "add" ? addEventListenerTo : removeEventListenerFrom;
        for (const eventType of eventTypes) {
          debug: logger?.debug8(`${action} listener for ${eventType}`, target);
          method(target, eventType, listener, {
            passive: false,
            capture: true,
          });
        }
      };
 
      const addInitialListener = () =>
        addOrRemoveListeners("add", initialListener, initiatingEvents[device]);
 
      const removeInitialListener = () =>
        addOrRemoveListeners(
          "remove",
          initialListener,
          initiatingEvents[device],
        );
 
      const addOngoingListener = () =>
        addOrRemoveListeners("add", processEvent, ongoingEvents[device]);
 
      const removeOngoingListener = () =>
        addOrRemoveListeners("remove", processEvent, ongoingEvents[device]);
 
      const initialListener = (event: Event) => {
        processEvent(event);
        removeInitialListener();
        addOngoingListener();
      };
 
      const processEvent = (event: Event) => {
        const isTerminated = invokeCallbacks(target, device, event);
        if (isTerminated) {
          removeOngoingListener();
          addInitialListener();
        }
      };
 
      addInitialListener();
 
      return {
        _nCallbacks: 0,
        _nPreventDefault: 0,
        _remove: () => {
          if (MH.isElement(target)) {
            if (hasAddedTabIndex) {
              MH.unsetTabIndex(target);
            }
 
            removeClasses(target, MC.PREFIX_NO_TOUCH_ACTION);
 
            if (hasPreventedSelect) {
              undoPreventSelect(target);
            }
          }
 
          removeOngoingListener();
          removeInitialListener();
        },
      };
    };
 
    // ----------
 
    this.trackGesture = (element, handler?, options?) => {
      if (!handler) {
        handler = setGestureCssProps;
        // initial values
        for (const intent of INTENTS) {
          setGestureCssProps(element, {
            intent,
            totalDeltaX: 0,
            totalDeltaY: 0,
            totalDeltaZ: 1,
          });
        }
      }
 
      return setupOnGesture(element, handler, options);
    };
 
    // ----------
 
    this.noTrackGesture = (element, handler?) => {
      if (!handler) {
        handler = setGestureCssProps;
 
        // delete the properties
        for (const intent of INTENTS) {
          setGestureCssProps(element, { intent });
        }
      }
 
      this.offGesture(element, handler);
    };
 
    // ----------
 
    this.onGesture = setupOnGesture;
 
    // ----------
 
    this.offGesture = (target, handler) => {
      debug: logger?.debug5("Removing handler");
      MH.remove(allCallbacks.get(target)?.get(handler)?._callback);
    };
  }
}
 
/**
 * @interface
 */
export type GestureWatcherConfig = {
  /**
   * The default value for
   * {@link OnGestureOptions.preventDefault | preventDefault} in calls to
   * {@link GestureWatcher.onGesture}.
   *
   * @defaultValue true
   */
  preventDefault?: boolean;
 
  /**
   * The default value for
   * {@link OnGestureOptions.debounceWindow | debounceWindow} in calls to
   * {@link GestureWatcher.onGesture}.
   *
   * @defaultValue 150
   */
  debounceWindow?: number;
 
  /**
   * The default value for
   * {@link OnGestureOptions.deltaThreshold | deltaThreshold} in calls to
   * {@link GestureWatcher.onGesture}.
   *
   * @defaultValue 5
   */
  deltaThreshold?: number;
 
  /**
   * The default value for
   * {@link OnGestureOptions.angleDiffThreshold | angleDiffThreshold} in calls to
   * {@link GestureWatcher.onGesture}.
   *
   * It does not make much sense to set this to 0.
   *
   * The value is in _degrees_, not radians.
   *
   * @defaultValue 35
   */
  angleDiffThreshold?: number;
 
  /**
   * The default value for
   * {@link OnGestureOptions.naturalTouchScroll | naturalTouchScroll} in calls to
   * {@link GestureWatcher.onGesture}.
   *
   * @defaultValue true
   */
  naturalTouchScroll?: boolean;
 
  /**
   * The default value for
   * {@link OnGestureOptions.touchDragHoldTime | touchDragHoldTime} in calls to
   * {@link GestureWatcher.onGesture}.
   *
   * @defaultValue 500
   */
  touchDragHoldTime?: number;
 
  /**
   * The default value for
   * {@link OnGestureOptions.touchDragNumFingers | touchDragNumFingers} in calls to
   * {@link GestureWatcher.onGesture}.
   *
   * @defaultValue 1
   */
  touchDragNumFingers?: number;
};
 
/**
 * @interface
 */
export type OnGestureOptions = {
  /**
   * One or more device types to listen for. If not specified, then all devices
   * are enabled.
   *
   * It can be a comma-separated list of {@link GestureDevice}s or an array of
   * such devices.
   *
   * @defaultValue undefined
   */
  devices?: CommaSeparatedStr<GestureDevice> | GestureDevice[];
 
  /**
   * If given, callback will only be called if the gesture's direction is one
   * of the given ones.
   *
   * It can be a comma-separated list of {@link Direction}s or an array of such
   * directions.
   *
   * @defaultValue undefined
   */
  directions?: CommaSeparatedStr<Direction> | Direction[];
 
  /**
   * If given, callback will only be called if the gesture's intent is one
   * of the given ones.
   *
   * It can be a comma-separated list of {@link GestureIntent}s or an
   * array of such intents.
   *
   * @defaultValue undefined
   */
  intents?: CommaSeparatedStr<GestureIntent> | GestureIntent[];
 
  /**
   * Set minimum total delta X. Further reductions in delta X below this value
   * will be ignored.
   *
   * The value is in pixels and can be negative.
   *
   * @defaultValue undefined
   */
  minTotalDeltaX?: number;
 
  /**
   * Set maximum total delta X. Further increase in delta X above this value
   * will be ignored.
   *
   * The value is in pixels.
   *
   * @defaultValue undefined
   */
  maxTotalDeltaX?: number;
 
  /**
   * Set minimum total delta Y. Further reductions in delta Y below this value
   * will be ignored.
   *
   * The value is in pixels and can be negative.
   *
   * @defaultValue undefined
   */
  minTotalDeltaY?: number;
 
  /**
   * Set maximum total delta Y. Further increase in delta Y above this value
   * will be ignored.
   *
   * The value is in pixels.
   *
   * @defaultValue undefined
   */
  maxTotalDeltaY?: number;
 
  /**
   * Set minimum total delta Z. Further reductions in delta Z below this value
   * will be ignored.
   *
   * The value is in percentage zoom, relative to 1, and can be less than 1 but
   * must be > 0.1 which is a hard minimum.
   *
   * @defaultValue undefined
   */
  minTotalDeltaZ?: number;
 
  /**
   * Set maximum total delta Z. Further increase in delta Z above this value
   * will be ignored.
   *
   * The value is in percentage zoom, relative to 1, and must be positive.
   *
   * @defaultValue undefined
   */
  maxTotalDeltaZ?: number;
 
  /**
   * If true, the events of the gesture, e.g. relevant key presses or touch
   * moves, etc, will have their default action prevented.
   *
   * **IMPORTANT:** For pointer gestures, then pointer/mouse down and click
   * will be prevented.
   *
   * @defaultValue {@link GestureWatcherConfig.preventDefault}
   */
  preventDefault?: boolean;
 
  /**
   * If given, callback will be called at most once every `debounceWindow`
   * milliseconds.
   *
   * Note that if both `debounceWindow` and `deltaThreshold` are set, _both_
   * must be exceeded before callback is called.
   *
   * @defaultValue {@link GestureWatcherConfig.debounceWindow}
   */
  debounceWindow?: number;
 
  /**
   * Callback will only be called when the gesture's accumulated delta, since
   * the last time callback was called, exceeds `deltaThreshold`.
   *
   * At least one of the three deltas (X, Y or Z) must exceed this number (in
   * absolute value). Note that when comparing `deltaZ`, it is multiplied by
   * 100 since it represents fractions of 1 (100%). So supplying
   * `deltaThreshold` of 10 means is equivalent to the following condition:
   *
   * ```
   * abs(deltaX) >= 10 || abs(deltaY) >= 10 ||  abs(1 - deltaZ) >= 0.1
   * ```
   *
   * Accumulation of the delta ends if the gesture is terminated, for example,
   * in case of touch gestures, by a "touchcancel" event of by the final finger
   * lifting off..
   *
   * Note that if both `debounceWindow` and `deltaThreshold` are set, _both_
   * must be exceeded before callback is called.
   *
   * @defaultValue {@link GestureWatcherConfig.deltaThreshold}
   */
  deltaThreshold?: number;
 
  /**
   * See {@link Utils.getVectorDirection | getVectorDirection}.
   *
   * @defaultValue {@link GestureWatcherConfig.angleDiffThreshold}
   */
  angleDiffThreshold?: number;
 
  /**
   * Whether touch scroll gestures follow the natural direction: swipe up
   * with scroll intent results in direction down and swipe down results in
   * direction up.
   *
   * @defaultValue {@link GestureWatcherConfig.naturalTouchScroll}
   */
  naturalTouchScroll?: boolean;
 
  /**
   * If the user presses and holds on a touchscreen for at least the given
   * amount of milliseconds before moving the finger(s), touch gestures other
   * than pinch will be treated as a drag intent instead of scroll as long as
   * the number of fingers touching the screen is {@link touchDragNumFingers}.
   *
   * Set to 0 in order to treat _all_ non-pinch touch gestures as drag.
   *
   * Set to a negative number in order to treat _all_ non-pinch touch gestures
   * as scroll.
   *
   * @defaultValue {@link GestureWatcherConfig.touchDragHoldTime}
   */
  touchDragHoldTime?: number;
 
  /**
   * The number of fingers that could be considered a drag intent for touch
   * gestures.
   *
   * @defaultValue {@link GestureWatcherConfig.touchDragHoldTime}
   */
  touchDragNumFingers?: number;
};
 
/**
 * The handler is invoked with two arguments:
 *
 * - the event target that was passed to the {@link GestureWatcher.onGesture}
 *   call (equivalent to
 *   {@link https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget | Event:currentTarget}).
 * - the {@link GestureData} that describes the gesture's progression since the
 *   last time the callback was called and since the callback was added.
 */
export type OnGestureHandlerArgs = [EventTarget, GestureData, Event[]];
export type OnGestureCallback = Callback<OnGestureHandlerArgs>;
export type OnGestureHandler =
  | CallbackHandler<OnGestureHandlerArgs>
  | OnGestureCallback;
 
export type GestureData = {
  device: GestureDevice;
  direction: Direction;
  intent: GestureIntent;
 
  /**
   * Delta in the horizontal direction since the start of the gesture.
   */
  deltaX: number;
 
  /**
   * Delta in the vertical direction since the start of the gesture.
   */
  deltaY: number;
 
  /**
   * Relative fractional zoom in or out for zoom intents since the start of
   * the gesture.
   *
   * For zoom in, `deltaZ` is always > 1, and for zoom out it is < 1.
   *
   * For non-zoom gestures it is 1.
   */
  deltaZ: number;
 
  /**
   * The time in milliseconds it took for the gesture. This will be the
   * difference in timestamps between the first and last event that composed
   * the gesture. For key and wheel gestures this could be 0, since 1 event is
   * sufficient for them.
   */
  time: number;
  // TODO totalTime, velocity (bound by max), averageVelocity (bound by max)
 
  /**
   * Delta in the horizontal direction since the callback was added.
   */
  totalDeltaX: number;
 
  /**
   * Delta in the vertical direction since the callback was added.
   */
  totalDeltaY: number;
 
  /**
   * Percentage (relative) zoom in or out for zoom intents since the callback
   * was added.
   */
  totalDeltaZ: number;
};
 
// ----------------------------------------
 
type GestureWatcherConfigInternal = {
  _preventDefault: boolean;
  _debounceWindow: number;
  _deltaThreshold: number;
  _angleDiffThreshold: number;
  _naturalTouchScroll: boolean;
  _touchDragHoldTime: number;
  _touchDragNumFingers: number;
};
 
type OnGestureOptionsInternal = {
  _devices: GestureDevice[] | null;
  _directions: Direction[] | null;
  _intents: GestureIntent[] | null;
  _minTotalDeltaX: number | null;
  _maxTotalDeltaX: number | null;
  _minTotalDeltaY: number | null;
  _maxTotalDeltaY: number | null;
  _minTotalDeltaZ: number | null;
  _maxTotalDeltaZ: number | null;
  _preventDefault: boolean;
  _debounceWindow: number;
  _deltaThreshold: number;
  _angleDiffThreshold: number;
  _naturalTouchScroll: boolean;
  _touchDragHoldTime: number;
  _touchDragNumFingers: number;
};
 
type OnGestureHandlerWrapper = (
  _target: EventTarget,
  _device: GestureDevice,
  _event: Event,
  _preventDefault: boolean,
) => boolean;
 
// Specific to a combination of target + device
type DeviceListeners = {
  _nCallbacks: number; // total number of callbacks
  _nPreventDefault: number; // total number wanting to prevent default action
  _remove: () => void;
};
 
const CONSTRUCTOR_KEY: unique symbol = MC.SYMBOL() as typeof CONSTRUCTOR_KEY;
const instances = MH.newMap<string, GestureWatcher>();
 
const getConfig = (
  config: GestureWatcherConfig | undefined,
): GestureWatcherConfigInternal => {
  config ??= {};
  return {
    _preventDefault: config.preventDefault ?? true,
    _debounceWindow: toNonNegNum(config[MC.S_DEBOUNCE_WINDOW], 150),
    _deltaThreshold: toNonNegNum(config.deltaThreshold, 5),
    _angleDiffThreshold: toPosNum(config.angleDiffThreshold, 35),
    _naturalTouchScroll: config.naturalTouchScroll ?? true,
    _touchDragHoldTime: config.touchDragHoldTime ?? 500,
    _touchDragNumFingers: config.touchDragNumFingers ?? 1,
  };
};
 
const initiatingEvents: {
  [D in GestureDevice]: readonly (keyof GlobalEventHandlersEventMap)[];
} = {
  key: [MC.S_KEYDOWN],
  // If the browser doesn't support pointer events, then
  // addEventListenerTo will transform it into mousedown
  //
  // We need to listen for click, since that occurs after a pointerup (i.e.
  // after a gesure is terminated and the ongoing listeners removed), but it
  // needs to have its default action prevented.
  pointer: [MC.S_POINTERDOWN, MC.S_CLICK],
  touch: [MC.S_TOUCHSTART],
  wheel: [MC.S_WHEEL],
} as const;
 
const ongoingEvents: {
  [D in GestureDevice]: readonly (keyof GlobalEventHandlersEventMap)[];
} = {
  key: [MC.S_KEYDOWN],
  pointer: [
    // If the browser doesn't support point events, then
    // addEventListenerTo will transform them into mouse*
    MC.S_POINTERDOWN,
    MC.S_POINTERUP, // would terminate
    MC.S_POINTERMOVE,
    MC.S_POINTERCANCEL, // would terminate
    MC.S_CLICK, // would terminate; can be default-prevented
  ],
  touch: [MC.S_TOUCHSTART, MC.S_TOUCHEND, MC.S_TOUCHMOVE, MC.S_TOUCHCANCEL],
  wheel: [MC.S_WHEEL],
} as const;
 
const fragmentGetters: {
  [D in GestureDevice]: (
    events: Event[],
    options: {
      deltaThreshold?: number;
      angleDiffThreshold?: number;
      reverseScroll?: boolean;
      dragHoldTime?: number;
      dragNumFingers?: number;
    },
  ) => GestureFragment | null | false;
} = {
  [MC.S_KEY]: getKeyGestureFragment,
  [MC.S_POINTER]: getPointerGestureFragment,
  [MC.S_TOUCH]: getTouchGestureFragment,
  [MC.S_WHEEL]: getWheelGestureFragment,
};
 
const getOptions = (
  config: GestureWatcherConfigInternal,
  options: OnGestureOptions,
): OnGestureOptionsInternal => {
  const debounceWindow = toNonNegNum(
    options[MC.S_DEBOUNCE_WINDOW],
    config._debounceWindow, // watcher is never debounced, so apply default here
  );
  const deltaThreshold = toNonNegNum(
    options.deltaThreshold,
    config._deltaThreshold,
  );
 
  return {
    _devices:
      validateStrList("devices", options.devices, isValidInputDevice) ?? null,
    _directions:
      validateStrList("directions", options.directions, isValidDirection) ??
      null,
    _intents:
      validateStrList("intents", options.intents, isValidIntent) ?? null,
    _minTotalDeltaX: options.minTotalDeltaX ?? null,
    _maxTotalDeltaX: options.maxTotalDeltaX ?? null,
    _minTotalDeltaY: options.minTotalDeltaY ?? null,
    _maxTotalDeltaY: options.maxTotalDeltaY ?? null,
    _minTotalDeltaZ: options.minTotalDeltaZ ?? null,
    _maxTotalDeltaZ: options.maxTotalDeltaZ ?? null,
    _preventDefault: options.preventDefault ?? config._preventDefault,
    _debounceWindow: debounceWindow,
    _deltaThreshold: deltaThreshold,
    _angleDiffThreshold: toNonNegNum(
      options.angleDiffThreshold,
      config._angleDiffThreshold,
    ),
    _naturalTouchScroll:
      options.naturalTouchScroll ?? config._naturalTouchScroll,
    _touchDragHoldTime: options.touchDragHoldTime ?? config._touchDragHoldTime,
    _touchDragNumFingers:
      options.touchDragNumFingers ?? config._touchDragNumFingers,
  };
};
 
// Since each callback needs to accumulate events during its debounce window
// and until its threshold is exceeded, we use a wrapper around the
// user-supplied handler to do that.
const getCallbackAndWrapper = (
  handler: OnGestureHandler,
  options: OnGestureOptionsInternal,
  logger: LoggerInterface | null,
): { _callback: OnGestureCallback; _wrapper: OnGestureHandlerWrapper } => {
  let totalDeltaX = 0,
    totalDeltaY = 0,
    totalDeltaZ = 1;
  // When there's a pointer down, drag then pointerup, since we prevent
  // pointerdown default action, this results in a click event shortly
  // afterwards even when there's been a movement of the mouse. We detect that
  // and prevent this click.
  let preventNextClick = false;
 
  const directions = options._directions;
  const intents = options._intents;
  const minTotalDeltaX = options._minTotalDeltaX;
  const maxTotalDeltaX = options._maxTotalDeltaX;
  const minTotalDeltaY = options._minTotalDeltaY;
  const maxTotalDeltaY = options._maxTotalDeltaY;
  const minTotalDeltaZ = options._minTotalDeltaZ;
  const maxTotalDeltaZ = options._maxTotalDeltaZ;
  const deltaThreshold = options._deltaThreshold;
  const angleDiffThreshold = options._angleDiffThreshold;
  const reverseScroll = !options._naturalTouchScroll;
  const dragHoldTime = options._touchDragHoldTime;
  const dragNumFingers = options._touchDragNumFingers;
 
  // The event queue is cleared when the threshold is exceeded AND the debounce
  // window has passed. It's not necessary for the actual handler to be called
  // then (e.g. if the direction or intent doesn't match, it won't be).
  const eventQueue: Event[] = [];
  const id = randId();
 
  // Since handler could be a function or a callback (not callable), we wrap it
  // so that in case it's already a callback, its removal will result in
  // deleteHandler getting called. It is not debounced itself, instead there's
  // a debounced wrapper that invokes it.
  const callback = wrapCallback(handler);
 
  // The debounced callback wrapper is what is debounced.
  // It accumulates total deltas and checks if the conditions (of threshold,
  // direction and intent) are satisfied before calling the real handler.
  //
  // Most importantly, since it is only called when the debounce window has
  // expired it can clear the event queue if the threshold is also exceeded.
  const debouncedWrapper = getDebouncedHandler(
    options._debounceWindow,
    (
      target: EventTarget,
      fragment: GestureFragment,
      eventQueueCopy: Event[],
    ) => {
      Iif (callback.isRemoved()) {
        return;
      }
 
      const deltaX = fragment.deltaX;
      const deltaY = fragment.deltaY;
      const deltaZ = fragment.deltaZ;
      const device = fragment.device;
 
      if (
        MH.round(maxAbs(deltaX, deltaY, (1 - deltaZ) * 100)) < deltaThreshold
      ) {
        debug: logger?.debug7(
          `[${id}] Delta threshold not exceeded for callback`,
        );
        return;
      }
 
      debug: logger?.debug9(`[${id}] Done summing events for ${device}`);
      clearEventQueue(device, eventQueue);
 
      const newTotalDeltaX = toNumWithBounds(totalDeltaX + deltaX, {
        min: minTotalDeltaX,
        max: maxTotalDeltaX,
      });
 
      const newTotalDeltaY = toNumWithBounds(totalDeltaY + deltaY, {
        min: minTotalDeltaY,
        max: maxTotalDeltaY,
      });
 
      const newTotalDeltaZ = toNumWithBounds(addDeltaZ(totalDeltaZ, deltaZ), {
        min: minTotalDeltaZ,
        max: maxTotalDeltaZ,
      });
 
      if (
        newTotalDeltaX === totalDeltaX &&
        newTotalDeltaY === totalDeltaY &&
        newTotalDeltaZ === totalDeltaZ
      ) {
        return;
      }
 
      totalDeltaX = newTotalDeltaX;
      totalDeltaY = newTotalDeltaY;
      totalDeltaZ = newTotalDeltaZ;
 
      const direction = fragment.direction;
      const intent = fragment.intent;
      const time =
        eventQueueCopy[MH.lengthOf(eventQueueCopy) - 1]?.timeStamp -
          eventQueueCopy[0]?.timeStamp || 0;
 
      const data = {
        device,
        direction,
        intent,
        deltaX,
        deltaY,
        deltaZ,
        time,
        totalDeltaX,
        totalDeltaY,
        totalDeltaZ,
      };
 
      if (
        direction !== MC.S_NONE &&
        (!directions || MH.includes(directions, direction)) &&
        (!intents || MH.includes(intents, intent))
      ) {
        callback.invoke(target, data, eventQueueCopy).catch(logError);
      } else {
        debug: logger?.debug7(
          `[${id}] Directions or intents not matching for callback`,
        );
      }
    },
  );
 
  // This wrapper is NOT debounced and adds the events to the queue, prevents
  // default action if needed, and indicates whether the gesture is terminated.
  const wrapper = (
    target: EventTarget,
    device: GestureDevice,
    event: Event,
    preventDefault: boolean,
  ) => {
    eventQueue.push(event);
 
    const fragment = fragmentGetters[device](eventQueue, {
      angleDiffThreshold,
      deltaThreshold,
      reverseScroll,
      dragHoldTime,
      dragNumFingers,
    });
 
    debug: logger?.debug8(
      `[${id}] Got fragment for ${device} (${event.type})`,
      fragment,
      [...eventQueue].map((e) => e.type),
    );
 
    if (preventDefault) {
      preventDefaultActionFor(
        event,
        !!fragment || (event.type === MC.S_CLICK && preventNextClick),
      );
    }
 
    if (fragment === false) {
      // not enough events in the queue, pass
      debug: logger?.debug9(`[${id}] Not enough events for gesture ${device}`);
      return false;
    } else if (fragment === null) {
      // consider the gesture terminated
      clearEventQueue(device, eventQueue);
      debug: logger?.debug9(`[${id}] Gesture for ${device} terminated`);
      return true;
    }
 
    if (device === MC.S_POINTER) {
      // If we're here, there's been a drag, expect a click immediately
      // afterwards and prevent default action.
      preventNextClick = true;
      MH.setTimer(() => {
        preventNextClick = false;
      }, 10);
    }
 
    debouncedWrapper(
      target,
      fragment,
      [...eventQueue], // copy
    );
 
    return false;
  };
 
  return { _callback: callback, _wrapper: wrapper };
};
 
const clearEventQueue = (device: GestureDevice, queue: Event[]) => {
  const keepLastEvent = device === MC.S_POINTER || device === MC.S_TOUCH;
  queue.splice(0, MH.lengthOf(queue) - (keepLastEvent ? 1 : 0));
};
 
const preventDefaultActionFor = (event: Event, isActualGesture: boolean) => {
  const target = event.currentTarget;
  const eventType = event.type;
  const isPointerDown =
    eventType === MC.S_POINTERDOWN || eventType === MC.S_MOUSEDOWN;
 
  if (
    eventType === MC.S_TOUCHMOVE ||
    eventType === MC.S_WHEEL ||
    ((eventType === MC.S_CLICK || eventType === MC.S_KEYDOWN) &&
      isActualGesture) ||
    (isPointerDown && (event as MouseEvent).buttons === 1)
  ) {
    MH.preventDefault(event);
 
    if (isPointerDown && MH.isHTMLElement(target)) {
      // Otherwise capturing key events won't work
      target.focus({ preventScroll: true });
    }
  }
};
 
const setGestureCssProps = (
  target: EventTarget,
  data: Partial<GestureData>,
) => {
  const intent = data.intent;
 
  if (!MH.isElement(target) || !intent || intent === MC.S_UNKNOWN) {
    return;
  }
 
  const prefix = `${intent}-`;
 
  if (intent === MC.S_ZOOM) {
    setNumericStyleJsVars(
      target,
      {
        deltaZ: data.totalDeltaZ,
      },
      {
        _prefix: prefix,
        _numDecimal: 2,
      },
    ); // don't await here
  } else {
    setNumericStyleJsVars(
      target,
      {
        deltaX: data.totalDeltaX,
        deltaY: data.totalDeltaY,
      },
      {
        _prefix: prefix,
      },
    ); // don't await here
  }
};