Skip to content

Commit

Permalink
Fix: Don't break TOC when OpenAPI description includes headers
Browse files Browse the repository at this point in the history
As noted in [0], the ability to render a CommonMark document through
OpenAPI specifications' `info.description` is breaking due to how the
Table of Contents code works.

We'd assumed that the `id` would always be set on headers - by Middleman
- but as it's possible for an OpenAPI description to include headers, we
won't always have one.

Until the `openapi3_parser` gem supports making this configurable, which
is unlikely, due to the way that CommonMark doesn't have this as a
default extension, we can instead utilise our `TechDocsHTMLRenderer` to
render the headings with IDs, as expected.

To do this, we can create a new helper in `ApiReferenceRenderer` which
will render the Markdown document as our custom Markdown, which requires
we construct the `TechDocsHTMLRenderer` class, which needs the Middleman
`ConfigContext` class injected in.

This means that we won't be using CommonMark, as per the OpenAPI spec,
and this is something we'll look to address in alphagov#282.

[0]: alphagov/tdt-documentation#156
  • Loading branch information
jamietanna committed Nov 12, 2021
1 parent ee6b8aa commit 5b738ab
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/govuk_tech_docs/api_reference/api_reference_renderer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Renderer
def initialize(app, document)
@app = app
@document = document
@redcarpet = build_redcarpet(app)

# Load template files
@template_api_full = get_renderer("api_reference_full.html.erb")
Expand Down Expand Up @@ -137,6 +138,11 @@ def schema_properties(schema_data)

private

def build_redcarpet(app)
renderer = GovukTechDocs::TechDocsHTMLRenderer.new(context: app.config_context)
Redcarpet::Markdown.new(renderer)
end

def get_renderer(file)
template_path = File.join(File.dirname(__FILE__), "templates/" + file)
template = File.open(template_path, "r").read
Expand All @@ -159,6 +165,10 @@ def get_schema_link(schema)
id = "schema-#{schema.name.parameterize}"
"<a href='\##{id}'>#{schema.name}</a>"
end

def render_markdown(text)
@redcarpet.render(text)
end
end
end
end
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<h1 id="<%= info.title.parameterize %>"><%= info.title %> v<%= info.version %></h1>
<%= info.description_html %>
<%= render_markdown(info.description) %>

<%# OpenAPI files default to having a single server of URL "/" %>
<% if servers.length > 1 || servers[0].url != "/" %>
Expand Down

0 comments on commit 5b738ab

Please sign in to comment.