From bc05bf7313fa34e0a1927b51717e86de0df2717d Mon Sep 17 00:00:00 2001 From: Kota Shiratsuka Date: Sun, 24 Nov 2024 14:42:46 +0900 Subject: [PATCH 1/2] Add width and height when img src --- app/helpers/application_helper.rb | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index ff6e9b7d4..91a43c9f3 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -990,10 +990,14 @@ module ApplicationHelper end if attachments.present? title_and_alt_re = /\s+(title|alt)="([^"]*)"/i + style_attr_re = /\s+style="([^"]*)"/i text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png|webp))"([^>]*)/i) do |m| filename, ext, other_attrs = $1, $2, $3 + # Check if style attribute exists + has_style = other_attrs =~ style_attr_re + # search for the picture in attachments if found = Attachment.latest_attach(attachments, CGI.unescape(filename)) image_url = download_named_attachment_url(found, found.filename, :only_path => only_path) @@ -1003,13 +1007,28 @@ module ApplicationHelper title_and_alt = other_attrs.scan(title_and_alt_re).to_h other_attrs.gsub!(title_and_alt_re, '') + # Process dimensions and scaling + width, height = nil, nil + image = MiniMagick::Image.open(found.diskfile) + width, height = image.width, image.height + + # Adjust dimensions for @2x, @3x, etc. + if filename =~ /@(\d+)x\./ + scale_factor = $1.to_i + width /= scale_factor + height /= scale_factor + end + + # Add width and height to the img tag only if style attribute is absent + dimension_attrs = (!has_style && width && height) ? " width=\"#{width}\" height=\"#{height}\"" : "" + title_and_alt_attrs = if !desc.blank? && title_and_alt['alt'].blank? " title=\"#{desc}\" alt=\"#{desc}\"" else # restore original title and alt attributes " #{title_and_alt.map { |k, v| %[#{k}="#{v}"] }.join(' ')}" end - "src=\"#{image_url}\"#{title_and_alt_attrs} loading=\"lazy\"#{other_attrs}" + "src=\"#{image_url}\"#{title_and_alt_attrs}#{dimension_attrs} loading=\"lazy\"#{other_attrs}" else m end -- 2.47.1