I extended trix with the ability to insert images using the element.editor.insertHTML "<img src='path-to-image.jpg' />" This works fine, however if i try to add a class or an alt attribute, they get ignored. It seems as if the document parser is removing these attributes, is there anyway to enable it or is this being considered?
Would be nice to have considering the SEO properties of the alt tag, and being able to change the class would enable things such as text being wrapped around the image, or full-width, etc...
element.editor.insertHTML "<img src='path-to-image.jpg', alt='image description', class='wrapped' />"<img src="path-to-image.jpg" data-trix-mutable="true" data-trix-store-key="..." width="..." height="...">I've been digging into the trix source code, and figured out how to extend the insertHTML method with an alt tag. Perhaps something like this could be considered?
trix/models/html_parser.coffee:
allowedAttributes = "style href src width height class alt".split(" ")
...
when "img"
attributes = url: element.getAttribute("src"), contentType: "image", alt: element.getAttribute("alt")
trix/model/attachment.coffee | line 66 | add a getAlt method:
getURL: ->
@attributes.get("url")
getHref: ->
@attributes.get("href")
getAlt: ->
@attributes.get("alt")
trix/views/previewable_attachment_view.coffee | line 10 | add alt attribute to createContentNodes:
createContentNodes: ->
@image = makeElement
tagName: "img"
attributes:
src: ""
alt: ""
data:
trixMutable: true
and in the same file appended the updateAttributesForImage method:
updateAttributesForImage: (image) ->
url = @attachment.getURL()
previewURL = @attachment.getPreviewURL()
image.src = previewURL or url
image.alt = @attachment.getAlt()
now when calling the insertHTML method:
element.editor.insertHTML "<img src='#{ url }' alt='test' />"
the image will have an alt tag
Nice work! I'd be happy to review a PR that adds alt support for image attachments. Let's treat class support as a separate change/idea since it has broader implications and could potentially be applied to all elements.
@javan and @acapro have you given class support any more thought? I think it would be very useful. One use case I鈥檓 considering is being able to add classes to images to align them left or right. Let me know if I can help.
Most helpful comment
@javan and @acapro have you given class support any more thought? I think it would be very useful. One use case I鈥檓 considering is being able to add classes to images to align them left or right. Let me know if I can help.