A platform for community discussion. Free, open, simple.
FIX: Remove newlines from img alt & title in HTML to markdown parser (#25473)
Martin Brennan575bc4af73fd
diff --git a/lib/html_to_markdown.rb b/lib/html_to_markdown.rbindex b0415718603..d302f6f2380 100644--- a/lib/html_to_markdown.rb+++ b/lib/html_to_markdown.rb@@ -21,6 +21,10 @@ class HtmlToMarkdownprivate+ def strip_newlines(string)+ string.gsub(/\n/, " ")&.squeeze(" ")+ end+def remove_not_allowed!(doc)allowed = Set.new@@ -167,16 +171,18 @@ class HtmlToMarkdowndef visit_img(node)return if node["src"].blank?+ node["alt"] = strip_newlines(node["alt"]) if node["alt"].present?+ node["title"] = strip_newlines(node["title"]) if node["title"].present?+if @opts[:keep_img_tags]node.to_htmlelsif @opts[:keep_cid_imgs] && node["src"].start_with?("cid:")node.to_htmlelsif node["src"].start_with?(*ALLOWED_IMG_SRCS)- title = node["alt"].presence || node["title"].presencewidth = node["width"].to_iheight = node["height"].to_idimensions = "|#{width}x#{height}" if width > 0 && height > 0- ""+ "![#{node["alt"] || node["title"]}#{dimensions}](#{node["src"]})"endenddiff --git a/spec/lib/html_to_markdown_spec.rb b/spec/lib/html_to_markdown_spec.rbindex c106b00b377..34b2cd30869 100644--- a/spec/lib/html_to_markdown_spec.rb+++ b/spec/lib/html_to_markdown_spec.rb@@ -150,6 +150,14 @@ RSpec.describe HtmlToMarkdown doexpect(html_to_markdown(HTML_WITH_IMG, keep_img_tags: true)).to eq(HTML_WITH_IMG)end+ it "removes newlines from img alt text" do+ html_with_alt_newlines =+ %Q{<img src="https://www.discourse.org/logo.svg" alt="Discourse\n\nLogo">}+ expect(html_to_markdown(html_with_alt_newlines)).to eq(+ "",+ )+ end+it "removes empty & invalid <img>" doexpect(html_to_markdown("<img>")).to eq("")expect(html_to_markdown(%Q{<img src="">})).to eq("")@@ -160,6 +168,13 @@ RSpec.describe HtmlToMarkdown doexpect(html_to_markdown(HTML_WITH_CID_IMG, keep_cid_imgs: true)).to eq(HTML_WITH_CID_IMG)end+ it "removes newlines from img alt text with cid images" do+ html_with_cid_alt_newlines = %Q{<img src="cid:ii_1525434659ddb4cb" title="Discourse\n\nLogo">}+ expect(html_to_markdown(html_with_cid_alt_newlines, keep_cid_imgs: true)).to eq(+ %Q{<img src="cid:ii_1525434659ddb4cb" title="Discourse Logo">},+ )+ end+it "skips hidden <img>" doexpect(html_to_markdown(%Q{<img src="https://www.discourse.org/logo.svg" width=0>})).to eq("")expect(html_to_markdown(%Q{<img src="https://www.discourse.org/logo.svg" height="0">})).to eq(