From 3c1172a9196d85da9f141a0e942cfe6e0b6cca07 Mon Sep 17 00:00:00 2001
From: Tim Canty <timmcanty@gmail.com>
Date: Wed, 13 Apr 2016 17:39:14 -0400
Subject: [PATCH] [FEATURE] Uses accept field to validate provided filetypes

---
 addon/components/file-picker.js           | 18 ++++++++++++++++++
 tests/unit/components/file-picker-test.js | 20 +++++++++++++++++++-
 2 files changed, 37 insertions(+), 1 deletion(-)

diff --git a/addon/components/file-picker.js b/addon/components/file-picker.js
index d0fa5d6..456017d 100644
--- a/addon/components/file-picker.js
+++ b/addon/components/file-picker.js
@@ -73,6 +73,20 @@ export default Component.extend({
     }
   },
 
+  _invalidExtension: function(files) {
+    let accept = this.get('accept');
+
+    if (accept === '*') {
+      return;
+    }
+
+    let validExtensions = accept.split(',');
+
+    let fileExtensions = files.map(file => `.${file.filename.split('.').slice(-1)[0]}`);
+
+    return fileExtensions.some(extension => validExtensions.indexOf(extension) === -1);
+  },
+
   handleFiles: function(files) {
     if (typeof(this.filesAreValid) === 'function') {
       if (!this.filesAreValid(files)) {
@@ -80,6 +94,10 @@ export default Component.extend({
       }
     }
 
+    if (this._invalidExtension(files)) {
+      return;
+    }
+
     if (this.get('preview')) {
       this.updatePreview(files);
     }
diff --git a/tests/unit/components/file-picker-test.js b/tests/unit/components/file-picker-test.js
index 6224459..0c93a8d 100644
--- a/tests/unit/components/file-picker-test.js
+++ b/tests/unit/components/file-picker-test.js
@@ -90,4 +90,22 @@ test('it shows file input', function(assert) {
   this.render();
 
   assert.equal(component.$('input:hidden').length, 0);
-});
\ No newline at end of file
+});
+
+test('it rejects improper filetypes', function(assert) {
+  assert.expect(2);
+
+  const component = this.subject({
+    accept: '.jpg,.jpeg',
+    multiple: true
+  });
+
+  const files = [
+    { filename: 'goodfile.jpg' },
+    { filename: 'good_file.jpeg' },
+    { filename: 'badfile.html' }
+  ];
+
+  assert.strictEqual(component._invalidExtension(files), true);
+  assert.strictEqual(component._invalidExtension(files.slice(0, 2)), false);
+});