Only sanitize content attribute when present in attachments

When the `content` attribute is set for Action Text attachments, Trix
shows this content.

1ac6d40d36a07b48a67bc7f8627fd1f92bffcb14 introduced sanitizing the
`content` attribute of ActionText::Attachable::ContentAttachment.
However, it would also set the `content` attribute when it isn't
present. Instead of showing the image preview, Trix would use the
empty `content` attribute resulting in missing previews for images.
This commit is contained in:
Petrik 2024-06-11 22:14:39 +02:00
parent e3ea4c7412
commit 52c21f9066
3 changed files with 18 additions and 1 deletions

@ -1,2 +1,5 @@
* Only sanitize `content` attribute when present in attachments.
*Petrik de Heus*
Please check [7-2-stable](https://github.com/rails/rails/blob/7-2-stable/actiontext/CHANGELOG.md) for previous changes.

@ -97,7 +97,9 @@ def append_attachables(attachables)
def render_attachments(**options, &block)
content = fragment.replace(ActionText::Attachment.tag_name) do |node|
if node.key? "content"
node["content"] = sanitize_content_attachment(node["content"])
end
block.call(attachment_for_node(node, **options))
end
self.class.new(content, canonicalize: false)

@ -158,6 +158,18 @@ class ActionText::ContentTest < ActiveSupport::TestCase
ActionText::ContentHelper.allowed_attributes = old_attrs
end
test "sanitizes attachment markup for Trix" do
html = '<action-text-attachment content="<img src=\&quot;.\&quot; onerror=alert>"></action-text-attachment>'
trix_html = '<figure data-trix-attachment="{&quot;content&quot;:&quot;<img src=\\&quot;\\\\%22.\\\\%22\\&quot;>&quot;}"></figure>'
assert_equal trix_html, content_from_html(html).to_trix_html.strip
end
test "does not add missing content attribute" do
html = '<action-text-attachment sgid="123"></action-text-attachment>'
trix_html = '<figure data-trix-attachment="{&quot;sgid&quot;:&quot;123&quot;}"></figure>'
assert_equal trix_html, content_from_html(html).to_trix_html.strip
end
test "renders with layout when in a new thread" do
html = "<h1>Hello world</h1>"
rendered = nil