From a720480a0acae0cf2ded207f802a6e376bf2bc46 Mon Sep 17 00:00:00 2001 From: Petrik Date: Tue, 6 Feb 2024 20:45:44 +0100 Subject: [PATCH] Improve `dom_id` uniqueness in guides All headers in a guide get a unique `dom_id` to make anchor links work. If a header is already present we would prefix it with the `dom_id` of the parent node. This would not work for headers without parent nodes. This commit simplifies the `dom_id` uniqueness by only prepending the parent node if it exists. This can still result in duplicates at the same level, but for these we already show a warning: *** DUPLICATE ID: 'some_id', please make sure that there are no headings with the same name at the same level. Co-authored-by: Carlos Antonio da Silva --- guides/rails_guides/generator.rb | 2 +- guides/rails_guides/markdown.rb | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb index 5f2a9386d3..a32ace583f 100644 --- a/guides/rails_guides/generator.rb +++ b/guides/rails_guides/generator.rb @@ -177,7 +177,7 @@ def extract_anchors(html) anchors = Set.new html.scan(/ 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 @@ -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,