From ade51b27fc6005dc21290bf76ba6859c251ac9f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20Zen?= Date: Sun, 5 Jun 2016 23:22:12 -0300 Subject: [PATCH] Support for image preview & drag and drop --- src/components/Widgets/ImageControl.js | 61 +++++++++++++++++++++++++- src/components/Widgets/ImagePreview.js | 8 +++- 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/src/components/Widgets/ImageControl.js b/src/components/Widgets/ImageControl.js index 40e1ffe9..19f1b051 100644 --- a/src/components/Widgets/ImageControl.js +++ b/src/components/Widgets/ImageControl.js @@ -4,13 +4,70 @@ export default class ImageControl extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); + this.handleFileInputRef = this.handleFileInputRef.bind(this); + this.handleClick = this.handleClick.bind(this); + this.handleDragEnter = this.handleDragEnter.bind(this); + this.handleDragOver = this.handleDragOver.bind(this); + } + + handleFileInputRef(el) { + this._fileInput = el; + } + + handleClick(e) { + this._fileInput.click(); + } + + handleDragEnter(e) { + e.stopPropagation(); + e.preventDefault(); + } + + handleDragOver(e) { + e.stopPropagation(); + e.preventDefault(); } handleChange(e) { - this.props.onChange(e.target.value); + e.stopPropagation(); + e.preventDefault(); + const fileList = e.dataTransfer ? e.dataTransfer.files : e.target.files; + const files = [...fileList]; + const imageType = /^image\//; + + // Iterate to list of files and return the first image on the list + const file = files.find((currentFile) => { + if (imageType.test(currentFile.type)) { + return currentFile; + } + }); + + this.props.onChange(file); } render() { - return ; + return ( +
+ Click or drop image here. + +
+ ); } } + +const styles = { + input: { + display: 'none' + } +}; diff --git a/src/components/Widgets/ImagePreview.js b/src/components/Widgets/ImagePreview.js index f93c5182..9db11ddc 100644 --- a/src/components/Widgets/ImagePreview.js +++ b/src/components/Widgets/ImagePreview.js @@ -3,11 +3,15 @@ import React from 'react'; export default class ImagePreview extends React.Component { constructor(props) { super(props); + this.handleImageLoaded = this.handleImageLoaded.bind(this); + } + + handleImageLoaded() { + window.URL.revokeObjectURL(this.props); } render() { const { value } = this.props; - - return value ? : null; + return value ? : null; } }