All files / globals minification-helpers.ts

98.24% Statements 336/342
77.41% Branches 48/62
94.23% Functions 98/104
98.6% Lines 212/215

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                94x                         94x     94x           94x     94x 269x   94x 7370x 428x 38x   8735x   1281x   1182x   6845x   94x   726x   94x   94x   94x   7264x   94x   18297x   94x   94x 1237x   6566x   3054x   94x 121x           94x 2772x   94x     435x   94x 14x 14x 14x 14x 14x     94x 19872x   94x 12096x   94x 5782x   18759x   4511x   94x 26851x     59277x     94x 12520x   94x 16555x   94x     94x 5581x   94x 8x   94x 81x   94x 291x   94x 170x   94x 351x   94x 166x   94x 265x   94x   5815x   94x 2362x   94x 542x     94x       1337x   94x   94x   94x 209x   94x 47x       94x 311x                       94x 171x   94x 19107x   94x 59x   94x 116x   94x   94x 3799x   94x 3183x   94x 740x   94x 549x   94x       3111x   94x               94x           17x   94x             7031x   94x     7671x 6974x     7671x     94x 3518x   94x 772271x   94x 197x   94x   2x   889x   94x     514x   94x   94x   5694x   94x     94x     9768x           94x 1350x     94x   94x   94x   94x   94x 13661x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x   94x     34557x   94x   120831x   94x 5x   94x 1801x   94x 200x       94x 4467x         94x 276x         94x 3905x     94x 238x   94x 252x   94x   94x     4381x   94x 361x   94x     4542x   94x       310x   94x           94x           15300x   94x 10572x   94x   1609x   7569x   94x 175x   94x     405x   94x 362x   94x 422x   168x   94x   94x 7x   94x 94x   94x   94x   94x   94x                                                                  
/**
 * For minification optimization
 *
 * @module
 * @ignore
 * @internal
 */
 
import * as MC from "@lisn/globals/minification-constants";
 
import {
  BoundingRect,
  IterableObject,
  Constructor,
  InstanceType,
  MapBase,
  SetBase,
  Spread,
  EmptyLiteral,
} from "@lisn/globals/types";
 
import { LisnUsageError, LisnBugError } from "@lisn/globals/errors";
 
// credit: underscore.js
export const root =
  (typeof self === "object" && self.self === self && self) ||
  (typeof global == "object" && global.global === global && global) ||
  Function("return this")() ||
  {};
 
export const userAgent =
  typeof navigator === "undefined" ? "" : navigator.userAgent;
 
export const kebabToCamelCase = (str: string) =>
  str.replace(/-./g, (m) => toUpperCase(m.charAt(1)));
 
export const camelToKebabCase = (str: string) =>
  str
    .replace(/[A-Z][a-z]/g, (m) => "-" + toLowerCase(m))
    .replace(/[A-Z]+/, (m) => "-" + toLowerCase(m));
 
export const prefixName = (name: string) => `${MC.PREFIX}-${name}`;
 
export const prefixCssVar = (name: string) => "--" + prefixName(name);
 
export const prefixCssJsVar = (name: string) => prefixCssVar("js--" + name);
 
export const prefixData = (name: string) => `data-${camelToKebabCase(name)}`;
 
export const prefixLisnData = (name: string) => prefixData(prefixName(name));
 
export const toLowerCase = (s: string) => s.toLowerCase();
 
export const toUpperCase = (s: string) => s.toUpperCase();
 
export const timeNow = Date.now.bind(Date);
 
export const timeSince = (startTime: number) => timeNow() - startTime;
 
export const hasDOM = () => typeof document !== "undefined";
 
export const getWindow = () => window;
 
export const getDoc = () => document;
 
export const getDocElement = () => getDoc().documentElement;
 
export const getDocScrollingElement = () =>
  getDoc().scrollingElement as HTMLElement | null;
 
export const getBody = () => getDoc().body;
 
export const getReadyState = () => getDoc().readyState;
 
export const getPointerType = (event: Event) =>
  isPointerEvent(event)
    ? event.pointerType
    : isMouseEvent(event)
      ? "mouse"
      : null;
 
export const onAnimationFrame = (callback: FrameRequestCallback) =>
  requestAnimationFrame(callback);
 
export const createElement = (
  tagName: string,
  options?: ElementCreationOptions,
) => getDoc().createElement(tagName, options);
 
export const createButton = (label = "", tag = "button") => {
  const btn = createElement(tag);
  setTabIndex(btn);
  setAttr(btn, MC.S_ROLE, "button");
  setAttr(btn, MC.ARIA_PREFIX + "label", label);
  return btn;
};
 
export const isNullish = (v: unknown): v is null | undefined =>
  v === undefined || v === null;
 
