All files addtopage.js

85.19% Statements 23/27
78.57% Branches 22/28
100% Functions 5/5
84% Lines 21/25
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  1x     7x       2x       1x         1x               36x   12x 10x   7x       7x       12x 2x 10x         12x         12x   12x 9x 3x 3x 3x           12x        
// Tie element types to a test using the file name
const elementTypeTest = [
  {
    element: 'image',
    test: (filename) => /\.(gif|jp[e]?g|png|svg)$/.test(filename)
  },
  {
    element: 'script',
    test: (filename) => /js[x]?$/.test(filename)
  },
  {
    element: 'style',
    test: (filename) => /css$/.test(filename)
  }
]
 
// All element types we know
const knownElementTypes = [
  'iframe',
  'image',
  'link',
  'script',
  'style'
]
 
function addtopage(resource, { inline = false, type = undefined } = {}) {
  // If not given a type, try to infer it from the file name (esp. the file extension)
  if (!type) {
    const testType = elementTypeTest.find(elementType => elementType.test(resource))
 
    Iif (!testType) {
      throw new Error(`Cannot guess element needed for unknown file type: ${resource}`)
    }
 
    type = testType.element
  }
 
  // Correct style and link tags when necessary
  if (!inline && type === 'style') {
    type = 'link'
  } else Iif (inline && type === 'link') {
    type = 'style'
  }
 
  // Ensure we are only working with an element we know
  Iif (!knownElementTypes.includes(type)) {
    throw new Error(`Cannot create element of unknown type: ${type}`)
  }
 
  // Create the element
  var newElement = document.createElement(type)
 
  if (!inline && type !== 'link') {
    newElement.src = resource
  } else Eif (type === 'link') {
    newElement.href = resource
    newElement.rel = 'stylesheet'
  } else {
    // TODO: write logic for inlining resource contents
    throw new Error('Creating inline resources is not yet implemented')
  }
 
  return document.body.appendChild(newElement)
}
 
export default addtopage