diff --git a/engine/app/assets/stylesheets/coplan/document-outline.css b/engine/app/assets/stylesheets/coplan/document-outline.css index 9b0747d3..d0bd053a 100644 --- a/engine/app/assets/stylesheets/coplan/document-outline.css +++ b/engine/app/assets/stylesheets/coplan/document-outline.css @@ -300,6 +300,7 @@ .markdown-rendered h4, .markdown-rendered h5, .markdown-rendered h6, +.markdown-rendered [data-heading-alias], .plan-title { scroll-margin-top: calc(var(--nav-height) + var(--space-lg)); } diff --git a/engine/app/helpers/coplan/markdown_helper.rb b/engine/app/helpers/coplan/markdown_helper.rb index 68b3e822..9400ae54 100644 --- a/engine/app/helpers/coplan/markdown_helper.rb +++ b/engine/app/helpers/coplan/markdown_helper.rb @@ -17,7 +17,7 @@ module MarkdownHelper section ].freeze - ALLOWED_ATTRIBUTES = %w[id class lang href src alt title width target rel type start checked disabled open aria-label aria-haspopup aria-expanded data-line data-line-text data-action data-mention-username data-sourcepos data-reference-type data-footnotes data-footnote-ref data-footnote-backref data-footnote-backref-idx data-math-style].freeze + ALLOWED_ATTRIBUTES = %w[id class lang href src alt title width target rel type start checked disabled open aria-label aria-haspopup aria-expanded data-line data-line-text data-action data-mention-username data-sourcepos data-reference-type data-heading-alias data-footnotes data-footnote-ref data-footnote-backref data-footnote-backref-idx data-math-style].freeze # Commonmarker extensions beyond the gem defaults (tables, tasklist, # strikethrough, autolink stay on). Footnotes: `[^1]` in text plus a @@ -130,6 +130,8 @@ def transform_mention_anchors(html) # so previews require no duplicate citation data or network request. def transform_reference_anchors(html, numbered_sections: true) doc = Nokogiri::HTML::DocumentFragment.parse(html) + # Only server-created aliases can redirect a reference to their heading. + doc.css("[data-heading-alias]").remove_attr("data-heading-alias") used_ids = doc.css("[id]").filter_map { |node| node["id"].presence }.to_set section_ids = Set.new @@ -150,9 +152,17 @@ def transform_reference_anchors(html, numbered_sections: true) section_number = heading.text.squish[/\A(\d+(?:\.\d+)*)\b/, 1] next unless section_number - heading["id"] ||= unique_dom_id("section-#{section_number.tr('.', '-')}", used_ids) - used_ids << heading["id"] - section_ids << heading["id"] + section_id = "section-#{section_number.tr('.', '-')}" + if heading["id"] != section_id + section_id = unique_dom_id(section_id, used_ids) + if heading["id"].present? + add_heading_alias(heading, section_id) + else + heading["id"] = section_id + end + end + used_ids << section_id + section_ids << section_id << heading["id"] end end @@ -204,6 +214,13 @@ def unique_dom_id(base, used_ids) "#{base}-#{suffix}" end + def add_heading_alias(heading, id) + anchor = Nokogiri::XML::Node.new("span", heading.document) + anchor["id"] = id + anchor["data-heading-alias"] = "" + heading.prepend_child(anchor) + end + def enhance_reference_anchor(anchor, type:) anchor.add_class("reference-anchor") anchor.add_class("reference-anchor--#{type}") diff --git a/engine/app/helpers/coplan/plans_helper.rb b/engine/app/helpers/coplan/plans_helper.rb index 2d719466..2bbe8537 100644 --- a/engine/app/helpers/coplan/plans_helper.rb +++ b/engine/app/helpers/coplan/plans_helper.rb @@ -10,10 +10,7 @@ def render_plan_document(content) if heading if heading["id"].present? && heading["id"] != "plan-title" # Numbered-section links and previews must survive title decoration. - alias_anchor = Nokogiri::XML::Node.new("span", fragment) - alias_anchor["id"] = heading["id"] - alias_anchor["data-heading-alias"] = "" - heading.prepend_child(alias_anchor) + add_heading_alias(heading, heading["id"]) end heading["id"] = "plan-title" heading["class"] = [ heading["class"], "plan-title__heading" ].compact.join(" ") diff --git a/engine/app/helpers/coplan/slideshows_helper.rb b/engine/app/helpers/coplan/slideshows_helper.rb index e3c34996..d704f4a3 100644 --- a/engine/app/helpers/coplan/slideshows_helper.rb +++ b/engine/app/helpers/coplan/slideshows_helper.rb @@ -271,6 +271,7 @@ def align_heading_ids(deck, document) [ [ "a.anchor", %w[id href], anchor_fingerprint ], + [ "span[data-heading-alias]", %w[id], anchor_fingerprint ], [ "h1, h2, h3, h4, h5, h6", %w[id], heading_fingerprint ] ].each do |selector, attributes, fingerprint| document_elements = outside_footnotes(document, selector) @@ -368,11 +369,9 @@ def drop_misleading_ids(deck, document) # they mark — so they validate by their parent's content instead of # their own. def id_owner_fingerprint(el) - if el.name == "a" && el.classes.include?("anchor") - content_fingerprint(el.parent) - else - content_fingerprint(el) - end + heading_anchor = (el.name == "a" && el.classes.include?("anchor")) || + (el.name == "span" && el.key?("data-heading-alias")) + content_fingerprint(heading_anchor ? el.parent : el) end # Ids still duplicated after alignment (author-written repeats, or diff --git a/engine/app/javascript/controllers/coplan/content_nav_controller.js b/engine/app/javascript/controllers/coplan/content_nav_controller.js index 35ac1d44..3fc90e40 100644 --- a/engine/app/javascript/controllers/coplan/content_nav_controller.js +++ b/engine/app/javascript/controllers/coplan/content_nav_controller.js @@ -351,7 +351,11 @@ export default class extends Controller { revealHashTarget() { let id try { id = decodeURIComponent(window.location.hash.slice(1)) } catch { return } - if (id && this._itemsById?.has(id)) this.revealEntry(id, { includeSelf: true }) + if (!id) return + + const target = document.getElementById(id) + const headingId = target?.hasAttribute("data-heading-alias") ? target.closest("h1, h2, h3, h4, h5, h6")?.id : id + if (this._itemsById?.has(headingId)) this.revealEntry(headingId, { includeSelf: true }) } toggleLinkedEntry(id) { diff --git a/spec/helpers/markdown_helper_spec.rb b/spec/helpers/markdown_helper_spec.rb index 2eb1a8fb..5c9e6d80 100644 --- a/spec/helpers/markdown_helper_spec.rb +++ b/spec/helpers/markdown_helper_spec.rb @@ -4,7 +4,7 @@ describe "#render_markdown" do it "converts markdown to HTML" do html = helper.render_markdown("# Hello\n\n**bold** text") - expect(html).to include("

") + expect(Nokogiri::HTML.fragment(html).at_css("h1").text.strip).to eq("Hello") expect(html).to include("bold") expect(html).to include("markdown-rendered") end @@ -170,7 +170,30 @@ it "gives numbered headings stable section ids" do doc = Nokogiri::HTML::DocumentFragment.parse(helper.render_markdown(markdown)) - expect(doc.at_css("h3")["id"]).to eq("section-3-1") + heading = doc.at_css("h3") + expect(doc.at_css("#section-3-1")).to satisfy { |target| target == heading || target&.parent == heading } + end + + it "keeps heading ids and assigns unique numbered aliases", :heading_slug_ids do + doc = Nokogiri::HTML.fragment(helper.render_markdown(<<~MARKDOWN)) + ## 3.1 Existing target + + ### 3.1 Rollout + + Read the [number](#section-3-1-2) or the [slug](#31-rollout). + MARKDOWN + + expect(doc.at_css('h2[id="31-existing-target"] > #section-3-1[data-heading-alias]')).to be_present + expect(doc.css("#section-3-1-2").size).to eq(1) + expect(doc.at_css('h3[id="31-rollout"] > #section-3-1-2[data-heading-alias]')).to be_present + expect(doc.css("p a.reference-anchor--section").map { |link| link["href"] }).to eq([ "#section-3-1-2", "#31-rollout" ]) + end + + it "strips the alias marker from author HTML" do + html = '' + doc = Nokogiri::HTML.fragment(helper.render_markdown(html)) + + expect(doc.at_css("#author-anchor")["data-heading-alias"]).to be_nil end it "enhances explicit links to numbered sections for previews" do diff --git a/spec/helpers/slideshows_helper_spec.rb b/spec/helpers/slideshows_helper_spec.rb index 18e47917..67e732a5 100644 --- a/spec/helpers/slideshows_helper_spec.rb +++ b/spec/helpers/slideshows_helper_spec.rb @@ -373,6 +373,22 @@ def deck(content, **options) expect(doc.css("h1").map { |h| h["id"] }).to eq(%w[section-1 section-1-2]) end + it "aligns numbered aliases across slides while keeping their heading ids", :heading_slug_ids do + doc = deck(<<~MARKDOWN) + See [the second section](#section-4-1-2). + + ## 4.1. First review + + --- + + ## 4.1. Later review + MARKDOWN + + expect(doc.at_css('h2[id="41-first-review"] > #section-4-1[data-heading-alias]')).to be_present + expect(doc.at_css('h2[id="41-later-review"] > #section-4-1-2[data-heading-alias]')).to be_present + expect(doc.at_css('a.reference-anchor--section[href="#section-4-1-2"]')).to be_present + end + it "keeps slide heading ids stable when a footnote definition holds a heading" do # The definition's heading renders only in the References back matter, # so it must not shift the ids of headings the slides actually show. @@ -484,6 +500,23 @@ def deck(content, **options) expect(doc.at_css("#foo-bar").parent.text.squish).to eq("Foo Bar") end + it "drops a numbered alias from the wrong heading when alignment is skipped", :heading_slug_ids do + # The fallback still has to protect links when the heading sequences cannot be aligned. + allow(helper).to receive(:align_heading_ids) + doc = deck(<<~MARKDOWN) + ## 1. Alpha + + --- + + ## 1. Beta + + ## 1. Gamma + MARKDOWN + + expect(doc.at_css("#section-1").parent["id"]).to eq("1-alpha") + expect(doc.at_css("#section-1-2")).to be_nil + end + it "does not swap ids between same-text headings whose link destinations differ" do # data-footnote-ref on an author link must not hide its href from the # alignment gate — genuine refs keep identical #fn-… hrefs in both diff --git a/spec/requests/plan_content_editing_spec.rb b/spec/requests/plan_content_editing_spec.rb index 778f5b50..9f992c60 100644 --- a/spec/requests/plan_content_editing_spec.rb +++ b/spec/requests/plan_content_editing_spec.rb @@ -331,7 +331,7 @@ post preview_plan_path(plan), params: { content: "# Preview\n\n- [ ] task" }, as: :json expect(response).to have_http_status(:ok) - expect(response.body).to include("Preview

