Skip to content

Commit 6bfe165

Browse files
authored
Merge pull request #355 from block/hampton-fix-numbered-section-links
Restore numbered section links
2 parents 70a96dc + 75e7d4a commit 6bfe165

11 files changed

Lines changed: 199 additions & 18 deletions

File tree

‎engine/app/assets/stylesheets/coplan/document-outline.css‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@
300300
.markdown-rendered h4,
301301
.markdown-rendered h5,
302302
.markdown-rendered h6,
303+
.markdown-rendered [data-heading-alias],
303304
.plan-title {
304305
scroll-margin-top: calc(var(--nav-height) + var(--space-lg));
305306
}

‎engine/app/helpers/coplan/markdown_helper.rb‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ module MarkdownHelper
1717
section
1818
].freeze
1919

20-
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
20+
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
2121

2222
# Commonmarker extensions beyond the gem defaults (tables, tasklist,
2323
# strikethrough, autolink stay on). Footnotes: `[^1]` in text plus a
@@ -142,6 +142,8 @@ def transform_mention_anchors(html)
142142
# so previews require no duplicate citation data or network request.
143143
def transform_reference_anchors(html, numbered_sections: true)
144144
doc = Nokogiri::HTML::DocumentFragment.parse(html)
145+
# Only server-created aliases can redirect a reference to their heading.
146+
doc.css("[data-heading-alias]").remove_attr("data-heading-alias")
145147
used_ids = doc.css("[id]").filter_map { |node| node["id"].presence }.to_set
146148
section_ids = Set.new
147149

@@ -162,9 +164,17 @@ def transform_reference_anchors(html, numbered_sections: true)
162164
section_number = heading.text.squish[/\A(\d+(?:\.\d+)*)\b/, 1]
163165
next unless section_number
164166

165-
heading["id"] ||= unique_dom_id("section-#{section_number.tr('.', '-')}", used_ids)
166-
used_ids << heading["id"]
167-
section_ids << heading["id"]
167+
section_id = "section-#{section_number.tr('.', '-')}"
168+
if heading["id"] != section_id
169+
section_id = unique_dom_id(section_id, used_ids)
170+
if heading["id"].present?
171+
add_heading_alias(heading, section_id)
172+
else
173+
heading["id"] = section_id
174+
end
175+
end
176+
used_ids << section_id
177+
section_ids << section_id << heading["id"]
168178
end
169179
end
170180

@@ -216,6 +226,13 @@ def unique_dom_id(base, used_ids)
216226
"#{base}-#{suffix}"
217227
end
218228

229+
def add_heading_alias(heading, id)
230+
anchor = Nokogiri::XML::Node.new("span", heading.document)
231+
anchor["id"] = id
232+
anchor["data-heading-alias"] = ""
233+
heading.prepend_child(anchor)
234+
end
235+
219236
def enhance_reference_anchor(anchor, type:)
220237
anchor.add_class("reference-anchor")
221238
anchor.add_class("reference-anchor--#{type}")

‎engine/app/helpers/coplan/plans_helper.rb‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,7 @@ def render_plan_document(content)
1010
if heading
1111
if heading["id"].present? && heading["id"] != "plan-title"
1212
# Numbered-section links and previews must survive title decoration.
13-
alias_anchor = Nokogiri::XML::Node.new("span", fragment)
14-
alias_anchor["id"] = heading["id"]
15-
alias_anchor["data-heading-alias"] = ""
16-
heading.prepend_child(alias_anchor)
13+
add_heading_alias(heading, heading["id"])
1714
end
1815
heading["id"] = "plan-title"
1916
heading["class"] = [ heading["class"], "plan-title__heading" ].compact.join(" ")

‎engine/app/helpers/coplan/slideshows_helper.rb‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,7 @@ def align_heading_ids(deck, document)
271271

