import {classOf} from "./common";
export default (Vue)=>{
Vue.directive('justify-width',{
bind(element){
element._$loadWidthHandler = (event)=>{
let img = event.target;
img.style.setProperty('width',`${(img.naturalWidth || img.width) / window.ROOT_FONT_SIZE}rem`);
};
element.addEventListener('load',element._$loadWidthHandler);
},
unbind(element){
element.removeEventListener('load',element._$loadWidthHandler);
}
});
Vue.directive('justify-height',{
bind(element){
element._$loadHeightHandler = (event)=>{
let img = event.target;
img.style.setProperty('height',`${(img.naturalHeight || img.height) / window.ROOT_FONT_SIZE}rem`);
};
element.addEventListener('load',element._$loadHeightHandler);
},
unbind(element){
element.removeEventListener('load',element._$loadHeightHandler);
}
});
Vue.directive('element-init',{
bind(element,binding,vNode){
let component = vNode.context;
let elementInit = binding.expression;
component[elementInit](element,binding.modifiers);
},
unbind(element,binding,vNode){
}
});
Vue.directive('element-unbind',{
bind(element,binding,vNode){
},
unbind(element,binding,vNode){
let component = vNode.context;
let elementUnbind = binding.expression;
component[elementUnbind](element,binding.modifiers);
}
});
function CustomEvent (event, params) {
params = params || {bubbles: false, cancelable: false, detail: undefined}
var evt = document.createEvent('CustomEvent')
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
return evt
}
(function () {
if (typeof window.CustomEvent !== 'function') {
CustomEvent.prototype = window.Event.prototype
window.CustomEvent = CustomEvent
}
})()
HTMLElement.prototype.$_listenWheel = function (event) {
if (classOf(event) === 'WheelEvent') {
var target = this
target.$_prevScrollTop = target.$_prevScrollTop || 0
target.$_prevScrollLeft = target.$_prevScrollLeft || 0
if (target.$_wheelLocked) {
return event.preventDefault()
}
var scrollHeight = target.scrollHeight
var scrollWidth = target.scrollWidth
var clientHeight = target.clientHeight
var clientWidth = target.clientWidth
var scrollTop = target.scrollTop
var scrollLeft = target.scrollLeft
try {
let customToEvent = new CustomEvent('customscroll')
customToEvent.deltaX = event.deltaX
customToEvent.deltaY = event.deltaY
if (target.$_prevScrollTop !== scrollTop && scrollTop === 0) {
customToEvent.toBoundary = 'top'
}
if (target.$_prevScrollLeft !== scrollLeft && scrollLeft === 0) {
customToEvent.toBoundary = 'left'
}
if (event.deltaY && !event.deltaX) {
customToEvent.details = 'to-bottom'
if (Math.abs(scrollTop + clientHeight - scrollHeight) <= 1) {
if (target.$_prevScrollTop !== scrollTop) {
customToEvent.toBoundary = 'bottom'
}
}
} else if (!event.deltaY && event.deltaX) {
customToEvent.details = 'to-right'
if (Math.abs(scrollLeft + clientWidth - scrollWidth) <= 1) {
if (target.$_prevScrollLeft !== scrollLeft) {
customToEvent.toBoundary = 'right'
}
}
}
if (target.oncustomscroll) {
target.oncustomscroll(customToEvent)
} else {
target.dispatchEvent(customToEvent)
}
if (target.$_wheelEventPrevented) {
event.preventDefault()
}
} finally {
target.$_prevScrollTop = scrollTop
target.$_prevScrollLeft = scrollLeft
}
}
}
Vue.directive('load-more', {
bind: function (element, binding, vNode, oldVnode) {
let funcName = binding.value
let modifiers = binding.modifiers
if (funcName) {
if (!element.$_loadMoreListener) {
element.$_loadMoreListener = function (event) {
let detail = event.detail
if (!element.$_wheelLocked) {
let c = vNode.context
let func = typeof funcName === 'function' ? funcName : typeof c[funcName] === 'function' ? c[funcName] : undefined
if (func) {
if (!modifiers.bottom && !modifiers.right) {
element.$_wheelLocked = true
func(function (data) {
element.$_wheelLocked = undefined
}, function (data) {
element.$_wheelLocked = undefined
}, detail)
} else {
for (let pro in modifiers) {
if (modifiers[pro]) {
if (detail === pro) {
element.$_wheelLocked = true
func(function (data) {
element.$_wheelLocked = undefined
}, function (data) {
element.$_wheelLocked = undefined
}, detail)
}
}
}
}
}
}
}
element.addEventListener('scroll-to-load-more', element.$_loadMoreListener)
}
if (!element.$_wheelListener) {
element.$_wheelListener = function (event) {
this.$_listenWheel(event)
}
element.addEventListener('wheel', element.$_wheelListener)
}
if (!element.$_customScrollListenerLoadMore) {
element.$_customScrollListenerLoadMore = function (customScrollEvent) {
if (customScrollEvent.toBoundary === 'bottom' || customScrollEvent.toBoundary === 'right') {
!this.$_wheelLocked && this.dispatchEvent(new CustomEvent('scroll-to-load-more', {
detail: customScrollEvent.toBoundary
}))
}
}
element.addEventListener('customscroll', element.$_customScrollListenerLoadMore)
}
} else {
throw new Error('v-scroll-to-load-more has no value!!!')
}
},
unbind: function (element, binding, vNode, oldVnode) {
element.removeEventListener('scroll-to-load-more', element.$_loadMoreListener)
element.removeEventListener('wheel', element.$_wheelListener)
element.removeEventListener('customscroll', element.$_customScrollListenerLoadMore)
element.$_loadMoreListener = null
element.$_wheelListener = null
element.$_customScrollListenerLoadMore = null
}
}
);
function insertNoScrollbarCssRule2Head (cssRule) {
let head = document.head
let style = document.getElementById('styleForNoScrollbar')
if (!style) {
style = document.createElement('style')
style.setAttribute('id', 'styleForNoScrollbar')
head.appendChild(style)
}
style.innerText += cssRule
}
Vue.directive('no-scrollbar', {
bind: function (element, binding, vNode, oldVnode) {
element.setAttribute('data-v-no-scroll', 'ns-' + new Date().getTime())
let modifiers = binding.modifiers
if (/webkit/i.test(window.navigator.userAgent)) {
let css = '[data-v-no-scroll=' + element.getAttribute('data-v-no-scroll') + ']::-webkit-scrollbar{display:none;}'
insertNoScrollbarCssRule2Head(css)
if (Object.keys(modifiers).length > 0) {
}
return
} else {
let regExp = /firefox\/(\d+(.\d+)?)/i
let exc = regExp.exec(window.navigator.userAgent)
if (exc) {
let version = exc[1]
if (version > 64) {
let css = '[data-v-no-scroll=' + element.getAttribute('data-v-no-scroll') + ']{scrollbar-width:none;}'
insertNoScrollbarCssRule2Head(css)
if (Object.keys(modifiers).length > 0) {
}
return
}
}
}
function makeNoScrollbar (where) {
switch (where) {
case 'right':
case 'y':
element.style.setProperty('overflow-y', 'hidden')
break
case 'bottom':
case 'x':
element.style.setProperty('overflow-x', 'hidden')
break
default:
element.style.setProperty('overflow', 'hidden')
break
}
}
let set = false
modifiers && ((mdfs) => {
for (let pro in mdfs) {
if (mdfs.hasOwnProperty(pro)) {
makeNoScrollbar(pro)
set = true
}
}
})(modifiers)
!set && makeNoScrollbar(null)
if (!element.$_customScrollListener) {
element.$_customScrollListener = function (event) {
if (event.details === 'to-bottom') {
let maxScrollTop = this.maxScrollTop
let newScrollTop = Math.max(Math.min(maxScrollTop, this.scrollTop + event.deltaY / 8), 0)
this.scrollTop = newScrollTop
if (maxScrollTop === 0 || event.toBoundary === 'bottom' || event.toBoundary === 'top' || event.toBoundary === 'right' || event.toBoundary === 'left') {
this.$_wheelEventPrevented = false
} else {
this.$_wheelEventPrevented = true
}
} else if (event.details === 'to-right') {
let maxScrollLeft = this.maxScrollLeft
let newScrollLeft = Math.max(Math.min(maxScrollLeft, this.scrollLeft + event.deltaX / 8), 0)
this.scrollLeft = newScrollLeft
if (maxScrollLeft === 0 || event.toBoundary === 'bottom' || event.toBoundary === 'top' || event.toBoundary === 'right' || event.toBoundary === 'left') {
this.$_wheelEventPrevented = false
} else {
this.$_wheelEventPrevented = true
}
}
}
element.addEventListener('customscroll', element.$_customScrollListener)
}
if (!element.$_wheelListener) {
element.$_wheelListener = function (event) {
element.$_listenWheel(event)
}
element.addEventListener('wheel', element.$_wheelListener)
}
},
unbind: function (element, binding, vNode, oldVnode) {
element.removeEventListener('wheel', element.$_wheelListener)
element.removeEventListener('customscroll', element.$_customScrollListener)
element.$_wheelListener = null
element.$_customScrollListener = null
}
});
Vue.directive('fix-click', {
bind: function (element, binding, vNode, oldVnode) {
let directiveValue = binding.value
let modifiers = binding.modifiers
let c = vNode.context
let func = typeof directiveValue === 'function' ? directiveValue : typeof directiveValue['click'] === 'function' ? directiveValue['click'] : undefined
let care = directiveValue.care
let targetSelector = care && care.targetSelector
let excludeSelectors = care && care.excludeSelectors
let prop = care && care.prop
element.$_mouseDownCall = function (event) {
if (event.button === 0) {
if (!this.$_upTime) {
this.$_upTime = 0
}
let time = new Date().getTime()
let deltaTime = time - this.$_upTime
this.$_doubleClicked = deltaTime < 250
if (this.$_doubleClicked) {
window.clearTimeout(this.$_clickTimeout)
}
this.$_PageX0 = this.$_PageX = event.pageX
this.$_PageY0 = this.$_PageY = event.pageY
}
}
element.$_mouseMoveCall = function (event) {
if (event.button === 0) {
this.$_PageX = event.pageX
this.$_PageY = event.pageY
}
}
element.$_mouseUpCall = function (event) {
if (event.button === 0) {
this.$_upTime = new Date().getTime()
this.$_PageX = event.pageX
this.$_PageY = event.pageY
let disSquare = Math.pow(this.$_PageX - this.$_PageX0, 2) + Math.pow(this.$_PageY - this.$_PageY0, 2)
if (disSquare < 36) {
if (!this.$_doubleClicked) {
this.$_clickTimeout = setTimeout(function () {
if (!this.$_doubleClicked) {
if (!targetSelector) {
func && func()
} else {
if (!excludeSelectors || !(excludeSelectors.some((s) => {
return event.target.closest(s)
}))) {
let target = event.target.closest(targetSelector)
if (target) {
if (prop) {
func && func(target[prop])
} else {
func && func(target)
}
} else {
}
}
}
}
window.clearTimeout(this.$_clickTimeout)
}.bind(this), 250)
}
}
}
}
element.addEventListener('mouse' + 'down', element.$_mouseDownCall)
element.addEventListener('mouse' + 'up', element.$_mouseUpCall)
element.addEventListener('mouse' + 'move', element.$_mouseMoveCall)
},
unbind: function (element, binding, vNode, oldVnode) {
element.removeEventListener('mouse' + 'down', element.$_mouseDownCall)
element.removeEventListener('mouse' + 'up', element.$_mouseUpCall)
element.removeEventListener('mouse' + 'move', element.$_mouseMoveCall)
element.$_mouseDownCall = null
element.$_mouseUpCall = null
element.$_mouseMoveCall = null
}
});
}
import moment from "moment";
export function classOf(obj) {
if (obj === null) {
return 'null';
} else if (typeof obj !== 'object') {
return typeof obj;
} else {
if (obj.constructor.name) {
return obj.constructor.name.trim();
} else {
let funcStr = obj.constructor.toString();
if (funcStr.indexOf('function') > -1) {
return funcStr.substring(9, funcStr.indexOf('(')).trim();
} else if (funcStr.indexOf('[object') > -1) {
return funcStr.substring(8, funcStr.length - 1).trim();
}
}
}
}
export function itEqual(a, b) {
let r = (function (obj, other) {
let type = classOf(obj).toLowerCase();
let typeOther = classOf(other).toLowerCase();
if (type === typeOther) {
switch (type) {
case 'null':
case 'undefined':
return typeOther === 'null' || typeOther === 'undefined';
case 'number':
case 'string':
return obj + '' === other + '';
default:
return JSON.stringify(obj) === JSON.stringify(other);
}
} else if (typeOther === 'number' && type === 'number'
|| typeOther === 'string' && type === 'string'
|| typeOther === 'string' && type === 'number'
|| typeOther === 'number' && type === 'string') {
return obj + '' === other + '';
} else {
return false;
}
}(a, b));
return r;
}
export function emptyObj(obj, p, excludedProps) {
if (obj) {
if (p) {
if (excludedProps && excludedProps.some && excludedProps.some(function (prop) {
return prop === p
})) {
return;
}
let type = classOf(obj[p]).toLowerCase();
switch (type) {
case 'string':
obj[p] = '';
return;
case 'object':
for (let pro in obj[p]) {
if (pro.indexOf('_') === 0 || !obj[p].hasOwnProperty(pro)) {
continue;
}
emptyObj(obj[p], pro, excludedProps);
}
return;
case 'number':
obj[p] = 0;
return;
case 'boolean':
obj[p] = false;
return;
case 'date':
obj[p].setTime(new Date().getTime());
return;
case 'array':
obj[p].splice(0);
return;
}
return obj[p] = undefined;
} else {
for (let pro in obj) {
if (excludedProps && excludedProps.some && excludedProps.some(function (prop) {
return prop === pro
}) || pro.indexOf('_') === 0 || !obj.hasOwnProperty(pro)) {
continue;
}
emptyObj(obj, pro, excludedProps);
}
}
}
}
export function clearVueData(vue, excludedProps) {
let data = vue.$data;
emptyObj(data, null, excludedProps);
}
export function ITMap() {
if (this instanceof ITMap) {
this.keys = [];
this.values = []
} else {
return new ITMap();
}
}
ITMap.prototype.clear = function(){
this.keys = [];
this.values = []
};
ITMap.prototype.put = function(key, value){
let index = -1;
this.keys.some((k, i) => {
if (k === key) {
index = i;
return true
}
});
if (index!==-1) {
this.values[index] = value;
} else {
this.keys.push(key);
this.values.push(value);
}
};
ITMap.prototype.get = function(key) {
if (this.keys && this.keys.length) {
let index = -1;
this.keys.some((k, i) => {
if (k === key) {
index = i;
return true;
}
});
return this.values && this.values[index];
}
};
export var itDocCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
export function getSearchValue(name,search) {
search = search || location.search;
let value = undefined;
if(search){
search = search.substr(1);
let searchArgs = search.split(/&/);
if(searchArgs){
searchArgs.some((searchArg)=>{
if(searchArg){
let nameAndValue = searchArg.split(new RegExp(`${name}=`));
if(nameAndValue && nameAndValue.length>1){
value = nameAndValue[1];
return true
}
}
})
}
}
return value;
}
export function replaceRouteWithParamsObject (vueComponent, paramsObject, noReplace, onComplete, onAbort) {
if (!paramsObject) {
throw new Error('paramsObject can not be undefined or null.')
}
let preParamsObject = getParamsObjectFromRoute(vueComponent)
if (preParamsObject) {
paramsObject = {
...preParamsObject,
...paramsObject
}
}
paramsObject = JSON.stringify(paramsObject)
paramsObject = encodeURIComponent(paramsObject)
let forReplace = {
name: vueComponent.$route.name,
params: {
...vueComponent.$route.params,
extraParams: paramsObject
}
}
if (vueComponent.$route.meta) {
forReplace.meta = {...vueComponent.$route.meta}
}
if (!noReplace) {
vueComponent.$router.replace(forReplace, onComplete, onAbort)
} else {
return forReplace
}
}
export function getParamsObjectFromRoute (vueComponent, name) {
let paramsObject = vueComponent.$route.params.extraParams
if (paramsObject) {
paramsObject = decodeURIComponent(paramsObject)
paramsObject = JSON.parse(paramsObject)
if (name) {
return paramsObject[name]
} else {
return paramsObject
}
}
}
export function formatDate(date,onlyDate,seperatorPre,seperatorSuf){
if(!(date instanceof Date)){
date = new Date();
}
var seperator1 = seperatorPre?seperatorPre:"-";
var seperator2 = seperatorSuf?seperatorSuf:":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate;
if(onlyDate){
currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
}else{
currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
}
return currentdate;
}
export function getContentDispositionFileName(headers, defaultName) {
var contentDisposition = headers.get ? headers.get('Content-Disposition') : headers['Content-Disposition']
|| headers.get ? headers.get('content-Disposition') : headers['content-Disposition']
|| headers.get ? headers.get('content-disposition') : headers['content-disposition'];
var regExp = /(?:filename=)([^;]+)(;?)/i;
var fileName = undefined;
var matches = contentDisposition && contentDisposition.match(regExp);
if (matches && matches.length > 1) {
fileName = matches[1];
fileName = decodeURIComponent(fileName);
}
return fileName ? fileName : defaultName;
}
export function saveBlobFile(blob, fileName) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style.setProperty('display', 'none');
a.href = objectUrl;
a.download = fileName;
a.click();
setTimeout(function () {
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
})
}
}
window._$_KEY_CNT = 0;
export function generateKey() {
return `${new Date().getTime()}${Math.floor(Math.random() * (10000 - 1000)) + 1000}${window._$_KEY_CNT++}`
}
export function reasonableFileSizeUnit(sizeSum,sizeUnit) {
sizeUnit = sizeUnit || 'b';
let unit = 'b';
if (sizeUnit === 'b' && sizeSum > 1024) {
unit = 'Kb';
sizeSum /= 1024;
}
if ((sizeUnit === 'b' || sizeUnit === 'Kb') && sizeSum > 1024) {
unit = 'Mb';
sizeSum /= 1024;
}
return {
size: sizeSum.toFixed(1) - 0,
unit
};
}
export function getIEVersion() {
var rv = -1;
var ua = window.navigator.userAgent;
var re = null;
if (window.navigator.appName === 'Microsoft Internet Explorer') {
re = new RegExp('MSIE ([0-9]+[\.0-9]*)');
if (re.exec(ua) !== null) {
rv = parseFloat(RegExp.$1);
}
} else if (window.navigator.appName === 'Netscape') {
re = new RegExp('Trident/.*rv:([0-9]+[\.0-9]*)');
if (re.exec(ua) !== null) {
rv = parseFloat(RegExp.$1);
}
}
return rv;
}
export function readFileAsDataURL(file) {
return new Promise((resolve, reject)=>{
let fileReader = new FileReader();
fileReader.onload = (event)=>{
resolve(fileReader.result);
};
fileReader.onerror = (event)=>{
reject(event);
};
fileReader.readAsDataURL(file);
});
}
export function downloadFileByAnchor(href) {
let a = document.createElement('a');
a.style.setProperty('display','none');
a.setAttribute('href',href);
a.setAttribute('target','_blank');
document.body.appendChild(a);
a.click();
setTimeout(()=>{
document.body.removeChild(a);
});
}
export function groupArrayByColumnCnt(array,columnCnt) {
let arr = [];
let rowCnt = Math.ceil(array.length / columnCnt);
for (let i = 0;i < rowCnt;i++){
arr.push([]);
}
for (let i = 0;i < array.length;i++){
let rowIndex = Math.floor(i / columnCnt);
let columnIndex = i % columnCnt;
arr[rowIndex][columnIndex] = array[i];
}
return arr;
}
export function dateFormat(date,format) {
if(date){
format = format ? format :'YYYY-MM-DD HH:mm:ss';
return moment(date).format(format);
}
}