Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
25 changes: 21 additions & 4 deletions engine/app/helpers/coplan/markdown_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand Down Expand Up @@ -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}")
Expand Down
5 changes: 1 addition & 4 deletions engine/app/helpers/coplan/plans_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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(" ")
Expand Down
9 changes: 4 additions & 5 deletions engine/app/helpers/coplan/slideshows_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test covers the new step that maps a numbered alias in the URL to its heading in the outline. For example, opening #section-4-1 on a heading whose ID is 41-findings must expand the collapsed outline section that holds that heading. The new browser specs in spec/system/references_spec.rb check only that the heading is visible below the sticky header. They do not look at the outline. If this mapping breaks, the alias is not an outline entry, nothing expands, and every test still passes. Add a case next to "unfolds the target of a section link" in spec/system/outline_collapse_spec.rb that visits a numbered alias fragment on a heading with its own ID. Assert that the outline section that holds it is expanded.

if (this._itemsById?.has(headingId)) this.revealEntry(headingId, { includeSelf: true })
}

toggleLinkedEntry(id) {
Expand Down
27 changes: 25 additions & 2 deletions spec/helpers/markdown_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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("<h1>")
expect(Nokogiri::HTML.fragment(html).at_css("h1").text.strip).to eq("Hello")
expect(html).to include("<strong>bold</strong>")
expect(html).to include("markdown-rendered")
end
Expand Down Expand Up @@ -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 = '<span id="author-anchor" data-heading-alias></span>'
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
Expand Down
33 changes: 33 additions & 0 deletions spec/helpers/slideshows_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels weird... why do we have HTML as 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
Expand Down
2 changes: 1 addition & 1 deletion spec/requests/plan_content_editing_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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</h1>")
expect(Nokogiri::HTML.fragment(response.body).at_css("h1").text.strip).to eq("Preview")
expect(response.body).not_to include("coplan--checkbox#toggle")
end

Expand Down
23 changes: 23 additions & 0 deletions spec/support/commonmarker_heading_ids.rb
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions spec/system/outline_collapse_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
70 changes: 69 additions & 1 deletion spec/system/references_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading