All files / watchers pointer-watcher.ts

100% Statements 89/89
100% Branches 30/30
100% Functions 22/22
100% Lines 86/86

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        94x 94x       94x           94x 94x 94x 94x   94x         94x           94x                                                                     22x                     23x 23x   23x 23x 2x 2x     23x             25x 1x                     24x     45x       24x       91x   91x 91x 27x     91x 91x         24x           53x 50x   50x       50x 92x           24x       24x 8x 8x 8x 8x                                                                                                                                                                                                             94x 94x   94x     45x           94x       53x                 94x             34x   34x 38x 1x     38x   38x         38x               34x   34x   34x 34x     94x                 58x 58x 58x 58x   58x 28x 2x     28x               28x   58x 58x   58x 58x       58x 58x     58x 18x 18x     58x 18x 18x                     94x   28x 30x     94x         66x  
/**
 * @module Watchers/PointerWatcher
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { PointerAction, CommaSeparatedStr } from "@lisn/globals/types";
 
import {
  addEventListenerTo,
  removeEventListenerFrom,
  preventSelect,
  undoPreventSelect,
} from "@lisn/utils/event";
import { logError } from "@lisn/utils/log";
import { isValidPointerAction, POINTER_ACTIONS } from "@lisn/utils/pointer";
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";
 
/**
 * {@link PointerWatcher} listens for simple pointer actions like clicks, press
 * and hold or hover.
 */
export class PointerWatcher {
  /**
   * Call the `startHandler` whenever the pointer action begins.
   * Call the `endHandler` whenever the pointer action ends. If `endHandler` is
   * not given, it defaults to `startHandler`.
   *
   * For an explanation of what "begins" and "ends" means for each supported
   * action, see {@link OnPointerOptions.actions}.
   *
   * **IMPORTANT:** The same handlers 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, then it will be removed and re-added with the
   * current options.
   */
  readonly onPointer: (
    target: EventTarget,
    startHandler: OnPointerHandler,
    endHandler?: OnPointerHandler,
    options?: OnPointerOptions,
  ) => Promise<void>;
 
  /**
   * Removes previously added handlers.
   */
  readonly offPointer: (
    target: EventTarget,
    startHandler: OnPointerHandler,
    endHandler?: OnPointerHandler,
  ) => void;
 
  /**
   * Creates a new instance of PointerWatcher with the given
   * {@link PointerWatcherConfig}. It does not save it for future reuse.
   */
  static create(config?: PointerWatcherConfig) {
    return new PointerWatcher(getConfig(config), CONSTRUCTOR_KEY);
  }
 
