trix icon indicating copy to clipboard operation
trix copied to clipboard

Cannot set HTML class attribute on block element

Open spyderman4g63 opened this issue 1 year ago • 11 comments

It looks like support for html class attributes should work on block elements here by passing a className option.

  if (options.className) {
    options.className.split(" ").forEach((className) => {
      element.classList.add(className)
    })
  }

However I cannot get the editor to add a class to the element:

Trix.config.blockAttributes.h2 = {
    tagName: 'h2',
    className: 'test1'
}

addEventListener("trix-initialize", function(event) {  
  var buttonHTML = '<button type="button" data-trix-attribute="h2">H2</button>'
  event.target.toolbarElement
      .querySelector(".button_group.text_tools")
      .insertAdjacentHTML("beforeend", buttonHTML)
})
Steps to Reproduce
  1. Go to JS fiddle: https://jsfiddle.net/mzsjpn8e/8/
  2. enter text into the editor
  3. highlight the text
  4. click the h2 button
  5. inspect the source code to see that the h2 element was create but that there is no class attribute
<trix-editor input="x" contenteditable="" trix-id="1" toolbar="trix-toolbar-1">
    <h2><!--block-->test</h2>
</trix-editor>

I am using actionText in rails. I see that the class attribute should already be allowed:

3.1.3 :001 > ActionText::ContentHelper.allowed_attributes
 => 
#<Set:                                                    
 {"href",
  "src",
  "width",
  "height",
  "alt",
  "cite",
  "datetime",
  "title",
  "class",
  "name",
  "xml:lang",
  "abbr",
  "sgid",
  "content-type",
  "url",
  "filename",
  "filesize",
  "previewable",
  "presentation",
  "caption"}> 

spyderman4g63 avatar Dec 09 '22 16:12 spyderman4g63