All files / utils event.ts

98.94% Statements 94/95
87.09% Branches 27/31
93.33% Functions 14/15
98.87% Lines 88/89

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        94x 94x   94x 94x   94x               94x       2x 2x                                   94x           3358x 3358x 3358x   124x     3234x 3234x       3234x 3234x 1721x 2x     1721x   2x 2x 2x         3234x         3234x 3234x                                   94x           1215x 1215x 1215x   1215x 304x     911x 911x 911x             94x 356x 356x 356x               94x 57x 57x 57x               94x 7894x   7852x     42x                       42x   42x 168x 168x   204x 204x 41x   163x         42x 42x 42x 42x 41x         41x         42x   42x 42x                       94x                       3231x                           94x     8718x           8718x 4271x 4447x 4447x     8718x     94x           4573x 4573x             94x           911x 911x       911x     94x             3234x 3234x             94x 4573x 4573x     1289x     3284x    
/**
 * @module Utils
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { addClasses, removeClasses } from "@lisn/utils/css-alter";
import { copyExistingKeys } from "@lisn/utils/misc";
 
import { XMap, newXMapGetter, newXWeakMap } from "@lisn/modules/x-map";
 
/**
 * Calls the given event listener, which could be a function that's callable
 * directly, or an object that has a `handleEvent` function property.
 *
 * @category Events: Generic
 */
export const callEventListener = (
  handler: EventListenerOrEventListenerObject,
  event: Event,
) => {
  if (MH.isFunction(handler)) {
    handler.call(event.currentTarget ?? self, event);
  } else E{
    handler.handleEvent.call(event.currentTarget ?? self, event);
  }
};
 
/**
 * Adds an event listener for the given event name to the given target.
 *
 * Like {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener | EventTarget:addEventListener}
 * but it handles `options` object in case the browser does not support those.
 * Does not support the `signal` option unless browser natively supports that.
 *
 * @returns `true` if successfully added, or `false` if the same handler has
 * already been added by us, or if the handler is not a valid event listener.
 *
 * @category Events: Generic
 */
export const addEventListenerTo = (
  target: EventTarget,
  eventType: string,
  handler: EventListenerOrEventListenerObject,
  options?: boolean | AddEventListenerOptions,
): boolean => {
  options ??= false;
  eventType = transformEventType(eventType);
  if (getEventHandlerData(target, eventType, handler, options)) {
    // already added
    return false;
  }
 
  let thirdArg = options;
  let wrappedHandler = handler;
 
  // If the user passed an options object but the browser only supports a
  // boolen for 'useCapture', then handle this.
  const supports = getBrowserSupport();
  if (MH.isNonPrimitive(options)) {
    if (!supports._optionsArg) {
      thirdArg = options.capture ?? false;
    }
 
    if (options.once && !supports._options.once) {
      // Remove the handler once it's called once
      wrappedHandler = (event) => {
        removeEventListenerFrom(target, eventType, handler, options);
        callEventListener(handler, event);
      };
    }
  }
 
  setEventHandlerData(target, eventType, handler, options, {
    _wrappedHandler: wrappedHandler,
    _thirdArg: thirdArg,
  });
 
  target.addEventListener(eventType, wrappedHandler, thirdArg);
  return true;
};
 
/**
 * Removes an event listener that has been added using
 * {@link addEventListenerTo}.
 *
 * **IMPORTANT:** If you have added a listener using the built-in
 * {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener | EventTarget:addEventListener},
 * then you should use
 * {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener | EventTarget:removeEventListener},
 * to remove it, not this function.
 *
 * @returns `true` if successfully removed, or `false` if the handler has not
 * been added by us.
 *
 * @category Events: Generic
 */
export const removeEventListenerFrom = (
  target: EventTarget,
  eventType: string,
  handler: EventListenerOrEventListenerObject,
  options?: boolean | AddEventListenerOptions,
) => {
  options ??= false;
  eventType = transformEventType(eventType);
  const data = getEventHandlerData(target, eventType, handler, options);
 
  if (!data) {
    return false;
  }
 
  target.removeEventListener(eventType, data._wrappedHandler, data._thirdArg);
  deleteEventHandlerData(target, eventType, handler, options);
  return true;
};
 
/**
 * @ignore
 * @internal
 */
export const preventSelect = (target: EventTarget) => {
  addEventListenerTo(target, MC.S_SELECTSTART, MH.preventDefault);
  if (MH.isElement(target)) {
    addClasses(target, MC.PREFIX_NO_SELECT);
  }
};
 
