Project

General

Profile

Defect #40650 » 0002-Fix-alt-and-title-attributes-for-attached-images-in-Wiki.patch

Katsuya HIDAKA, 2024-05-01 19:46

View differences:

app/helpers/application_helper.rb
944 944
      attachments += obj.attachments if obj.respond_to?(:attachments)
945 945
    end
946 946
    if attachments.present?
947
      text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png|webp))"(\s+alt="([^"]*)")?/i) do |m|
948
        filename, ext, alt, alttext = $1, $2, $3, $4
947
      title_and_alt_re = /\s+(title|alt)="([^"]*)"/i
948

  
949
      text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png|webp))"([^>]*)/i) do |m|
950
        filename, ext, other_attrs = $1, $2, $3
951

  
949 952
        # search for the picture in attachments
950 953
        if found = Attachment.latest_attach(attachments, CGI.unescape(filename))
951 954
          image_url = download_named_attachment_url(found, found.filename, :only_path => only_path)
952 955
          desc = found.description.to_s.delete('"')
953
          if !desc.blank? && alttext.blank?
954
            alt = " title=\"#{desc}\" alt=\"#{desc}\""
955
          end
956
          "src=\"#{image_url}\"#{alt} loading=\"lazy\""
956

  
957
          # remove title and alt attributes after extracting them
958
          title_and_alt = other_attrs.scan(title_and_alt_re).to_h
959
          other_attrs.gsub!(title_and_alt_re, '')
960

  
961
          title_and_alt_attrs = if !desc.blank? && title_and_alt['alt'].blank?
962
                                  " title=\"#{desc}\" alt=\"#{desc}\""
963
                                else
964
                                  # restore original title and alt attributes
965
                                  " #{title_and_alt.map { |k, v| %[#{k}="#{v}"] }.join(' ')}"
966
                                end
967
          "src=\"#{image_url}\"#{title_and_alt_attrs} loading=\"lazy\"#{other_attrs}"
957 968
        else
958 969
          m
959 970
        end
test/helpers/application_helper_test.rb
202 202
    attachments = Attachment.all
203 203
    with_settings text_formatting: 'textile' do
204 204
      # When alt text is set
205
      assert_match %r[<img src=".+?" title="This is a logo" alt="This is a logo" loading=".+?" title="alt text" alt="alt text" />],
205
      assert_match %r[<img src=".+?" title="alt text" alt="alt text" loading=".+?" />],
206 206
        textilizable('!logo.gif(alt text)!', attachments: attachments)
207 207

  
208 208
      # When alt text and style are set
209
      assert_match %r[<img src=".+?" title="This is a logo" alt="This is a logo" loading=".+?" style="width:100px;" title="alt text" alt="alt text" />],
209
      assert_match %r[<img src=".+?" title="alt text" alt="alt text" loading=".+?" style="width:100px;" />],
210 210
        textilizable('!{width:100px}logo.gif(alt text)!', attachments: attachments)
211 211

  
212 212
      # When alt text is not set
(4-4/4)