← All articles
development

Disable Attachments in the Trix Editor

A drop-in Stimulus controller that strips the attachment button, blocks pasted images, and disables file uploads in Rails' Trix editor.

Donn Felker

Donn Felker

2023.07.05 · 1 min read

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.

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading