Sha256: b0a71cb5ff7b3a465c59c5c463c8bd44dde0d91c4faddd05490900cebbafde95

Contents?: true

Size: 1.92 KB

Versions: 5

Compression:

Stored size: 1.92 KB

Contents

import { DirectUpload } from "./direct_upload"
import { dispatchEvent } from "./helpers"

export class DirectUploadController {
  constructor(input, file) {
    this.input = input
    this.file = file
    this.directUpload = new DirectUpload(this.file, this.url, this.directUploadToken, this.attachmentName, this)
    this.dispatch("initialize")
  }

  start(callback) {
    const hiddenInput = document.createElement("input")
    hiddenInput.type = "hidden"
    hiddenInput.name = this.input.name
    this.input.insertAdjacentElement("beforebegin", hiddenInput)

    this.dispatch("start")

    this.directUpload.create((error, attributes) => {
      if (error) {
        hiddenInput.parentNode.removeChild(hiddenInput)
        this.dispatchError(error)
      } else {
        hiddenInput.value = attributes.signed_id
      }

      this.dispatch("end")
      callback(error)
    })
  }

  uploadRequestDidProgress(event) {
    const progress = event.loaded / event.total * 100
    if (progress) {
      this.dispatch("progress", { progress })
    }
  }

  get url() {
    return this.input.getAttribute("data-direct-upload-url")
  }

  get directUploadToken() {
    return this.input.getAttribute("data-direct-upload-token")
  }

  get attachmentName() {
    return this.input.getAttribute("data-direct-upload-attachment-name")
  }

  dispatch(name, detail = {}) {
    detail.file = this.file
    detail.id = this.directUpload.id
    return dispatchEvent(this.input, `direct-upload:${name}`, { detail })
  }

  dispatchError(error) {
    const event = this.dispatch("error", { error })
    if (!event.defaultPrevented) {
      alert(error)
    }
  }

  // DirectUpload delegate

  directUploadWillCreateBlobWithXHR(xhr) {
    this.dispatch("before-blob-request", { xhr })
  }

  directUploadWillStoreFileWithXHR(xhr) {
    this.dispatch("before-storage-request", { xhr })
    xhr.upload.addEventListener("progress", event => this.uploadRequestDidProgress(event))
  }
}

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
activestorage-7.0.1 app/javascript/activestorage/direct_upload_controller.js
activestorage-7.0.0 app/javascript/activestorage/direct_upload_controller.js
activestorage-7.0.0.rc3 app/javascript/activestorage/direct_upload_controller.js
activestorage-7.0.0.rc2 app/javascript/activestorage/direct_upload_controller.js
activestorage-7.0.0.rc1 app/javascript/activestorage/direct_upload_controller.js