Donn Felker

Not A Subscriber?

Join thousands of people who build and refuse to get left behind. One message a week on building, using AI as an accelerator, and staying sharp in the new AI frontier.

Receive one free message a week

July 5, 2023 Donn Felker

Disable Attachments in the Trix Editor

Use this stimulus controller to quickly disable attachments in the Trix Editor.

When you need to disable attachments in the Trix editor you’ll need to make sure you do three things:

  1. Remove the file attachment button from the Trix editor
  2. Disable copy/paste of attachments
  3. Disable all attachments

You can do this with the following stimulus controller:

Save this as disable_uploads_controller.rb

import {Controller} from "@hotwired/stimulus"
export default class extends Controller {
connect() {
// Disable trix uploads: https://github.com/basecamp/trix/issues/604#issuecomment-600974875
// Get rid of the upload button
document.addEventListener("trix-initialize", function(e) {
const fileTools = document.querySelector(".trix-button-group--file-tools");
// null check hack: trix-initialize gets called twice for some reason, sometimes it is null :shrug:
fileTools?.remove();
});
// Dont allow images/etc to be pasted
document.addEventListener("trix-attachment-add", function(event) {
if (!event.attachment.file) {
event.attachment.remove()
}
})
// No files, ever
document.addEventListener("trix-file-accept", function(event) {
event.preventDefault();
});
}
}

Once included in your /app/javascript/controllers/ folder, you would apply it like this in a Rails form:

<div data-controller="disable-uploads">
<%= form.label :body %>
<%= form.rich_text_area :body %>
</div>

That’s it.

Bonus

What if you only wanted to allow images of type png, jpeg and gif in your Trix editor? You can do that with another stimulus controller as well:

Save this as images_only_controller.rb

import {Controller} from "@hotwired/stimulus"
export default class extends Controller {
connect() {
document.addEventListener("trix-file-accept", function(event) {
const acceptedTypes = ['image/jpeg', 'image/png', 'image/gif']
if (!acceptedTypes.includes(event.file.type)) {
event.preventDefault()
alert("We only support jpeg, png or gif files")
}
})
}
}

Apply it like this:

<div data-controller="images-only">
<%= form.label :body %>
<%= form.rich_text_area :body %>
</div>

Now, file attachments will be possible, but only if the file type is jpeg, png, or gif. Adjust as you deem necessary.