  /**
   * Returns an existing instance of PointerWatcher with the given
   * {@link PointerWatcherConfig}, 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?: PointerWatcherConfig) {
    const myConfig = getConfig(config);
    const configStrKey = objToStrKey(myConfig);
 
    let instance = instances.get(configStrKey);
    if (!instance) {
      instance = new PointerWatcher(myConfig, CONSTRUCTOR_KEY);
      instances.set(configStrKey, instance);
    }
 
    return instance;
  }
 
  private constructor(
    config: PointerWatcherConfigInternal,
    key: typeof CONSTRUCTOR_KEY,
  ) {
    if (key !== CONSTRUCTOR_KEY) {
      throw MH.illegalConstructorError("PointerWatcher.create");
    }
 
    // Keep this watcher super simple. The events we listen for don't fire at a
    // high rate and it's unlikely for there to be many many callbacks for each
    // target and event type, so don't bother with using a delegating listener,
    // etc.
 
    // Keep a map of callbacks so we can lookup the callback by the handler
    // (and also to prevent duplicate handler for each target, for consistency
    // with other watchers).
    const allCallbacks = newXWeakMap<
      EventTarget,
      Map<OnPointerHandler, OnPointerCallback>
    >(() => MH.newMap());
 
    // ----------
 
    const createCallback = (
      target: EventTarget,
      handler: OnPointerHandler,
    ): OnPointerCallback => {
      MH.remove(allCallbacks.get(target)?.get(handler));
 
      const callback = wrapCallback(handler);
      callback.onRemove(() => {
        MH.deleteKey(allCallbacks.get(target), handler);
      });
 
      allCallbacks.sGet(target).set(handler, callback);
      return callback;
    };
 
    // async for consistency with other watchers and future compatibility in
    // case of change needed
    const setupOnPointer = async (
      target: EventTarget,
      startHandler: OnPointerHandler,
      endHandler: OnPointerHandler | undefined,
      userOptions: OnPointerOptions | undefined,
    ) => {
      const options = getOptions(config, userOptions);
      const startCallback = createCallback(target, startHandler);
      const endCallback =
        endHandler && endHandler !== startHandler
          ? createCallback(target, endHandler)
          : startCallback;
 
      for (const action of options._actions) {
        listenerSetupFn[action](target, startCallback, endCallback, options);
      }
    };
 
    // ----------
 
    this.onPointer = setupOnPointer;
 
    // ----------
 
    this.offPointer = (target, startHandler, endHandler?) => {
      const entry = allCallbacks.get(target);
      MH.remove(entry?.get(startHandler));
      if (endHandler) {
        MH.remove(entry?.get(endHandler));
      }
    };
  }
}
 
/**
 * @interface
 */
export type PointerWatcherConfig = {
  /**
   * The default value for
   * {@link OnPointerOptions.preventDefault | preventDefault} in calls to
   * {@link PointerWatcher.onPointer}.
   *
   * @defaultValue false
   */
  preventDefault?: boolean;
 
  /**
   * The default value for
   * {@link OnPointerOptions.preventSelect | preventSelect} in calls to
   * {@link PointerWatcher.onPointer}.
   *
   * @defaultValue true
   */
  preventSelect?: boolean;
};
 
/**
 * @interface
 */
export type OnPointerOptions = {
  /**
   * One or more of of "click", "hover" or "press". If not specified, then all
   * actions are enabled.
   *
   * It can be a comma-separated list of {@link PointerAction}s or an array of
   * such actions.
   *
   * For click actions, the start handler is called for every odd number of
   * clicks (1st, 3rd, 5th, etc), and the end handler is called for every other
   * click. It functions like a toggle.
   *
   * For hover and press actions, the start handler is called when the pointer
   * enters or presses down on the target respectively, and the end handler is
   * called when the pointer leaves or comes off the target respectively.
   *
   * Note that on touch screens, hover and press actions behave identically.
   *
   * @defaultValue undefined
   */
  actions?: CommaSeparatedStr<PointerAction> | PointerAction[];
 
  /**
   * If true, the events of the pointer actions, e.g. click, will have their
   * default action prevented.
   *
   * @defaultValue {@link PointerWatcherConfig.preventDefault}
   */
  preventDefault?: boolean;
 
  /**
   * If true (default), then for press actions (and hover actions on touch
   * screens) it will prevent starting a text selection.
   *
   * @defaultValue {@link PointerWatcherConfig.preventSelect}
   */
  preventSelect?: boolean;
};
 
/**
 * The handler is invoked with two arguments:
 *
 * - the event target that was passed to the {@link PointerWatcher.onPointer}
 *   call (equivalent to
 *   {@link https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget | Event:currentTarget}).
 * - the {@link PointerActionData} describing the state of the action.
 */
export type OnPointerHandlerArgs = [EventTarget, PointerActionData, Event];
export type OnPointerCallback = Callback<OnPointerHandlerArgs>;
export type OnPointerHandler =
  | CallbackHandler<OnPointerHandlerArgs>
  | OnPointerCallback;
 
export type PointerActionData = {
  action: PointerAction;
  state: "ON" | "OFF";
};
 
// ----------------------------------------
 
type PointerWatcherConfigInternal = {
  _preventDefault: boolean;
  _preventSelect: boolean;
};
 
type OnPointerOptionsInternal = {
  _actions: PointerAction[];
  _preventDefault: boolean;
  _preventSelect: boolean;
};
 
const CONSTRUCTOR_KEY: unique symbol = MC.SYMBOL() as typeof CONSTRUCTOR_KEY;
const instances = MH.newMap<string, PointerWatcher>();
 
const getConfig = (
  config: PointerWatcherConfig | undefined,
): PointerWatcherConfigInternal => {
  return {
    _preventDefault: config?.preventDefault ?? false,
    _preventSelect: config?.preventSelect ?? true,
  };
};
 
const getOptions = (
  config: PointerWatcherConfigInternal,
  options: OnPointerOptions | undefined,
): OnPointerOptionsInternal => {
  return {
    _actions:
      validateStrList("actions", options?.actions, isValidPointerAction) ||
      POINTER_ACTIONS,
    _preventDefault: options?.preventDefault ?? config._preventDefault,
    _preventSelect: options?.preventSelect ?? config._preventSelect,
  };
};
 
const setupClickListener = (
  target: EventTarget,
  startCallback: OnPointerCallback,
  endCallback: OnPointerCallback,
  options: OnPointerOptionsInternal,
) => {
  // false if next will start; true if next will end.
  let toggleState = false;
 
  const wrapper = (event: Event) => {
    if (options._preventDefault) {
      MH.preventDefault(event);
    }
 
    toggleState = !toggleState;
 
    const data: PointerActionData = {
      action: MC.S_CLICK,
      state: toggleState ? "ON" : "OFF",
    };
 
    invokeCallback(
      toggleState ? startCallback : endCallback,
      target,
      data,
      event,
    );
  };
 
  addEventListenerTo(target, MC.S_CLICK, wrapper);
 
  const remove = () => removeEventListenerFrom(target, MC.S_CLICK, wrapper);
 
  startCallback.onRemove(remove);
  endCallback.onRemove(remove);
};
 
const setupPointerListeners = (
  action: typeof MC.S_HOVER | typeof MC.S_PRESS,
  target: EventTarget,
  startCallback: OnPointerCallback,
  endCallback: OnPointerCallback,
  options: OnPointerOptionsInternal,
) => {
  // If the browser doesn't support pointer events, then
  // addEventListenerTo will transform these into mouse*
  const startEventSuff = action === MC.S_HOVER ? "enter" : "down";
  const endEventSuff = action === MC.S_HOVER ? "leave" : "up";
  const startEvent = MC.S_POINTER + startEventSuff;
  const endEvent = MC.S_POINTER + endEventSuff;
 
  const wrapper = (event: Event, callback: OnPointerCallback) => {
    if (options._preventDefault) {
      MH.preventDefault(event);
    }
 
    const data: PointerActionData = {
      action,
      state:
        MH.strReplace(event.type, /pointer|mouse/, "") === startEventSuff
          ? "ON"
          : "OFF",
    };
 
    invokeCallback(callback, target, data, event);
  };
  const startListener = (event: Event) => wrapper(event, startCallback);
  const endListener = (event: Event) => wrapper(event, endCallback);
 
  addEventListenerTo(target, startEvent, startListener);
  addEventListenerTo(target, endEvent, endListener);
 
  // On some touch screen devices pressing and holding will initiate select
  // and result in touchend, so we prevent text select
  if (options._preventSelect) {
    preventSelect(target);
  }
 
  startCallback.onRemove(() => {
    undoPreventSelect(target);
    removeEventListenerFrom(target, startEvent, startListener);
  });
 
  endCallback.onRemove(() => {
    undoPreventSelect(target);
    removeEventListenerFrom(target, endEvent, endListener);
  });
};
 
const listenerSetupFn: {
  [D in PointerAction]: (
    target: EventTarget,
    startCallback: OnPointerCallback,
    endCallback: OnPointerCallback,
    options: OnPointerOptionsInternal,
  ) => void;
} = {
  click: setupClickListener,
  hover: (...args) => setupPointerListeners(MC.S_HOVER, ...args),
  press: (...args) => setupPointerListeners(MC.S_PRESS, ...args),
} as const;
 
const invokeCallback = (
  callback: OnPointerCallback,
  target: EventTarget,
  actionData: PointerActionData,
  event: Event,
) => callback.invoke(target, MH.copyObject(actionData), event).catch(logError);