Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract page description after any leading headings #303

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
5 changes: 4 additions & 1 deletion lib/sdoc/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ module SDoc::Helpers
require_relative "helpers/git"
include SDoc::Helpers::Git

LEADING_PARAGRAPH_XPATH =
"./*[not(self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6)][1][self::p]"

def link_to(text, url = nil, html_attributes = {})
url, html_attributes = nil, url if url.is_a?(Hash)
url ||= text
Expand Down Expand Up @@ -79,7 +82,7 @@ def og_modified_time
def page_description(leading_html, max_length: 160)
return if leading_html.nil? || !leading_html.include?("</p>")

text = Nokogiri::HTML.fragment(leading_html).at_css("h1 + p, p:first-child")&.inner_text
text = Nokogiri::HTML.fragment(leading_html).at(LEADING_PARAGRAPH_XPATH)&.inner_text
return unless text

if text.length > max_length
Expand Down
3 changes: 2 additions & 1 deletion lib/sdoc/search_index.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require "base64"
require "nokogiri"
require_relative "helpers"

module SDoc::SearchIndex
extend self
Expand Down Expand Up @@ -120,7 +121,7 @@ def signature_for(rdoc_method)

def truncate_description(description, limit)
return if description.empty?
leading_paragraph = Nokogiri::HTML.fragment(description).at_css("h1 + p, p:first-child")
leading_paragraph = Nokogiri::HTML.fragment(description).at(SDoc::Helpers::LEADING_PARAGRAPH_XPATH)
return unless leading_paragraph

# Treat <code> elements as a whole when truncating
Expand Down
10 changes: 10 additions & 0 deletions spec/helpers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,11 @@ module Foo; module Bar; module Qux; end; end; end
<h1>headline</h1>
<p>paragraph</p>
HTML

_(@helpers.page_description(<<~HTML)).must_equal "paragraph"
<h1>1</h1><h2>2</h2><h3>3</h3><h4>4</h4><h5>5</h5><h6>6</h6>
<p>paragraph</p>
HTML
end

it "returns nil when there is no leading paragraph" do
Expand All @@ -420,6 +425,11 @@ module Foo; module Bar; module Qux; end; end; end
<p>other</p>
HTML

_(@helpers.page_description(<<~HTML)).must_be_nil
<ul><li><p>item</p></li></ul>
<p>other</p>
HTML

_(@helpers.page_description("")).must_be_nil
_(@helpers.page_description(nil)).must_be_nil
end
Expand Down