All files / src/core/dom style.ts

26.32% Statements 5/19
0% Branches 0/12
0% Functions 0/6
27.78% Lines 5/18

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        3x                               3x     3x                                                   3x       3x      
import { isString, isNumber, isUndefined } from 'core/utils/types';
 
type cssStyleObj = { [key: string]: string | number };
 
const cssNumber = {
  animationIterationCount: true,
  columnCount: true,
  fillOpacity: true,
  flexGrow: true,
  flexShrink: true,
  fontWeight: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  widows: true,
  zIndex: true,
  zoom: true,
};
 
const parseCSSVal: (prop: string, val: string | number) => string | number = (prop, val) =>
  !cssNumber[prop.toLowerCase()] && isNumber(val) ? `${val}px` : val;
 
const setCSSVal: (elm: HTMLElement, prop: string, val: string | number) => void = (elm, prop, val) => {
  try {
    if (elm.style[prop] !== undefined) {
      elm.style[prop] = parseCSSVal(prop, val);
    }
  } catch (e) {}
};
 
export function style(elm: HTMLElement, styles: string | cssStyleObj): string;
export function style(elm: HTMLElement, styles: string | cssStyleObj, val: string | number): void;
export function style(elm: HTMLElement, styles: string | cssStyleObj, val?: string | number): string | void {
  const getCptStyle = window.getComputedStyle;
 
  if (isString(styles)) {
    if (isUndefined(val)) {
      const cptStyle: CSSStyleDeclaration = getCptStyle(elm, null);
 
      // https://bugzilla.mozilla.org/show_bug.cgi?id=548397 can be null sometimes if iframe with display: none (firefox only!)
      return cptStyle != null ? cptStyle.getPropertyValue(styles) : elm.style[styles];
    }
    setCSSVal(elm, styles, val);
  } else {
    Object.keys(styles).forEach((key) => setCSSVal(elm, key, styles[key]));
  }
}
 
export const hide: (elm: HTMLElement) => void = (elm) => {
  elm.style.display = 'none';
};
 
export const show: (elm: HTMLElement) => void = (elm) => {
  elm.style.display = 'block';
};