fix(markdown): don't convert underscore within urls or emails

This commit is contained in:
Colin Darie 2023-04-20 13:10:45 +02:00
parent 8f6681d2a3
commit fb54ca1469
3 changed files with 40 additions and 2 deletions

View file

@ -21,12 +21,22 @@ class SimpleFormatComponent < ApplicationComponent
no_images: true
}
SIMPLE_URL_REGEX = %r{https?://\S+}
EMAIL_IN_TEXT_REGEX = Regexp.new(Devise.email_regexp.source.gsub(/\\A|\\z/, '\b'))
def initialize(text, allow_a: true, class_names_map: {})
@allow_a = allow_a
@text = (text || "").gsub(/\R/, "\n\n") # force double \n otherwise a single one won't split paragraph
.split("\n\n") #
.map(&:lstrip) # this block prevent redcarpet to consider " text" as block code by lstriping
.join("\n\n") #
@allow_a = allow_a
.join("\n\n")
.gsub(EMAIL_IN_TEXT_REGEX) { _1.gsub('_', '\\_') } # Workaround for redcarpet bug on autolink email having _. Cf tests
if !@allow_a
@text = @text.gsub(SIMPLE_URL_REGEX) { _1.gsub('_', '\\_') } # Escape underscores in URLs
end
@renderer = Redcarpet::Markdown.new(
Redcarpet::BareRenderer.new(class_names_map:),
REDCARPET_EXTENSIONS.merge(autolink: @allow_a)

View file

@ -26,6 +26,7 @@ module Redcarpet
when :url
link(link, nil, link)
when :email
# NOTE: As of Redcarpet 3.6.0, autolinking email containing is broken https://github.com/vmg/redcarpet/issues/402
content_tag(:a, link, { href: "mailto:#{link}" })
else
link

View file

@ -90,4 +90,31 @@ TEXT
it { expect(page).not_to have_selector("a") }
end
end
context 'emphasis not in urls' do
let(:text) do
<<~TEXT
A _string emphased_ but https://example.fr/path_preserves_underscore
email: here_is_my@email.com
TEXT
end
context "without autolink" do
let(:allow_a) { false }
it { expect(page).to have_selector("em", count: 1, text: "string emphased") }
it { expect(page).to have_text("https://example.fr/path_preserves_underscore") }
it { expect(page).to have_text("email: here_is_my@email.com") }
end
context "with autolink" do
let(:allow_a) { true }
it {
expect(page).to have_link("https://example.fr/path_preserves_underscore")
# NOTE: As of Redcarpet 3.6.0, autolinking email containing _ is broken https://github.com/vmg/redcarpet/issues/402
# but we still want the email to be displayed
expect(page).to have_text("here_is_my@email.com")
}
end
end
end