272272
[
273273
[ "a.anchor", %w[id href], anchor_fingerprint ],
274+
[ "span[data-heading-alias]", %w[id], anchor_fingerprint ],
274275
[ "h1, h2, h3, h4, h5, h6", %w[id], heading_fingerprint ]
275276
].each do |selector, attributes, fingerprint|
276277
document_elements = outside_footnotes(document, selector)
@@ -368,11 +369,9 @@ def drop_misleading_ids(deck, document)
368369
# they mark — so they validate by their parent's content instead of
369370
# their own.
370371
def id_owner_fingerprint(el)
371-
if el.name == "a" && el.classes.include?("anchor")
372-
content_fingerprint(el.parent)
373-
else
374-
content_fingerprint(el)
375-
end
372+
heading_anchor = (el.name == "a" && el.classes.include?("anchor")) ||
373+
(el.name == "span" && el.key?("data-heading-alias"))
374+
content_fingerprint(heading_anchor ? el.parent : el)
376375
end
377376

378377
# Ids still duplicated after alignment (author-written repeats, or

‎engine/app/javascript/controllers/coplan/content_nav_controller.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,11 @@ export default class extends Controller {
352352
revealHashTarget() {
353353
let id
354354
try { id = decodeURIComponent(window.location.hash.slice(1)) } catch { return }
355-
if (id && this._itemsById?.has(id)) this.revealEntry(id, { includeSelf: true })
355+
if (!id) return
356+
357+
const target = document.getElementById(id)
358+
const headingId = target?.hasAttribute("data-heading-alias") ? target.closest("h1, h2, h3, h4, h5, h6")?.id : id
359+
if (this._itemsById?.has(headingId)) this.revealEntry(headingId, { includeSelf: true })
356360
}
357361

358362
toggleLinkedEntry(id) {

‎spec/helpers/markdown_helper_spec.rb‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
describe "#render_markdown" do
55
it "converts markdown to HTML" do
66
html = helper.render_markdown("# Hello\n\n**bold** text")
7-
expect(html).to include("<h1>")
7+
expect(Nokogiri::HTML.fragment(html).at_css("h1").text.strip).to eq("Hello")
88
expect(html).to include("<strong>bold</strong>")
99
expect(html).to include("markdown-rendered")
1010
end
@@ -170,7 +170,30 @@
170170
it "gives numbered headings stable section ids" do
171171
doc = Nokogiri::HTML::DocumentFragment.parse(helper.render_markdown(markdown))
172172

173-
expect(doc.at_css("h3")["id"]).to eq("section-3-1")
173+
heading = doc.at_css("h3")
174+
expect(doc.at_css("#section-3-1")).to satisfy { |target| target == heading || target&.parent == heading }
175+
end
176+
177+
it "keeps heading ids and assigns unique numbered aliases", :heading_slug_ids do
178+
doc = Nokogiri::HTML.fragment(helper.render_markdown(<<~MARKDOWN))
179+
## 3.1 Existing target
180+
181+
### 3.1 Rollout
182+
183+
Read the [number](#section-3-1-2) or the [slug](#31-rollout).
184+
MARKDOWN
185+
186+
expect(doc.at_css('h2[id="31-existing-target"] > #section-3-1[data-heading-alias]')).to be_present
187+
expect(doc.css("#section-3-1-2").size).to eq(1)
188+
expect(doc.at_css('h3[id="31-rollout"] > #section-3-1-2[data-heading-alias]')).to be_present
189+
expect(doc.css("p a.reference-anchor--section").map { |link| link["href"] }).to eq([ "#section-3-1-2", "#31-rollout" ])
190+
end
191+
192+
it "strips the alias marker from author HTML" do
193+
html = '<span id="author-anchor" data-heading-alias></span>'
194+
doc = Nokogiri::HTML.fragment(helper.render_markdown(html))
195+
196+
expect(doc.at_css("#author-anchor")["data-heading-alias"]).to be_nil
174197
end
175198

176199
it "enhances explicit links to numbered sections for previews" do

‎spec/helpers/slideshows_helper_spec.rb‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,22 @@ def deck(content, **options)
373373
expect(doc.css("h1").map { |h| h["id"] }).to eq(%w[section-1 section-1-2])
374374
end
375375

376+
it "aligns numbered aliases across slides while keeping their heading ids", :heading_slug_ids do
377+
doc = deck(<<~MARKDOWN)
378+
See [the second section](#section-4-1-2).
379+
380+
## 4.1. First review
381+
382+
---
383+
384+
## 4.1. Later review
385+
MARKDOWN
386+
387+
expect(doc.at_css('h2[id="41-first-review"] > #section-4-1[data-heading-alias]')).to be_present
388+
expect(doc.at_css('h2[id="41-later-review"] > #section-4-1-2[data-heading-alias]')).to be_present
389+
expect(doc.at_css('a.reference-anchor--section[href="#section-4-1-2"]')).to be_present
390+
end
391+
376392
it "keeps slide heading ids stable when a footnote definition holds a heading" do
377393
# The definition's heading renders only in the References back matter,
378394
# so it must not shift the ids of headings the slides actually show.
@@ -484,6 +500,23 @@ def deck(content, **options)
484500
expect(doc.at_css("#foo-bar").parent.text.squish).to eq("Foo Bar")
485501
end
486502

503+
it "drops a numbered alias from the wrong heading when alignment is skipped", :heading_slug_ids do
504+
# The fallback still has to protect links when the heading sequences cannot be aligned.
505+
allow(helper).to receive(:align_heading_ids)
506+
doc = deck(<<~MARKDOWN)
507+
## 1. Alpha
508+
509+
---
510+
511+
## 1. Beta
512+
513+
## 1. Gamma
514+
MARKDOWN
515+
516+
expect(doc.at_css("#section-1").parent["id"]).to eq("1-alpha")
517+
expect(doc.at_css("#section-1-2")).to be_nil
518+
end
519+
487520
it "does not swap ids between same-text headings whose link destinations differ" do
488521
# data-footnote-ref on an author link must not hide its href from the
489522
# alignment gate — genuine refs keep identical #fn-… hrefs in both

‎spec/requests/plan_content_editing_spec.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@
331331
post preview_plan_path(plan), params: { content: "# Preview\n\n- [ ] task" }, as: :json
332332

333333
expect(response).to have_http_status(:ok)
334-
expect(response.body).to include("Preview</h1>")
334+
expect(Nokogiri::HTML.fragment(response.body).at_css("h1").text.strip).to eq("Preview")
335335
expect(response.body).not_to include("coplan--checkbox#toggle")
336336
end
337337

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
RSpec.shared_context "Commonmarker heading slug IDs" do
2+
before do
3+
# Commonmarker 2.9 moved the slug ID from the self-link to the heading.
4+
# Exercise that output with real Markdown on either parser version.
5+
allow(Commonmarker).to receive(:to_html).and_wrap_original do |render, *args, **options|
6+
html = render.call(*args, **options)
7+
doc = Nokogiri::HTML.fragment(html)
8+
anchors = doc.css("a.anchor[id]").select do |anchor|
9+
anchor.parent.name.match?(/\Ah[1-6]\z/) && !anchor.parent.key?("id")
10+
end
11+
next html if anchors.empty?
12+
13+
anchors.each do |anchor|
14+
anchor.parent["id"] = anchor.remove_attribute("id").value
15+
end
16+
doc.to_html
17+
end
18+
end
19+
end
20+
21+
RSpec.configure do |config|
22+
config.include_context "Commonmarker heading slug IDs", :heading_slug_ids
23+
end

‎spec/system/outline_collapse_spec.rb‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,22 @@ def wait_for_heading_scroll(text)
223223
expect_expanded("3. Architecture", false)
224224
end
225225

226+
it "unfolds a numbered alias target and its parent in the outline", :heading_slug_ids do
227+
replace_content(long_content.sub("### 4.2 Correctness detail 2",
228+
"#### Retry ownership\n\nDetails.\n\n### 4.2 Correctness detail 2"))
229+
visit plan_page_path(plan)
230+
expect_expanded("4. Correctness", false)
231+
expect(page).to have_css('h3[id="41-correctness-detail-1"] [id="section-4-1"][data-heading-alias]', visible: :all)
232+
233+
visit root_path
234+
visit "#{plan_page_path(plan)}#section-4-1"
235+
236+
expect_expanded("4. Correctness", true)
237+
expect_expanded("4.1 Correctness detail 1", true)
238+
expect_entry_visible("Retry ownership", true)
239+
expect_expanded("3. Architecture", false)
240+
end
241+
226242
it "remembers the reader's toggles across reloads and Turbo navigation, ignoring stale keys" do
227243
visit plan_page_path(plan)
228244
chevron("3. Architecture").click

0 commit comments

Comments
 (0)