Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/ui / src / components / features / Portal / deps.ts
Size: Mime:
import { isObj, isFunction, isString } from 'exotic'

/**
 * also available from 'fbjs'
 */
export const canUseDOM =
  typeof window === 'object' &&
  isObj(window.document) &&
  isFunction(window.document.createElement)

/**
 * @description sometimes this throws, so we wrap this one function and scope the easily-deopted of trycatch
 */
export function removeElement(element: Element) {
  try {
    document.body.removeChild(element)
    return true
  } catch (objectOrDomException) {
    //
    return false
  }
}

/**
 * @todo @@perf at least cache/memoize these functions to reduce dom reads
 */
export function getElementOrCreate(id: string) {
  return document.getElementById(id) || document.createElement('div')
}
export function hasElementFor(idOrElement: string | HTMLElement) {
  return isString(idOrElement)
    ? !!document.getElementById(idOrElement)
    : document.body.contains(idOrElement)
}
export function getElemetFor(id: string) {
  return document.getElementById(id)
}

export function appendToBodyIfRequired(node: HTMLElement) {
  if (!hasElementFor(node)) {
    console.warn(
      'did not have the dom in the body - if you are using `<Portal id="eh">`, then you should have an element with <div id="eh"> in the html body. this warning can be ignored in @skava/ui'
    )
    document.body.appendChild(node)
  } else {
    // console.debug('has node already')
  }
}