/**
 * @ignore
 * @internal
 */
export const undoPreventSelect = (target: EventTarget) => {
  removeEventListenerFrom(target, MC.S_SELECTSTART, MH.preventDefault);
  if (MH.isElement(target)) {
    removeClasses(target, MC.PREFIX_NO_SELECT);
  }
};
 
/**
 * @ignore
 * @internal
 */
export const getBrowserSupport = (): BrowserEventSupport => {
  if (browserEventSupport) {
    // already detected
    return browserEventSupport;
  }
 
  const supports = {
    _pointer: false,
    _optionsArg: false,
    _options: {
      capture: false,
      passive: false,
      once: false,
      signal: false,
    },
  };
 
  // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#safely_detecting_option_support
  const optTest = {};
  let opt: keyof typeof supports._options;
  for (opt in supports._options) {
    const thisOpt = opt;
    MH.defineProperty(optTest, thisOpt, {
      get: () => {
        supports._options[thisOpt] = true;
        if (thisOpt === "signal") {
          return new AbortController().signal;
        }
        return false;
      },
    });
  }
 
  const dummyHandler = () => {}; // TypeScript does not accept null
  const dummyElement = MH.createElement("div");
  try {
    dummyElement.addEventListener("testOptionSupport", dummyHandler, optTest);
    dummyElement.removeEventListener(
      "testOptionSupport",
      dummyHandler,
      optTest,
    );
    supports._optionsArg = true;
  } catch (e__ignored) {
    //
  }
 
  supports._pointer = "onpointerup" in dummyElement;
 
  browserEventSupport = supports;
  return supports;
};
 
// --------------------
 
type EventHandlerData = {
  _wrappedHandler: EventListenerOrEventListenerObject;
  _thirdArg: boolean | AddEventListenerOptions;
};
 
let browserEventSupport: BrowserEventSupport;
 
const registeredEventHandlerData = newXWeakMap<
  EventTarget,
  XMap<
    string, // event type
    XMap<
      EventListenerOrEventListenerObject, // user-supplied handler
      Map<
        string, // str repr of options
        EventHandlerData
      >
    >
  >
>(newXMapGetter(newXMapGetter(() => MH.newMap())));
 
// detect browser features, see below
type BrowserEventSupport = {
  _pointer: boolean;
  _optionsArg: boolean;
  _options: {
    capture: boolean;
    passive: boolean;
    once: boolean;
    signal: boolean;
  };
};
 
const getEventOptionsStr = (
  options: boolean | AddEventListenerOptions,
): string => {
  const finalOptions: AddEventListenerOptions = {
    capture: false,
    passive: false,
    once: false,
  };
 
  if (options === false || options === true) {
    finalOptions.capture = options;
  } else if (MH.isObject(options)) {
    copyExistingKeys(options, finalOptions);
  }
 
  return MH.stringify(finalOptions);
};
 
const getEventHandlerData = (
  target: EventTarget,
  eventType: string,
  handler: EventListenerOrEventListenerObject,
  options: boolean | AddEventListenerOptions,
) => {
  const optionsStr = getEventOptionsStr(options);
  return registeredEventHandlerData
    .get(target)
    ?.get(eventType)
    ?.get(handler)
    ?.get(optionsStr);
};
 
const deleteEventHandlerData = (
  target: EventTarget,
  eventType: string,
  handler: EventListenerOrEventListenerObject,
  options: boolean | AddEventListenerOptions,
) => {
  const optionsStr = getEventOptionsStr(options);
  MH.deleteKey(
    registeredEventHandlerData.get(target)?.get(eventType)?.get(handler),
    optionsStr,
  );
  registeredEventHandlerData.prune(target, eventType, handler);
};
 
const setEventHandlerData = (
  target: EventTarget,
  eventType: string,
  handler: EventListenerOrEventListenerObject,
  options: boolean | AddEventListenerOptions,
  data: EventHandlerData,
) => {
  const optionsStr = getEventOptionsStr(options);
  registeredEventHandlerData
    .sGet(target)
    .sGet(eventType)
    .sGet(handler)
    .set(optionsStr, data);
};
 
const transformEventType = (eventType: string) => {
  const supports = getBrowserSupport();
  if (eventType.startsWith(MC.S_POINTER) && !supports._pointer) {
    // TODO maybe log a warning message is it's not supported, e.g. there's no
    // mousecancel
    return MH.strReplace(eventType, MC.S_POINTER, MC.S_MOUSE);
  }
 
  return eventType;
};