aboutsummaryrefslogtreecommitdiffstats
path: root/app/javascript/activetext/index.js
blob: 03cb9960cbc1e71fe2980e0346ea66353b4a5fef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import * as Trix from "trix"
import { DirectUpload } from "activestorage"

// FIXME: Hard coded routes
const directUploadsURL = "/rails/active_storage/direct_uploads"
const blobsURL = "/rails/active_storage/blobs"

addEventListener("trix-attachment-add", event => {
  const { attachment } = event
  if (!attachment.file) return

  const delegate = {
    directUploadWillStoreFileWithXHR: (xhr) => {
      xhr.upload.addEventListener("progress", event => {
        const progress = event.loaded / event.total * 100
        attachment.setUploadProgress(progress)
      })
    }
  }

  const directUpload = new DirectUpload(attachment.file, directUploadsURL, delegate)

  directUpload.create((error, attributes) => {
    if (error) {
      console.warn("Failed to store file for attachment", attachment, error)
    } else {
      console.log("Created blob for attachment", attributes, attachment)
      const { signed_id } = attributes
      const url = `${blobsURL}/${signed_id}/${encodeURIComponent(attachment.file.name)}`
      attachment.setAttributes({ url, signed_id })
    }
  })
})