UNPKG

json-editor

Version:
94 lines (81 loc) 3.09 kB
JSONEditor.defaults.editors.base64 = JSONEditor.AbstractEditor.extend({ getNumColumns: function() { return 4; }, build: function() { var self = this; this.title = this.header = this.label = this.theme.getFormInputLabel(this.getTitle()); // Input that holds the base64 string this.input = this.theme.getFormInputField('hidden'); this.container.appendChild(this.input); // Don't show uploader if this is readonly if(!this.schema.readOnly && !this.schema.readonly) { if(!window.FileReader) throw "FileReader required for base64 editor"; // File uploader this.uploader = this.theme.getFormInputField('file'); this.uploader.addEventListener('change',function(e) { e.preventDefault(); e.stopPropagation(); if(this.files && this.files.length) { var fr = new FileReader(); fr.onload = function(evt) { self.value = evt.target.result; self.refreshPreview(); self.onChange(true); fr = null; }; fr.readAsDataURL(this.files[0]); } }); } this.preview = this.theme.getFormInputDescription(this.schema.description); this.container.appendChild(this.preview); this.control = this.theme.getFormControl(this.label, this.uploader||this.input, this.preview); this.container.appendChild(this.control); }, refreshPreview: function() { if(this.last_preview === this.value) return; this.last_preview = this.value; this.preview.innerHTML = ''; if(!this.value) return; var mime = this.value.match(/^data:([^;,]+)[;,]/); if(mime) mime = mime[1]; if(!mime) { this.preview.innerHTML = '<em>Invalid data URI</em>'; } else { this.preview.innerHTML = '<strong>Type:</strong> '+mime+', <strong>Size:</strong> '+Math.floor((this.value.length-this.value.split(',')[0].length-1)/1.33333)+' bytes'; if(mime.substr(0,5)==="image") { this.preview.innerHTML += '<br>'; var img = document.createElement('img'); img.style.maxWidth = '100%'; img.style.maxHeight = '100px'; img.src = this.value; this.preview.appendChild(img); } } }, enable: function() { if(this.uploader) this.uploader.disabled = false; this._super(); }, disable: function() { if(this.uploader) this.uploader.disabled = true; this._super(); }, setValue: function(val) { if(this.value !== val) { this.value = val; this.input.value = this.value; this.refreshPreview(); this.onChange(); } }, destroy: function() { if(this.preview && this.preview.parentNode) this.preview.parentNode.removeChild(this.preview); if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title); if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input); if(this.uploader && this.uploader.parentNode) this.uploader.parentNode.removeChild(this.uploader); this._super(); } });