yyzone
Version:
yyzone vue components and utils
310 lines (272 loc) • 8.22 kB
JavaScript
import Vue from 'vue'
const isServer = Vue.prototype.$isServer
// oneOf
export function oneOf (value, validList) {
for (let i = 0; i < validList.length; i++) {
if (value === validList[i]) {
return true
}
}
return false
}
// typeOf
export function typeOf(obj) {
const toString = Object.prototype.toString
const types = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
}
return types[toString.call(obj)] || 'undefined'
}
// deepCopy
export function deepCopy(obj, cache) {
if (cache === void 0) cache = []
if (obj === null || typeof obj !== 'object') {
return obj
}
// let hit = cache.find(function (c) {
// return c.original === obj
// })
// 兼容IE 11
let hit = null
for (let i = 0;i < cache.length;i ++) {
let c = cache[i]
if (c.original === obj) {
hit = c
break
}
}
if (hit) {
return hit.copy
}
let copy = Array.isArray(obj) ? [] : {}
cache.push({
original: obj,
copy: copy
})
Object.keys(obj).forEach(function (key) {
copy[key] = deepCopy(obj[key], cache)
})
return copy
}
// getScrollBarSize
let cached
export function getScrollBarSize (fresh) {
if (isServer) return 0
if (fresh || cached === undefined) {
const inner = document.createElement('div')
inner.style.width = '100%'
inner.style.height = '200px'
const outer = document.createElement('div')
const outerStyle = outer.style
outerStyle.position = 'absolute'
outerStyle.top = 0
outerStyle.left = 0
outerStyle.pointerEvents = 'none'
outerStyle.visibility = 'hidden'
outerStyle.width = '200px'
outerStyle.height = '150px'
outerStyle.overflow = 'hidden'
outer.appendChild(inner)
document.body.appendChild(outer)
const widthContained = inner.offsetWidth
outer.style.overflow = 'scroll'
let widthScroll = inner.offsetWidth
if (widthContained === widthScroll) {
widthScroll = outer.clientWidth
}
document.body.removeChild(outer)
cached = widthContained - widthScroll
}
return cached
}
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g
const MOZ_HACK_REGEXP = /^moz([A-Z])/
function camelCase(name) {
return name.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter
}).replace(MOZ_HACK_REGEXP, 'Moz$1');
}
// getStyle
export function getStyle (element, styleName) {
if (!element || !styleName) return null
styleName = camelCase(styleName)
if (styleName === 'float') {
styleName = 'cssFloat'
}
try {
const computed = document.defaultView.getComputedStyle(element, '');
return element.style[styleName] || computed ? computed[styleName] : null
} catch(e) {
return element.style[styleName]
}
}
// first upperCase
export function firstUpperCase(str) {
return str.toString()[0].toUpperCase() + str.toString().slice(1)
}
// find component
export function findComponentUpward (context, componentName, componentNames) {
if (typeof componentName === 'string') {
componentNames = [componentName]
} else {
componentNames = componentName
}
let parent = context.$parent
let name = parent.$options.name
while (parent && (!name || componentNames.indexOf(name) < 0)) {
parent = parent.$parent
if (parent) name = parent.$options.name
}
return parent
}
export function findComponentDownward (context, componentName) {
const childrens = context.$children
let children = null
if (childrens.length) {
for (const child of childrens) {
const name = child.$options.name
if (name === componentName) {
children = child
break
} else {
children = findComponentDownward(child, componentName)
if (children) break
}
}
}
return children
}
// find components
export function findComponentsUpward (context, componentName) {
let parents = []
const parent = context.$parent
if (parent) {
if (parent.$options.name === componentName) parents.push(parent)
return parents.concat(findComponentsUpward(parent, componentName))
} else {
return []
}
}
export function findComponentsDownward (context, componentName) {
return context.$children.reduce((components, child) => {
if (child.$options.name === componentName) components.push(child)
const foundChilds = findComponentsDownward(child, componentName)
return components.concat(foundChilds)
}, [])
}
// hasClass
export function hasClass(el, cls) {
if (!el || !cls) return false
if (cls.indexOf(' ') !== -1) throw new Error('className should not contain space.')
if (el.classList) {
return el.classList.contains(cls)
}
return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1
}
// addClass
export function addClass(el, cls) {
if (!el) return
let curClass = el.className
const classes = (cls || '').split(' ')
for (let i = 0, j = classes.length ;i < j; i++) {
const clsName = classes[i]
if (!clsName) continue
if (el.classList) {
return el.classList.add(clsName)
}
if (!hasClass(el, clsName)) {
return curClass += ' ' + clsName
}
}
if (!el.classList) {
el.className = curClass
}
}
// removeClass
export function removeClass(el, cls) {
if (!el || !cls) return
const classes = cls.split(' ')
let curClass = ' ' + el.className + ' '
for (let i = 0, j = classes.length; i < j; i++) {
const clsName = classes[i]
if (!clsName) continue
if (el.classList) {
return el.classList.remove(clsName)
}
if (hasClass(el, clsName)) {
return curClass = curClass.replace(' ' + clsName + ' ', ' ')
}
}
if (!el.classList) {
el.className = trim(curClass)
}
}
//普通字符转换成转意符
export function htmlEscape(str) {
if (str && typeof str == 'string') {
return str.replace(/[\<\>\&\"\']/g, function (c) {
return {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
'\'': '''
} [c]
})
}
return str
}
//转意符换成普通字符
export function escapeHtml(str) {
if (str && typeof str == 'string') {
let arrEntities = {
'lt': '<',
'gt': '>',
'nbsp': ' ',
'amp': '&',
'quot': '"',
'#60': '<',
'#62': '>',
'#38': '&',
'#34': '"',
'#39': '\''
}
return str.replace(/&(lt|gt|nbsp|amp|quot|\#(:?60|62|38|34|39))?/ig, function (all, t) {
return arrEntities[t]
})
}
return str
}
// 转换URL
export function revertURL() {
let {
protocol,
host,
pathname,
hash,
search
} = window.location
if (search !== '') {
window.location.href = decodeURIComponent([protocol, '//', host, pathname, hash, search].join(''))
}
}
// bytesToSize
export function bytesToSize(bytes) {
if(typeof bytes == 'string'){
bytes = parseInt(bytes)
}
if (bytes === 0) return '0 B'
var k = 1024
var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
var i = Math.floor(Math.log(bytes) / Math.log(k))
return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i] //toPrecision(3) 后面保留一位小数,如1.0GB
}