diff --git a/lib/sdoc/helpers.rb b/lib/sdoc/helpers.rb index f3cdaa28..eda3dac5 100644 --- a/lib/sdoc/helpers.rb +++ b/lib/sdoc/helpers.rb @@ -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 @@ -79,7 +82,7 @@ def og_modified_time def page_description(leading_html, max_length: 160) return if leading_html.nil? || !leading_html.include?("
") - 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 diff --git a/lib/sdoc/search_index.rb b/lib/sdoc/search_index.rb index 60761776..0ca0f193 100644 --- a/lib/sdoc/search_index.rb +++ b/lib/sdoc/search_index.rb @@ -1,5 +1,6 @@ require "base64" require "nokogiri" +require_relative "helpers" module SDoc::SearchIndex extend self @@ -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 elements as a whole when truncating
diff --git a/spec/helpers_spec.rb b/spec/helpers_spec.rb
index 207cdeb4..1fb00de7 100644
--- a/spec/helpers_spec.rb
+++ b/spec/helpers_spec.rb
@@ -412,6 +412,11 @@ module Foo; module Bar; module Qux; end; end; end
headline
paragraph
HTML
+
+ _(@helpers.page_description(<<~HTML)).must_equal "paragraph"
+ 1
2
3
4
5
6
+ paragraph
+ HTML
end
it "returns nil when there is no leading paragraph" do
@@ -420,6 +425,11 @@ module Foo; module Bar; module Qux; end; end; end
other
HTML
+ _(@helpers.page_description(<<~HTML)).must_be_nil
+ item
+ other
+ HTML
+
_(@helpers.page_description("")).must_be_nil
_(@helpers.page_description(nil)).must_be_nil
end