Skip to content

Commit

Permalink
Replace regex with nokogiri to process code blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
richardTowers committed Mar 12, 2021
1 parent 8efa6f9 commit e11be57
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
18 changes: 15 additions & 3 deletions lib/govuk_tech_docs/tech_docs_html_renderer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,25 @@ def block_code(text, lang)
# to include Middleman::Syntax::RedcarpetCodeRenderer. This defines its own
# version of `block_code(text, lang)` which we can call with `super`.

highlighted_html = super
highlighted_html.sub("<pre ", '<pre tabindex="0" ')
fragment = Nokogiri::HTML::DocumentFragment.parse(super)
fragment.traverse do |element|
if element.name == "pre" && element["tabindex"].nil?
element["tabindex"] = "0"
end
end
fragment.to_html
else
# If syntax highlighting with redcarpet isn't enabled, super will not
# be `defined?`, so we can jump straight to rendering HTML ourselves.

"<pre tabindex=\"0\"><code class=\"#{lang}\">#{text}</code></pre>"
fragment = Nokogiri::HTML::DocumentFragment.parse("")
pre = Nokogiri::XML::Node.new "pre", fragment
pre["tabindex"] = "0"
code = Nokogiri::XML::Node.new "code", fragment
code["class"] = lang
code.content = text
pre.add_child code
pre.to_html
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion spec/govuk_tech_docs/tech_docs_html_renderer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def hello_world

describe "#render a code block" do
it "sets tab index to 0" do
expect(output).to include('<pre tabindex="0" class=" ruby">')
expect(output).to include('<pre class=" ruby" tabindex="0">')
end

it "renders the code with syntax highlighting" do
Expand Down

0 comments on commit e11be57

Please sign in to comment.