ruby-on-railsactiontext

Add Buttons to Rails ActionText toolbar


What is the best way to configure ActionText to add buttons to the toolbar. For example, an h2 and h3 button?


Solution

  • To add to Will's answer, you can avoid recreating the whole toolbar by using trix after initialize callback :

    example, adding a 'Red' button that turns the text red :

    var Trix = require("trix");
    
    /* what the newly created button does */
    Trix.config.textAttributes.red = {
        style: { color: "red" },
        parser: function(element) {
            return element.style.color === "red"
        },
        inheritable: true
    }
    
    /* insert the button visual in the default toolbar */
    addEventListener("trix-initialize", function(event) {
        var buttonHTML = '<button type="button" data-trix-attribute="red">RED</button>'
    
        event.target.toolbarElement.
        querySelector(".trix-button-group").
        insertAdjacentHTML("beforeend", buttonHTML)
    })
    
    

    output:

    enter image description here