all files / src/ file.js

100% Statements 83/83
96.55% Branches 84/87
100% Functions 11/11
100% Lines 71/71
1 branch Ignored     
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                           176× 176×   176× 176× 176×   176× 170×     176× 18×         28×         158×     176× 176×   266× 284×     284×   283×   277× 45×   277×   269×     266× 266× 266× 279× 279× 279× 21× 21× 21×   34×         279× 53×   279× 50×     266×   258× 53× 53×               205× 50× 50×                         100×     296×       290×                           258×     155× 155×     21×    
import Validators from './index'
import { prepareMsg, prepare, selectNum, memoize, TO_STRING } from './helpers'
 
let ACCEPT_SEP_REG = /\s*,\s*/
let ESCAPE_REG = /([.+?^=!:${}()|[\]\/\\])/g // Removed star char
let ANY_REG = /\*/g
 
let file = memoize(function({
  message,
  msg,
  accept,
  minSize,
  maxSize,
  minFiles,
  maxFiles,
  if: ifCond,
  unless,
  allowBlank,
} = {}) {
  msg = msg || message
 
  minFiles = selectNum(minFiles)
  maxFiles = selectNum(maxFiles)
  if (maxFiles < 0) {
    maxFiles = null
  }
  if (null === minFiles) {
    minFiles = 1
  }
 
  if ('string' === typeof accept && accept.trim()) {
    accept = accept
      .trim()
      .toLowerCase()
      .split(ACCEPT_SEP_REG)
      .map(function(type) {
        return '.' === type.charAt(0) || type.indexOf('*') < 0
          ? type
          : new RegExp('^' + type.replace(ESCAPE_REG, '\\$1').replace(ANY_REG, '.*') + '$', 'i')
      })
  } else {
    accept = null
  }
 
  let min = null != minSize ? sizeToInt(minSize) : null
  let max = null != maxSize ? sizeToInt(maxSize) : null
 
  return prepare(ifCond, unless, false, function(value) {
    let isAFileList = isFileList(value)
 
    // special blank check
    if ((null != allowBlank ? allowBlank : Validators.defaultOptions.allowBlank) && isAFileList && 0 === value.length) {
      return
    }
    if (!isAFileList) {
      return Validators.formatMessage(prepareMsg(msg, 'file'))
    }
    if (isNaN(value.length)) {
      value = [value]
    }
    if (value.length < minFiles) {
      return Validators.formatMessage(prepareMsg(msg, 'fileTooFew', { count: minFiles }))
    }
    if (null !== maxFiles && value.length > maxFiles) {
      return Validators.formatMessage(prepareMsg(msg, 'fileTooMany', { count: maxFiles }))
    }
 
    let acceptError = []
    let tooSmallError = []
    let tooBigError = []
    for (let i = 0, len = value.length, val, ftype, fext; i < len; ++i) {
      val = value[i]
      if (accept) {
        ftype = val.type || ''
        fext = fileExt(val.name || '')
        if (
          !accept.some(function(type) {
            return 'string' === typeof type ? type === ('.' === type.charAt(0) ? fext : ftype) : type.test(ftype)
          })
        ) {
          acceptError.push(val)
        }
      }
      if (null != min && val.size < min) {
        tooSmallError.push(val)
      }
      if (null != max && val.size > max) {
        tooBigError.push(val)
      }
    }
    if (acceptError.length) {
      return Validators.formatMessage(prepareMsg(msg, 'fileAccept', { files: acceptError, count: acceptError.length }))
    }
    if (tooSmallError.length) {
      let pair = parse(minSize)
      return Validators.formatMessage(
        prepareMsg(msg, 'fileTooSmall', {
          files: tooSmallError,
          count: tooSmallError.length,
          size: Validators.formatSize(pair[1], pair[2] || 'B'),
        })
      )
    }
    if (tooBigError.length) {
      let pair = parse(maxSize)
      return Validators.formatMessage(
        prepareMsg(msg, 'fileTooBig', {
          files: tooBigError,
          count: tooBigError.length,
          size: Validators.formatSize(pair[1], pair[2] || 'B'),
        })
      )
    }
  })
})
 
export default file
 
export function formatSize(size, unit) {
  return size + ' ' + unit
}
 
export function isFileList(value) {
  if (
    ('undefined' !== typeof FileList && value instanceof FileList) ||
    ('undefined' !== typeof File && (value instanceof File || value[0] instanceof File))
  ) {
    return true
  }
  let str = TO_STRING.call(value)
  return '[object FileList]' === str || '[object File]' === str || '[object File]' === TO_STRING.call(value[0])
}
 
// private
const SIZE_REG = /^([\d\.]+)\s*([KMGTPE]?B)?$/
const SIZE_UNITS = {
  B: 1,
  KB: 1024,
  MB: 1048576,
  GB: 1073741824,
  TB: 1099511627776,
  PB: 1125899906842624,
  EB: 1152921504606847000,
}
 
function parse(size) {
  return SIZE_REG.exec(('' + size).trim())
}
 
function sizeToInt(size) {
  let pair = parse(size)
  return pair ? pair[1] * (SIZE_UNITS[pair[2]] || 1) : null
}
 
function fileExt(filename) {
  return filename.slice(((filename.lastIndexOf('.') - 1) >>> 0) + 1).toLowerCase()
}