fix(a11y): add a title in simple renderer links and autolinks

Closes #8095
This commit is contained in:
Colin Darie 2023-03-22 12:48:53 +01:00
parent 0eceed4126
commit 40a303f6a6
4 changed files with 20 additions and 7 deletions

View file

@ -28,15 +28,11 @@ class SimpleFormatComponent < ApplicationComponent
.join("\n\n") #
@allow_a = allow_a
@renderer = Redcarpet::Markdown.new(
Redcarpet::BareRenderer.new(link_attributes: external_link_attributes, class_names_map: class_names_map),
Redcarpet::BareRenderer.new(class_names_map:),
REDCARPET_EXTENSIONS.merge(autolink: @allow_a)
)
end
def external_link_attributes
{ target: '_blank', rel: 'noopener noreferrer' }
end
def tags
if @allow_a
Rails.configuration.action_view.sanitized_allowed_tags + ['a']
@ -46,6 +42,6 @@ class SimpleFormatComponent < ApplicationComponent
end
def attributes
['target', 'rel', 'href', 'class']
['target', 'rel', 'href', 'class', 'title']
end
end

View file

@ -142,7 +142,7 @@ module ApplicationHelper
end
def new_tab_suffix(title)
"#{title}#{I18n.t('utils.new_tab')}"
[title, I18n.t('utils.new_tab')].compact.join(' — ')
end
def download_details(attachment)

View file

@ -1,6 +1,7 @@
module Redcarpet
class BareRenderer < Redcarpet::Render::HTML
include ActionView::Helpers::TagHelper
include ApplicationHelper
# won't use rubocop tag method because it is missing output buffer
# rubocop:disable Rails/ContentTag
@ -16,6 +17,17 @@ module Redcarpet
def paragraph(text)
content_tag(:p, text, { class: @options[:class_names_map].fetch(:paragraph) {} }, false)
end
def link(href, title, content)
content_tag(:a, content, { href:, title: new_tab_suffix(title), **external_link_attributes }, false)
end
def autolink(link, link_type)
return super unless link_type == :url
link(link, nil, link)
end
# rubocop:enable Rails/ContentTag
end
end

View file

@ -64,6 +64,11 @@ TEXT
context 'enabled' do
let(:allow_a) { true }
it { expect(page).to have_selector("a") }
it "inject expected attributes" do
link = page.find_link("https://www.demarches-simplifiees.fr").native
expect(link[:rel]).to eq("noopener noreferrer")
expect(link[:title]).to eq("Nouvel onglet")
end
end
context 'disabled' do