") + expect(Nokogiri::HTML.fragment(response.body).at_css("h1").text.strip).to eq("Preview") expect(response.body).not_to include("coplan--checkbox#toggle") end diff --git a/spec/support/commonmarker_heading_ids.rb b/spec/support/commonmarker_heading_ids.rb new file mode 100644 index 00000000..dd23f4cf --- /dev/null +++ b/spec/support/commonmarker_heading_ids.rb @@ -0,0 +1,23 @@ +RSpec.shared_context "Commonmarker heading slug IDs" do + before do + # Commonmarker 2.9 moved the slug ID from the self-link to the heading. + # Exercise that output with real Markdown on either parser version. + allow(Commonmarker).to receive(:to_html).and_wrap_original do |render, *args, **options| + html = render.call(*args, **options) + doc = Nokogiri::HTML.fragment(html) + anchors = doc.css("a.anchor[id]").select do |anchor| + anchor.parent.name.match?(/\Ah[1-6]\z/) && !anchor.parent.key?("id") + end + next html if anchors.empty? + + anchors.each do |anchor| + anchor.parent["id"] = anchor.remove_attribute("id").value + end + doc.to_html + end + end +end + +RSpec.configure do |config| + config.include_context "Commonmarker heading slug IDs", :heading_slug_ids +end diff --git a/spec/system/outline_collapse_spec.rb b/spec/system/outline_collapse_spec.rb index 896a1297..ca16fcec 100644 --- a/spec/system/outline_collapse_spec.rb +++ b/spec/system/outline_collapse_spec.rb @@ -223,6 +223,22 @@ def wait_for_heading_scroll(text) expect_expanded("3. Architecture", false) end + it "unfolds a numbered alias target and its parent in the outline", :heading_slug_ids do + replace_content(long_content.sub("### 4.2 Correctness detail 2", + "#### Retry ownership\n\nDetails.\n\n### 4.2 Correctness detail 2")) + visit plan_page_path(plan) + expect_expanded("4. Correctness", false) + expect(page).to have_css('h3[id="41-correctness-detail-1"] [id="section-4-1"][data-heading-alias]', visible: :all) + + visit root_path + visit "#{plan_page_path(plan)}#section-4-1" + + expect_expanded("4. Correctness", true) + expect_expanded("4.1 Correctness detail 1", true) + expect_entry_visible("Retry ownership", true) + expect_expanded("3. Architecture", false) + end + it "remembers the reader's toggles across reloads and Turbo navigation, ignoring stale keys" do visit plan_page_path(plan) chevron("3. Architecture").click diff --git a/spec/system/references_spec.rb b/spec/system/references_spec.rb index 2aba64e5..48ff9268 100644 --- a/spec/system/references_spec.rb +++ b/spec/system/references_spec.rb @@ -34,6 +34,74 @@ expect(page).to have_current_path(/#section-1\z/, url: true) end + it "previews and follows numbered and slug links to the same heading", :heading_slug_ids do + padding = ("A paragraph to make the jump visible.\n\n" * 25).strip + document = Coplan::Plans::Create.call(user: user, actor_type: "human", content: <<~MARKDOWN) + # Section link check + + See the [numbered section](#section-4-1) or the [heading slug](#41-findings). + + #{padding} + + ### 4.1. Findings + + This is the findings preview. + + #{padding} + MARKDOWN + document_path = plan_page_path(document) + + { "numbered section" => "section-4-1", "heading slug" => "41-findings" }.each do |label, fragment| + visit document_path + link = find_link(label, href: "##{fragment}") + link.hover + expect(page).to have_css(".reference-preview__title", text: "4.1. Findings", visible: true) + expect(page).to have_css(".reference-preview__body", text: "This is the findings preview.", visible: true) + link.click + expect(page).to have_current_path(/##{fragment}\z/, url: true) + expect(page).to have_css('h3[id="41-findings"]', obscured: false) + end + + visit root_path + visit "#{document_path}#section-4-1" + expect(page).to have_css('h3[id="41-findings"]', obscured: false) + expect(page.evaluate_script(<<~JS)).to be(true) + document.getElementById("41-findings").getBoundingClientRect().top >= + document.querySelector(".site-nav").getBoundingClientRect().bottom + JS + end + + it "previews a numbered alias on another slide and opens that slide", :heading_slug_ids do + document = Coplan::Plans::Create.call(user: user, actor_type: "human", content: <<~MARKDOWN) + # Deck section links + + See [the second review](#section-4-1-2). + + ::: {.presentation} + + ## 4.1. First review + + First slide details. + + --- + + ## 4.1. Later review + + Second slide details. + + ::: + MARKDOWN + visit plan_page_path(document) + + link = find_link("the second review", href: "#section-4-1-2") + link.hover + expect(page).to have_css(".reference-preview__title", text: "4.1. Later review", visible: true) + expect(page).to have_css(".reference-preview__body", text: "Second slide details.", visible: true) + link.click + expect(page).to have_current_path(/#section-4-1-2\z/, url: true) + expect(page).to have_css('.deck-slide--current h2[id="41-later-review"]', visible: true) + end + # References live under the document as a footnote section — same page as # the content, no tabs. def open_add_reference_modal @@ -145,7 +213,7 @@ def press_at_start_of(element) # The suppression is specific to the drag — an ordinary hover still # previews. Moving off the anchor first is load bearing: the pointer is # still inside it, and staying inside fires no second mouseenter. - find("#section-2-1").hover + find("h2", text: "2.1 Rollout").hover section_link.hover expect(page).to have_css(".reference-preview__title", text: "2.1 Rollout", visible: :visible) end