Skip to content

Commit

Permalink
Merge pull request rails#50988 from p8/guides/improve-dom-id-uniqueness
Browse files Browse the repository at this point in the history
Improve `dom_id` uniqueness in guides
  • Loading branch information
carlosantoniodasilva authored Feb 8, 2024
2 parents 6bbfbdb + a720480 commit 1007cc8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
2 changes: 1 addition & 1 deletion guides/rails_guides/generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def extract_anchors(html)
anchors = Set.new
html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor|
if anchors.member?(anchor)
puts "*** DUPLICATE ID: #{anchor}, please make sure that there are no headings with the same name at the same level."
puts "*** DUPLICATE ID: '#{anchor}', please make sure that there are no headings with the same name at the same level."
else
anchors << anchor
end
Expand Down
15 changes: 11 additions & 4 deletions guides/rails_guides/markdown.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,15 @@ def render(body)
def dom_id(nodes)
dom_id = dom_id_text(nodes.last.text)

# Fix duplicate node by prefix with its parent node
# Fix duplicate dom_ids by prefixing the parent node dom_id
if @node_ids[dom_id]
if @node_ids[dom_id].size > 1
duplicate_nodes = @node_ids.delete(dom_id)
new_node_id = "#{duplicate_nodes[-2][:id]}-#{duplicate_nodes.last[:id]}"
new_node_id = dom_id_with_parent_node(dom_id, duplicate_nodes[-2])
duplicate_nodes.last[:id] = new_node_id
@node_ids[new_node_id] = duplicate_nodes
end

dom_id = "#{nodes[-2][:id]}-#{dom_id}"
dom_id = dom_id_with_parent_node(dom_id, nodes[-2])
end

@node_ids[dom_id] = nodes
Expand All @@ -60,6 +59,14 @@ def dom_id_text(text)
.gsub(/\s+/, "-")
end

def dom_id_with_parent_node(dom_id, parent_node)
if parent_node
[parent_node[:id], dom_id].join("-")
else
dom_id
end
end

def engine
renderer = @epub ? EpubRenderer : Renderer
@engine ||= Redcarpet::Markdown.new(renderer,
Expand Down

0 comments on commit 1007cc8

Please sign in to comment.