export const isEmpty = (v: unknown): v is null | undefined | "" =>
  isNullish(v) || v === "";
 
export const isIterableObject = (v: unknown): v is IterableObject<unknown> =>
  isNonPrimitive(v) && MC.SYMBOL.iterator in v;
 
export const isArray = (v: unknown) => isInstanceOf(v, MC.ARRAY);
 
export const isObject = (v: unknown) => isInstanceOf(v, MC.OBJECT);
 
export const isNonPrimitive = (v: unknown): v is object =>
  v !== null && typeOf(v) === "object";
 
// only primitive number
export const isNumber = (v: unknown): v is number => typeOf(v) === "number";
 
/* eslint-disable-next-line @typescript-eslint/no-wrapper-object-types */
export const isString = (v: unknown): v is string | String =>
  typeOf(v) === "string" || isInstanceOf(v, MC.STRING);
 
export const isLiteralString = (v: unknown): v is string =>
  typeOf(v) === "string";
 
export const isBoolean = (v: unknown): v is boolean => typeOf(v) === "boolean";
 
/* eslint-disable-next-line @typescript-eslint/no-unsafe-function-type */
export const isFunction = (v: unknown): v is Function =>
  typeOf(v) === "function" || isInstanceOf(v, MC.FUNCTION);
 
export const isDoc = (target: unknown): target is Document =>
  target === getDoc();
 
export const isMouseEvent = (event: Event): event is MouseEvent =>
  isInstanceOf(event, MouseEvent);
 
export const isPointerEvent = (event: Event): event is PointerEvent =>
  typeof PointerEvent !== "undefined" && isInstanceOf(event, PointerEvent);
 
export const isTouchPointerEvent = (event: Event): event is PointerEvent =>
  isPointerEvent(event) && getPointerType(event) === MC.S_TOUCH;
 
export const isWheelEvent = (event: Event): event is WheelEvent =>
  isInstanceOf(event, WheelEvent);
 
export const isKeyboardEvent = (event: Event): event is KeyboardEvent =>
  isInstanceOf(event, KeyboardEvent);
 
export const isTouchEvent = (event: Event): event is TouchEvent =>
  typeof TouchEvent !== "undefined" && isInstanceOf(event, TouchEvent);
 
export const isNode = (target: unknown) => isInstanceOf(target, Node);
 
export const isElement = (target: unknown) => isInstanceOf(target, Element);
 
export const isHTMLElement = (target: unknown) =>
  isInstanceOf(target, HTMLElement);
 
export const isNodeBAfterA = (nodeA: Node, nodeB: Node) =>
  (nodeA.compareDocumentPosition(nodeB) & Node.DOCUMENT_POSITION_FOLLOWING) !==
  0;
 
export const strReplace = (
  s: string,
  match: string | RegExp,
  replacement: string,
) => s.replace(match, replacement);
 
export const setTimer = root.setTimeout.bind(root);
 
export const clearTimer = root.clearTimeout.bind(root);
 
export const closestParent = (element: Element, selector: string) =>
  element.closest(selector);
 
export const getBoundingClientRect = (element: Element) =>
  element.getBoundingClientRect();
 
// Copy size properties explicitly to another object so they can be used with
// the spread operator (DOMRect/DOMRectReadOnly's properties are not enumerable)
export const copyBoundingRectProps = (rect: BoundingRect): BoundingRect => {
  return {
    x: rect.x,
    left: rect.left,
    right: rect.right,
    [MC.S_WIDTH]: rect[MC.S_WIDTH],
    y: rect.y,
    top: rect.top,
    bottom: rect.bottom,
    [MC.S_HEIGHT]: rect[MC.S_HEIGHT],
  };
};
 
export const querySelector = (root: Element | Document, selector: string) =>
  root.querySelector(selector);
 
export const querySelectorAll = (root: Element | Document, selector: string) =>
  root.querySelectorAll(selector);
 
export const docQuerySelector = (selector: string) =>
  querySelector(getDoc(), selector);
 
export const docQuerySelectorAll = (selector: string) =>
  querySelectorAll(getDoc(), selector);
 
export const getElementById = (id: string) => getDoc().getElementById(id);
 
export const getAttr = (element: Element, name: string) =>
  element.getAttribute(name);
 
export const setAttr = (element: Element, name: string, value = "true") =>
  element.setAttribute(name, value);
 
export const unsetAttr = (element: Element, name: string) =>
  element.setAttribute(name, "false");
 
export const delAttr = (element: Element, name: string) =>
  element.removeAttribute(name);
 
export const includes = (
  arr: readonly unknown[] | string,
  v: unknown,
  startAt?: number,
) => (arr.indexOf as (v: unknown, startAt?: number) => number)(v, startAt) >= 0;
 
