JSFiddle - React, Tailwind, and code Playground
HTML
<x-file label="Pick a File" max-megabyte="4" data-show-error="true" data-error="You've exceded the maximum size.">
<template id="alert">
<p class="alert">
<span class="msg"></span>
</p>
</template>
<div class="file field">
<label>${label}</label>
<input as="file-input" type="file" multiple />
</div>
</x-file>
JavaScript
xtag.register('x-file', {
extends: 'div',
lifecycle: {
created: function () {
var tmpl = this.innerHTML || this.parseTemplate()
this.alertNode = this.querySelector('#alert').content
xtag.innerHTML(this, tmpl )
}
},
events: {
'change:delegate(input[type=file])': function (e) {
e.preventDefault();
var parent = e.currentTarget
parent.validate();
}
},
methods: {
validate: function (e) {
if ( !(window.File && window.FileList) ) {
return
}
var input = e? e.target: this.querySelector('input[as=file-input]')
var files = Array.prototype.slice.call(input.files)
var size = arraySum(files.map(function (it) {return it.size}))
if (size > 10000) {
this.displayError()
} else {
this.removeError()
}
},
displayError: function (msg) {
var clone = this.alertNode.cloneNode(true)
var msg = clone.querySelector('.msg')
msg.innerHTML = msg || this.dataset.error
this.dataset.alertNode = clone.firstElementChild
console.dir(clone)
this.appendChild(clone)
this.dataset.errorShowing = true
},
removeError: function () {
if (this.dataset.errorShowing) {
console.log('removing')
this.removeChild(this.dataset.alertNode)
}
this.dataset.errorShowing = false
},
parseTemplate: function () {
var tmpl = this.innerHTML
return tmpl;
}
}
})
var arraySum = (function () {
"use strict";
function sumFunc (arr) {
var sum = 0, i = 0, j = arr.length, cur, toAdd;
for (; i < j; i++) {
cur = arr[i];
...