Browse Source

Merge pull request #5 from angusmcleod/pr/4

Add upload component
Angus McLeod 6 years ago
parent
commit
5c7ab3d550

+ 51 - 0
assets/javascripts/wizard/components/wizard-field-upload.js.es6

@@ -0,0 +1,51 @@
+import getUrl from "discourse-common/lib/get-url";
+import { getToken } from "wizard/lib/ajax";
+
+export default Ember.Component.extend({
+  classNames: ["wizard-field-upload"],
+  uploading: false,
+
+  didInsertElement() {
+    this._super();
+
+    const $upload = this.$();
+
+    const id = this.get("field.id");
+
+    $upload.fileupload({
+      url: getUrl("/uploads.json"),
+      formData: {
+        synchronous: true,
+        type: `wizard_${id}`,
+        authenticity_token: getToken()
+      },
+      dataType: "json",
+      dropZone: $upload
+    });
+
+    $upload.on("fileuploadsubmit", () => this.set("uploading", true));
+
+    $upload.on("fileuploaddone", (e, response) => {
+      this.setProperties({
+        "field.value": response.result,
+        "uploading": false
+      });
+    });
+
+    $upload.on("fileuploadfail", (e, response) => {
+      let message = I18n.t("wizard.upload_error");
+      if (response.jqXHR.responseJSON && response.jqXHR.responseJSON.errors) {
+        message = response.jqXHR.responseJSON.errors.join("\n");
+      }
+
+      window.swal({
+        customClass: "wizard-warning",
+        title: "",
+        text: message,
+        type: "warning",
+        confirmButtonColor: "#6699ff"
+      });
+      this.set("uploading", false);
+    });
+  }
+});

+ 16 - 0
assets/javascripts/wizard/templates/components/wizard-field-upload.hbs

@@ -0,0 +1,16 @@
+<label class="wizard-btn wizard-btn-upload-file {{if uploading 'disabled'}}">
+  {{#if uploading}}
+    {{i18n "wizard.uploading"}}
+  {{else}}
+    {{i18n "wizard.upload"}}
+    {{d-icon "upload"}}
+  {{/if}}
+
+  <input disabled={{uploading}} type="file" accept="image/*,application/pdf" style="visibility: hidden; position: absolute;" />
+</label>
+
+{{#if field.value}}
+  <a href="{{field.value.url}}" class="filename">
+    {{field.value.original_filename}}
+  </a>
+{{/if}}

+ 19 - 0
assets/stylesheets/wizard/wizard_custom.scss

@@ -218,6 +218,25 @@
     margin: 0;
   }
 
+  .wizard-field-upload {
+    .wizard-btn-upload-file {
+      display: inline-block;
+      position: relative;
+      cursor: pointer;
+
+      input {
+        left: 0;
+        right: 0;
+        top: 0;
+        bottom: 0;
+      }
+    }
+
+    .filename {
+      margin-left: 10px;
+    }
+  }
+
   .wizard-column .wizard-field .input-area {
     margin: 0.5em 0;
   }

+ 1 - 1
lib/field.rb

@@ -1,6 +1,6 @@
 class CustomWizard::Field
   def self.types
-    @types ||= ['text', 'textarea', 'dropdown', 'image', 'checkbox', 'user-selector', 'text-only', 'composer']
+    @types ||= ['checkbox', 'composer', 'dropdown', 'image', 'text', 'textarea', 'text-only', 'upload', 'user-selector']
   end
 
   def self.require_assets