export const every = <
  A extends readonly unknown[],
  C extends ArrayCallbackFn<A[number]>,
>(
  array: A,
  predicate: C,
) => array.every(predicate);
 
export const some = <
  A extends readonly unknown[],
  C extends ArrayCallbackFn<A[number]>,
>(
  array: A,
  predicate: C,
) => array.some(predicate);
 
export const filter = <
  A extends readonly unknown[],
  T extends A[number],
  C extends ArrayCallbackFn<A[number]> | FilterFnTypeP<A[number], T>,
>(
  array: A,
  filterFn: C,
) => array.filter(filterFn) as FilteredType<C, A[number], T>[];
 
export const filterBlank = <A extends readonly unknown[]>(
  array: A | null | undefined,
) => {
  const result = array
    ? filter(array, (v): v is NonNullable<A[number]> => !isEmpty(v))
    : undefined;
 
  return lengthOf(result) ? result : undefined;
};
 
export const sizeOf = (obj: { size: number } | null | undefined) =>
  obj?.size ?? 0;
 
export const lengthOf = (obj: { length: number } | null | undefined) =>
  obj?.length ?? 0;
 
export const lastOf = <A extends readonly unknown[]>(a: A | null | undefined) =>
  a?.slice(-1)[0] as LastElement<A>;
 
export const firstOf = <A extends readonly unknown[]>(
  a: A | null | undefined,
) => a?.slice(0, 1)[0] as FirstElement<A>;
 
export const tagName = (element: Element) => element.tagName;
 
export const hasTagName = (element: Element, tag: string) =>
  toLowerCase(tagName(element)) === toLowerCase(tag);
 
export const preventDefault = (event: Event) => event.preventDefault();
 
export const arrayFrom = MC.ARRAY.from.bind(MC.ARRAY);
 
export const keysOf = <T extends Record<string | symbol, unknown>>(
  obj: T,
): Array<keyof T & string> => MC.OBJECT.keys(obj);
 
export const defineProperty = MC.OBJECT.defineProperty.bind(MC.OBJECT);
 
// use it in place of object spread
export const merge = <A extends readonly (object | null | undefined)[]>(
  ...a: [...A]
) => {
  return assign({}, ...a) as Spread<A>;
};
 
export function copyObject<T extends object>(obj: T): T;
export function copyObject(obj: null | undefined): EmptyLiteral;
// implementation (wide) — callers see the overloads, not this signature
export function copyObject(obj: object | null | undefined) {
  return merge(obj);
}
 
export const promiseResolve = MC.PROMISE.resolve.bind(MC.PROMISE);
 
export const promiseAll = MC.PROMISE.all.bind(MC.PROMISE);
 
export const assign = MC.OBJECT.assign.bind(MC.OBJECT);
 
export const freezeObj = MC.OBJECT.freeze.bind(MC.OBJECT);
 
export const hasOwnProp = (o: object, prop: string | symbol) =>
  MC.OBJECT.prototype.hasOwnProperty.call(o, prop);
 
export const preventExtensions = MC.OBJECT.preventExtensions.bind(MC.OBJECT);
 
export const stringify = JSON.stringify.bind(JSON);
 
export const floor = MC.MATH.floor.bind(MC.MATH);
 
export const ceil = MC.MATH.ceil.bind(MC.MATH);
 
export const log2 = MC.MATH.log2.bind(MC.MATH);
 
export const sqrt = MC.MATH.sqrt.bind(MC.MATH);
 
export const max = MC.MATH.max.bind(MC.MATH);
 
export const min = MC.MATH.min.bind(MC.MATH);
 
export const abs = MC.MATH.abs.bind(MC.MATH);
 
export const round = MC.MATH.round.bind(MC.MATH);
 
export const pow = MC.MATH.pow.bind(MC.MATH);
 
export const exp = MC.MATH.exp.bind(MC.MATH);
 
export const cos = MC.MATH.cos.bind(MC.MATH);
 
export const sin = MC.MATH.sin.bind(MC.MATH);
 
export const tan = MC.MATH.tan.bind(MC.MATH);
 
export const parseFloat = MC.NUMBER.parseFloat.bind(MC.NUMBER);
 
export const isNaN = MC.NUMBER.isNaN.bind(MC.NUMBER);
 
export const isInstanceOf = <C extends Constructor<unknown>>(
  value: unknown,
  Class: C,
): value is InstanceType<C> => value instanceof Class;
 
export const constructorOf = (obj: object) => obj.constructor;
 
export const typeOf = (obj: unknown) => typeof obj;
 
