I would like to add a button to Trix editor that would insert YouTube video using custom HTML attribute. It seems to me that default link
button is exactly what I need. I would need to just modify little bit what is done once someone click the link button after text is entered.
The standard link button
- has Trix menu button
- has input field
- has input value validation
- link and unlink functionality. I might want to remove the
unlink
button - inserts text into editor
- inserted text / area is not editable
I was searching the net but did not find any example how to achieve what I want. The closest solution is https://www.kindleman.com.au/blog/advanced-actiontext-modifications-for-cms-use/ the embed, image, and link buttons are basically what I want. But it is coded in RoR. I know nothing about RoR.
Could someone help me to create my link (embed) button in Trix?
I know how to add a button. But I do not know how to open modal upon clicking the button. I know how to insert text.
var buttonHTML = '<button type="button" data-trix-attribute="red">RED</button>'
event.target.toolbarElement.
querySelector(".trix-button-group").
insertAdjacentHTML("beforeend", buttonHTML)
2
Answers
You’ve already figured out how to add a button, but you’re unsure about opening a modal and handling the insertion. Here’s a rough outline to get you started. Hopefully, you can figure out the rest 🙂
First, add your custom button:
Now, handle the button click to open a modal.Here’s a simple example using plain HTML:
This is the basic idea. The modal part is simple and ugly, but should be enough to get you started.
adding a button to the toolbar: There are two important
attributes that need to match the dialog:
data-trix-attribute="embed_URL"
anddata-trix-action="embed"
.[source file]
Adding embed dialog similar to the link dialog: I matched
the
data-trix-dialog="embed"
anddata-trix-dialog-attribute="embed_URL"
attribute values with thebutton.
URL validation: I’ve added
data-trix-method="setAttribute"
to theAdd
button to validate URL and close dialog by callingSetAttribute
from toolbar_controller.js ( to find out how it works check StimulusJS syntax )For more details, see the comments in the code.