All files / src utils.ts

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        11x 11x       11x                 11x     10x 10x 16x   10x     441x   221x     9x     9x   4x   4x 4x     5x   9x 9x   212x   1x 211x   211x   210x 1x           1x 2x 1x       221x     11x 11x 11x                               11x                                   11x 2442x               11x 4x     11x       39603x   39603x 67151x 67151x     39603x     11x       175x   175x 269x 106x     175x   11x       4714x 5316x 3890x     824x   11x       686x     11x   11x   616x 31x     616x     11x       13494x 13085x   409x 409x             11x 253x       253x   253x     1x 1x   1x 14x 14x     1x         252x     11x     13x     11x 31x   31x 616x 1x     615x       11x 10576x     11x     118x 118x 590x       564x     118x     11x       163x 135x 28x 19x 9x 9x           11x         9612x 8962x         650x       11x                     113x 113x 113x     113x         113x 678x     113x 678x     113x     11x       111x 110x 660x     111x    
/*
 * Copyright (c) 2015 NAVER Corp.
 * egjs projects are licensed under the MIT license
 */
import { window } from "./browser";
import { PREVENT_DRAG_CSSPROPS } from "./const";
import { PanInputOption } from "./inputType/PanInput";
import { PinchInputOption } from "./inputType/PinchInput";
import { ObjectInterface } from "./types";
import {
  DIRECTION_NONE,
  DIRECTION_VERTICAL,
  DIRECTION_HORIZONTAL,
  DIRECTION_ALL,
} from "./const";
 
declare let jQuery: any;
 
export const toArray = (nodes: NodeList): HTMLElement[] => {
  // const el = Array.prototype.slice.call(nodes);
  // for IE8
  const el = [];
  for (let i = 0, len = nodes.length; i < len; i++) {
    el.push(nodes[i]);
  }
  return el;
};
 
export const $ = (param, multi = false) => {
  let el;
  if (typeof param === "string") {
    // String (HTML, Selector)
    // check if string is HTML tag format
    const match = param.match(/^<([a-z]+)\s*([^>]*)>/);
 
    // creating element
    if (match) {
      // HTML
      const dummy = document.createElement("div");
 
      dummy.innerHTML = param;
      el = toArray(dummy.childNodes);
    } else {
      // Selector
      el = toArray(document.querySelectorAll(param));
    }
    Eif (!multi) {
      el = el.length >= 1 ? el[0] : undefined;
    }
  } else if (param === window) {
    // window
    el = param;
  } else Iif ("value" in param || "current" in param) {
    el = param.value! || param.current!;
  } else if (param.nodeName && (param.nodeType === 1 || param.nodeType === 9)) {
    // HTMLElement, Document
    el = param;
  } else Iif (
    ("jQuery" in window && param instanceof jQuery) ||
    param.constructor.prototype.jquery
  ) {
    // jQuery
    el = multi ? param.toArray() : param.get(0);
  } else Eif (Array.isArray(param)) {
    el = param.map((v) => $(v));
    Iif (!multi) {
      el = el.length >= 1 ? el[0] : undefined;
    }
  }
  return el;
};
 
let raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
let caf = window.cancelAnimationFrame || window.webkitCancelAnimationFrame;
Iif (raf && !caf) {
  const keyInfo = {};
  const oldraf = raf;
  raf = (callback: FrameRequestCallback) => {
    const wrapCallback = (timestamp: number) => {
      if (keyInfo[key]) {
        callback(timestamp);
      }
    };
    const key = oldraf(wrapCallback);
    keyInfo[key] = true;
    return key;
  };
  caf = (key: number) => {
    delete keyInfo[key];
  };
} else Iif (!(raf && caf)) {
  raf = (callback: FrameRequestCallback) => {
    return window.setTimeout(() => {
      callback(
        ((window.performance &&
          window.performance.now &&
          window.performance.now()) as number) || new Date().getTime()
      );
    }, 16);
  };
  caf = window.clearTimeout;
}
 
/**
 * A polyfill for the window.requestAnimationFrame() method.
 * @see  https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
 * @private
 */
export const requestAnimationFrame = (fp) => {
  return raf(fp);
};
/**
 * A polyfill for the window.cancelAnimationFrame() method. It cancels an animation executed through a call to the requestAnimationFrame() method.
 * @param {Number} key −  The ID value returned through a call to the requestAnimationFrame() method. <ko>requestAnimationFrame() 메서드가 반환한 아이디 값</ko>
 * @see  https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
 * @private
 */
export const cancelAnimationFrame = (key) => {
  caf(key);
};
 
export const map = <T, U>(
  obj: ObjectInterface<T>,
  callback: (value: T, key: string) => U
): ObjectInterface<U> => {
  const tranformed: ObjectInterface<U> = {};
 
  for (const k in obj) {
    Eif (k) {
      tranformed[k] = callback(obj[k], k);
    }
  }
  return tranformed;
};
 
export const filter = <T>(
  obj: ObjectInterface<T>,
  callback: (value: T, key: string) => boolean
): ObjectInterface<T> => {
  const filtered: ObjectInterface<T> = {};
 
  for (const k in obj) {
    if (k && callback(obj[k], k)) {
      filtered[k] = obj[k];
    }
  }
  return filtered;
};
export const every = <T>(
  obj: ObjectInterface<T>,
  callback: (value: T, key: string) => boolean
) => {
  for (const k in obj) {
    if (k && !callback(obj[k], k)) {
      return false;
    }
  }
  return true;
};
export const equal = (
  target: ObjectInterface,
  base: ObjectInterface
): boolean => {
  return every(target, (v, k) => v === base[k]);
};
 
const roundNumFunc = {};
 
export const roundNumber = (num: number, roundUnit: number) => {
  // Cache for performance
  if (!roundNumFunc[roundUnit]) {
    roundNumFunc[roundUnit] = getRoundFunc(roundUnit);
  }
 
  return roundNumFunc[roundUnit](num);
};
 
export const roundNumbers = (
  num: ObjectInterface<number>,
  roundUnit: ObjectInterface<number> | number
): ObjectInterface<number> => {
  if (!num || !roundUnit) {
    return num;
  }
  return map(num, (value, key) =>
    roundNumber(
      value,
      typeof roundUnit === "number" ? roundUnit : roundUnit[key]
    )
  );
};
 
export const getDecimalPlace = (val: number): number => {
  Iif (!isFinite(val)) {
    return 0;
  }
 
  const v = `${val}`;
 
  if (v.indexOf("e") >= 0) {
    // Exponential Format
    // 1e-10, 1e-12
    let p = 0;
    let e = 1;
 
    while (Math.round(val * e) / e !== val) {
      e *= 10;
      p++;
    }
 
    return p;
  }
 
  // In general, following has performance benefit.
  // https://jsperf.com/precision-calculation
  return v.indexOf(".") >= 0 ? v.length - v.indexOf(".") - 1 : 0;
};
 
export const inversePow = (n: number) => {
  // replace Math.pow(10, -n) to solve floating point issue.
  // eg. Math.pow(10, -4) => 0.00009999999999999999
  return 1 / Math.pow(10, n);
};
 
export const getRoundFunc = (v: number) => {
  const p = v < 1 ? Math.pow(10, getDecimalPlace(v)) : 1;
 
  return (n: number) => {
    if (v === 0) {
      return 0;
    }
 
    return Math.round(Math.round(n / v) * v * p) / p;
  };
};
 
export const getAngle = (posX: number, posY: number) => {
  return (Math.atan2(posY, posX) * 180) / Math.PI;
};
 
export const isCssPropsFromAxes = (originalCssProps: {
  [key: string]: string;
}) => {
  let same = true;
  Object.keys(PREVENT_DRAG_CSSPROPS).forEach((prop) => {
    if (
      !originalCssProps ||
      originalCssProps[prop] !== PREVENT_DRAG_CSSPROPS[prop]
    ) {
      same = false;
    }
  });
  return same;
};
 
export const getDirection = (
  useHorizontal: boolean,
  useVertical: boolean
): number => {
  if (useHorizontal && useVertical) {
    return DIRECTION_ALL;
  } else if (useHorizontal) {
    return DIRECTION_HORIZONTAL;
  } else Eif (useVertical) {
    return DIRECTION_VERTICAL;
  } else {
    return DIRECTION_NONE;
  }
};
 
export const useDirection = (
  checkType: number,
  direction: number,
  userDirection?: number
): boolean => {
  if (userDirection) {
    return !!(
      direction === DIRECTION_ALL ||
      (direction & checkType && userDirection & checkType)
    );
  } else {
    return !!(direction & checkType);
  }
};
 
export const setCssProps = (
  element: HTMLElement,
  option: PanInputOption | PinchInputOption,
  direction: number
): { [key: string]: string } => {
  const touchActionMap = {
    [DIRECTION_NONE]: "auto",
    [DIRECTION_ALL]: "none",
    [DIRECTION_VERTICAL]: "pan-x",
    [DIRECTION_HORIZONTAL]: "pan-y",
  };
  const oldCssProps = {};
  Eif (element && element.style) {
    const touchAction = option.touchAction
      ? option.touchAction
      : touchActionMap[direction];
    const newCssProps = {
      ...PREVENT_DRAG_CSSPROPS,
      "touch-action":
        element.style["touch-action"] === "none" ? "none" : touchAction,
    };
    Object.keys(newCssProps).forEach((prop) => {
      oldCssProps[prop] = element.style[prop];
    });
    // Old style props like user-select can be corrupted if you change the style directly in the logic above.
    Object.keys(newCssProps).forEach((prop) => {
      element.style[prop] = newCssProps[prop];
    });
  }
  return oldCssProps;
};
 
export const revertCssProps = (
  element: HTMLElement,
  originalCssProps: { [key: string]: string }
): { [key: string]: string } => {
  if (element && element.style && originalCssProps) {
    Object.keys(originalCssProps).forEach((prop) => {
      element.style[prop] = originalCssProps[prop];
    });
  }
  return;
};