export const typeOrClassOf = (obj: unknown) =>
  isObject(obj) ? constructorOf(obj)?.name : typeOf(obj);
 
export const parentOf = (element: Element | undefined | null) =>
  element?.parentElement ?? null;
 
export const childrenOf = (element: Element | undefined | null) =>
  element?.children || [];
 
export function targetOf<T>(obj: { target: T }): T;
export function targetOf(obj: object | null | undefined): undefined;
export function targetOf(obj: object | null | undefined) {
  return obj && "target" in obj ? obj.target : undefined;
}
 
export function currentTargetOf<T>(obj: { currentTarget: T }): T;
export function currentTargetOf(obj: object | null | undefined): undefined;
export function currentTargetOf(obj: object | null | undefined) {
  return obj && "currentTarget" in obj ? obj.currentTarget : undefined;
}
 
export function classList(element: Element): DOMTokenList;
export function classList(element: null | undefined): undefined;
export function classList(element: Element | null | undefined) {
  return element?.classList;
}
 
const S_TABINDEX = "tabindex";
export const getTabIndex = (element: Element) => getAttr(element, S_TABINDEX);
 
export const setTabIndex = (element: Element, index = "0") =>
  setAttr(element, S_TABINDEX, index);
 
export const unsetTabIndex = (element: Element) => delAttr(element, S_TABINDEX);
 
export const remove = <A extends readonly unknown[]>(
  obj: { remove: (...args: A) => void } | null | undefined,
  ...args: A
) => obj?.remove(...args);
 
export const deleteObjKey = <O extends object>(obj: O, key: keyof O) =>
  delete obj[key];
 
export const deleteKey = <K, V>(
  map: MapBase<K, V> | SetBase<K> | null | undefined,
  key: K,
) => map?.delete(key);
 
export const elScrollTo = (
  element: Element,
  coords: { top?: number; left?: number },
  behavior: ScrollBehavior = "instant",
) => element.scrollTo(merge({ behavior }, coords));
 
export const elScrollBy = (
  element: Element,
  coords: { top?: number; left?: number },
  behavior: ScrollBehavior = "instant",
) => element.scrollBy(merge({ behavior }, coords));
 
export const newPromise = <T>(
  executor: (
    resolve: (value: T) => void,
    /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
    reject: (reason?: any) => void,
  ) => void,
) => new Promise(executor);
 
export const newMap = <K, V>(entries?: readonly (readonly [K, V])[] | null) =>
  new Map(entries);
 
export const newWeakMap = <K extends WeakKey, V>(
  entries?: readonly (readonly [K, V])[] | null,
) => new WeakMap(entries);
 
export const newSet = <T>(values?: readonly T[] | null) => new Set(values);
 
export const newWeakSet = <T extends WeakKey>(values?: readonly T[] | null) =>
  new WeakSet(values);
 
export const newIntersectionObserver = (
  callback: IntersectionObserverCallback,
  options?: IntersectionObserverInit,
) => new IntersectionObserver(callback, options);
 
export const newResizeObserver = (callback: ResizeObserverCallback) =>
  typeof ResizeObserver === "undefined" ? null : new ResizeObserver(callback);
 
export const newMutationObserver = (callback: MutationCallback) =>
  new MutationObserver(callback);
 
export const usageError = (msg: string) => new LisnUsageError(msg);
 
export const bugError = (msg: string) => new LisnBugError(msg);
 
export const illegalConstructorError = (useWhat: string) =>
  usageError(`Illegal constructor. Use ${useWhat}.`);
 
const CONSOLE = console;
export const consoleDebug = CONSOLE.debug.bind(CONSOLE);
 
export const consoleLog = CONSOLE.log.bind(CONSOLE);
 
export const consoleInfo = CONSOLE.info.bind(CONSOLE);
 
export const consoleWarn = CONSOLE.warn.bind(CONSOLE);
 
export const consoleError = CONSOLE.error.bind(CONSOLE);
 
// --------------------
 
type FirstElement<T extends readonly unknown[]> = T extends readonly [
  infer Head,
  ...infer Last__ignored,
]
  ? Head
  : T[number] | undefined;
 
type LastElement<T extends readonly unknown[]> = T extends readonly [
  ...infer Head__ignored,
  infer Last,
]
  ? Last
  : T[number] | undefined;
 
type ArrayCallbackFn<V> = (
  value: V,
  index: number,
  array: readonly V[],
) => unknown;
type FilterFnTypeP<V, T extends V> = (
  value: V,
  index: number,
  array: readonly V[],
) => value is T;
type FilteredType<
  C extends ArrayCallbackFn<V> | FilterFnTypeP<V, T>,
  V,
  T extends V,
> = C extends FilterFnTypeP<V, infer T> ? T : V;