|
| 1 | +import { Controller } from "@hotwired/stimulus" |
| 2 | +import { DirectUpload } from "@rails/activestorage" |
| 3 | + |
| 4 | +export default class extends Controller { |
| 5 | + static targets = ["input", "progress", "progressBar", "submit", "form"] |
| 6 | + static values = { |
| 7 | + url: String |
| 8 | + } |
| 9 | + |
| 10 | + connect() { |
| 11 | + this.inputTarget.addEventListener("change", this.upload.bind(this)) |
| 12 | + |
| 13 | + // Add form submission handler to disable the file input |
| 14 | + if (this.hasFormTarget) { |
| 15 | + this.formTarget.addEventListener("submit", this.onSubmit.bind(this)) |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + onSubmit(event) { |
| 20 | + if (this.isUploading) { |
| 21 | + // If still uploading, prevent submission |
| 22 | + event.preventDefault() |
| 23 | + console.log("Form submission prevented during upload") |
| 24 | + return |
| 25 | + } |
| 26 | + |
| 27 | + // Disable the file input to prevent it from being submitted with the form |
| 28 | + // This ensures only our hidden inputs with signed IDs are submitted |
| 29 | + this.inputTarget.disabled = true |
| 30 | + |
| 31 | + // Check if we have any signed IDs |
| 32 | + const signedIds = this.element.querySelectorAll('input[name="import[files][]"][type="hidden"]') |
| 33 | + if (signedIds.length === 0) { |
| 34 | + event.preventDefault() |
| 35 | + console.log("No files uploaded yet") |
| 36 | + alert("Please select and upload files first") |
| 37 | + } else { |
| 38 | + console.log(`Submitting form with ${signedIds.length} uploaded files`) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + upload() { |
| 43 | + const files = this.inputTarget.files |
| 44 | + if (files.length === 0) return |
| 45 | + |
| 46 | + console.log(`Uploading ${files.length} files`) |
| 47 | + this.isUploading = true |
| 48 | + |
| 49 | + // Disable submit button during upload |
| 50 | + this.submitTarget.disabled = true |
| 51 | + |
| 52 | + // Always remove any existing progress bar to ensure we create a fresh one |
| 53 | + if (this.hasProgressTarget) { |
| 54 | + this.progressTarget.remove() |
| 55 | + } |
| 56 | + |
| 57 | + // Create a wrapper div for better positioning and visibility |
| 58 | + const progressWrapper = document.createElement("div") |
| 59 | + progressWrapper.className = "mt-4 mb-6 border p-4 rounded-lg bg-gray-50" |
| 60 | + |
| 61 | + // Add a label |
| 62 | + const progressLabel = document.createElement("div") |
| 63 | + progressLabel.className = "font-medium mb-2 text-gray-700" |
| 64 | + progressLabel.textContent = "Upload Progress" |
| 65 | + progressWrapper.appendChild(progressLabel) |
| 66 | + |
| 67 | + // Create a new progress container |
| 68 | + const progressContainer = document.createElement("div") |
| 69 | + progressContainer.setAttribute("data-direct-upload-target", "progress") |
| 70 | + progressContainer.className = "w-full bg-gray-200 rounded-full h-4" |
| 71 | + |
| 72 | + // Create the progress bar fill element |
| 73 | + const progressBarFill = document.createElement("div") |
| 74 | + progressBarFill.setAttribute("data-direct-upload-target", "progressBar") |
| 75 | + progressBarFill.className = "bg-blue-600 h-4 rounded-full transition-all duration-300" |
| 76 | + progressBarFill.style.width = "0%" |
| 77 | + |
| 78 | + // Add the fill element to the container |
| 79 | + progressContainer.appendChild(progressBarFill) |
| 80 | + progressWrapper.appendChild(progressContainer) |
| 81 | + progressBarFill.dataset.percentageDisplay = "true" |
| 82 | + |
| 83 | + // Add the progress wrapper AFTER the file input field but BEFORE the submit button |
| 84 | + this.submitTarget.parentNode.insertBefore(progressWrapper, this.submitTarget) |
| 85 | + |
| 86 | + console.log("Progress bar created and inserted before submit button") |
| 87 | + |
| 88 | + let uploadCount = 0 |
| 89 | + const totalFiles = files.length |
| 90 | + |
| 91 | + // Clear any existing hidden fields for files |
| 92 | + this.element.querySelectorAll('input[name="import[files][]"][type="hidden"]').forEach(el => { |
| 93 | + if (el !== this.inputTarget) { |
| 94 | + el.remove() |
| 95 | + } |
| 96 | + }); |
| 97 | + |
| 98 | + Array.from(files).forEach(file => { |
| 99 | + console.log(`Starting upload for ${file.name}`) |
| 100 | + const upload = new DirectUpload(file, this.urlValue, this) |
| 101 | + upload.create((error, blob) => { |
| 102 | + uploadCount++ |
| 103 | + |
| 104 | + if (error) { |
| 105 | + console.error("Error uploading file:", error) |
| 106 | + } else { |
| 107 | + console.log(`Successfully uploaded ${file.name} with ID: ${blob.signed_id}`) |
| 108 | + |
| 109 | + // Create a hidden field with the correct name |
| 110 | + const hiddenField = document.createElement("input") |
| 111 | + hiddenField.setAttribute("type", "hidden") |
| 112 | + hiddenField.setAttribute("name", "import[files][]") |
| 113 | + hiddenField.setAttribute("value", blob.signed_id) |
| 114 | + this.element.appendChild(hiddenField) |
| 115 | + |
| 116 | + console.log("Added hidden field with signed ID:", blob.signed_id) |
| 117 | + } |
| 118 | + |
| 119 | + // Enable submit button when all uploads are complete |
| 120 | + if (uploadCount === totalFiles) { |
| 121 | + this.submitTarget.disabled = false |
| 122 | + this.isUploading = false |
| 123 | + console.log("All uploads completed") |
| 124 | + console.log(`Ready to submit with ${this.element.querySelectorAll('input[name="import[files][]"][type="hidden"]').length} files`) |
| 125 | + } |
| 126 | + }) |
| 127 | + }) |
| 128 | + } |
| 129 | + |
| 130 | + directUploadWillStoreFileWithXHR(request) { |
| 131 | + request.upload.addEventListener("progress", event => { |
| 132 | + if (!this.hasProgressBarTarget) { |
| 133 | + console.warn("Progress bar target not found") |
| 134 | + return |
| 135 | + } |
| 136 | + |
| 137 | + const progress = (event.loaded / event.total) * 100 |
| 138 | + const progressPercentage = `${progress.toFixed(1)}%` |
| 139 | + console.log(`Upload progress: ${progressPercentage}`) |
| 140 | + this.progressBarTarget.style.width = progressPercentage |
| 141 | + |
| 142 | + // Update text percentage if exists |
| 143 | + const percentageDisplay = this.element.querySelector('[data-percentage-display="true"]') |
| 144 | + if (percentageDisplay) { |
| 145 | + percentageDisplay.textContent = progressPercentage |
| 146 | + } |
| 147 | + }) |
| 148 | + } |
| 149 | +} |
0 commit comments