Trix editor: how to know when attachment upload finished?

Viewed 667

When using ActionText, f.rich_text_area renders a Trix editor. When I add an attachment to the editor, it starts direct-uploading automatically. If I submit the form before the upload is complete, the attachment will be missing in the text, obviously. I know that the event trix-attachment-add is triggered when an attachment is just added, before the upload starts. What event listener can I add in order to know when the upload is finished?

1 Answers

If you are using Stimulus.js, the following controller will disable the submit button until all attachments are done uploading.

Controller:

// form-with-trix-controller.js
export default class extends Controller {
  static targets = ['submit']

  disableSubmitIfTrixAttachmentsUploading(/*event*/) {
    const { hasTrixAttachmentsUploading } = this
    this.submitTargets.forEach(submitTarget => submitTarget.disabled = hasTrixAttachmentsUploading)
  }

  get hasTrixAttachmentsUploading() {
    return this.trixAttachments.some(attachment => attachment.isPending())
  }

  get trixAttachments() {
    return this.trixElements.flatMap(trix => trix.editor.getDocument().getAttachments())
  }

  get trixElements() {
    return Array.from(this.element.querySelectorAll("trix-editor"))
  }
}

In your form that wrapps a Trix controller:

<form data-controller="form-with-trix" data-action="trix-change->form#disableSubmitIfTrixAttachmentsUploading">  
  <input type="submit" name="commit" value="Save File" data-form-target="submit">
</form>

Based on code from Hey.com.

Related