discourse/app/assets/javascripts/wizard/components/wizard-field-image.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

86 lines
2.4 KiB
JavaScript
Raw Normal View History

import Component from "@ember/component";
import { warn } from "@ember/debug";
import I18n from "I18n";
import { dasherize } from "@ember/string";
import discourseComputed from "discourse-common/utils/decorators";
import { getOwner } from "discourse-common/lib/get-owner";
import { getToken } from "wizard/lib/ajax";
import getUrl from "discourse-common/lib/get-url";
import Uppy from "@uppy/core";
import DropTarget from "@uppy/drop-target";
import XHRUpload from "@uppy/xhr-upload";
2016-09-09 04:58:07 +08:00
export default Component.extend({
2016-09-09 04:58:07 +08:00
classNames: ["wizard-image-row"],
uploading: false,
@discourseComputed("field.id")
previewComponent(id) {
const componentName = `image-preview-${dasherize(id)}`;
const exists = getOwner(this).lookup(`component:${componentName}`);
return exists ? componentName : "wizard-image-preview";
},
2016-09-09 04:58:07 +08:00
didInsertElement() {
this._super(...arguments);
this.setupUploads();
},
2016-09-09 04:58:07 +08:00
setupUploads() {
2016-09-09 04:58:07 +08:00
const id = this.get("field.id");
this._uppyInstance = new Uppy({
id: `wizard-field-image-${id}`,
meta: { upload_type: `wizard_${id}` },
autoProceed: true,
});
2016-09-09 04:58:07 +08:00
this._uppyInstance.use(XHRUpload, {
endpoint: getUrl("/uploads.json"),
headers: {
"X-CSRF-Token": getToken(),
2016-09-09 04:58:07 +08:00
},
});
this._uppyInstance.use(DropTarget, { target: this.element });
2016-09-09 04:58:07 +08:00
this._uppyInstance.on("upload", () => {
this.set("uploading", true);
});
this._uppyInstance.on("upload-success", (file, response) => {
this.set("field.value", response.body.url);
2016-09-09 04:58:07 +08:00
this.set("uploading", false);
});
this._uppyInstance.on("upload-error", (file, error, response) => {
2018-07-12 15:12:11 +08:00
let message = I18n.t("wizard.upload_error");
if (response.body.errors) {
message = response.body.errors.join("\n");
}
window.bootbox.alert(message);
this.set("uploading", false);
});
this.element
.querySelector(".wizard-hidden-upload-field")
.addEventListener("change", (event) => {
const files = Array.from(event.target.files);
files.forEach((file) => {
try {
this._uppyInstance.addFile({
source: `${this.id} file input`,
name: file.name,
type: file.type,
data: file,
});
} catch (err) {
warn(`error adding files to uppy: ${err}`, {
id: "discourse.upload.uppy-add-files-error",
});
}
});
});
2016-09-09 04:58:07 +08:00
},
});