]> git.openstreetmap.org Git - rails.git/commitdiff
Use first paragraph as richtext description
authorAnton Khorev <tony29@yandex.ru>
Wed, 7 Aug 2024 03:06:10 +0000 (06:06 +0300)
committerAnton Khorev <tony29@yandex.ru>
Wed, 7 Aug 2024 05:01:48 +0000 (08:01 +0300)
lib/rich_text.rb
test/lib/rich_text_test.rb

index f554e5ab59d665a6b48332dab22b8e12d2ae115e..b720f33e700cfe75536dddf1a6440afcc49361d8 100644 (file)
@@ -109,6 +109,11 @@ module RichText
       @image_element.attr["alt"] if @image_element
     end
 
+    def description
+      @paragraph_element = first_paragraph_element(document.root) unless defined? @paragraph_element
+      text_content(@paragraph_element) if @paragraph_element
+    end
+
     private
 
     def document
@@ -124,9 +129,37 @@ module RichText
       end
     end
 
+    def first_paragraph_element(element)
+      return element if paragraph?(element)
+
+      element.children.find do |child|
+        nested_paragraph = first_paragraph_element(child)
+        break nested_paragraph if nested_paragraph
+      end
+    end
+
+    def text_content(element)
+      text = ""
+
+      append_text = lambda do |child|
+        if child.type == :text
+          text << child.value
+        else
+          child.children.each { |c| append_text.call(c) }
+        end
+      end
+      append_text.call(element)
+
+      text
+    end
+
     def image?(element)
       element.type == :img || (element.type == :html_element && element.value == "img")
     end
+
+    def paragraph?(element)
+      element.type == :p
+    end
   end
 
   class Text < Base
index 3e17cac7b6303232f000c8c55e23749dcd7f3811..3536db3989e7ffde8a2f539cc00a051e55eb9c98 100644 (file)
@@ -335,6 +335,21 @@ class RichTextTest < ActiveSupport::TestCase
     assert_nil r.description
   end
 
+  def test_markdown_description
+    r = RichText.new("markdown", "This is an article about something.")
+    assert_equal "This is an article about something.", r.description
+  end
+
+  def test_markdown_description_after_heading
+    r = RichText.new("markdown", "#Heading\n\nHere starts the text.")
+    assert_equal "Here starts the text.", r.description
+  end
+
+  def test_markdown_description_elements
+    r = RichText.new("markdown", "*Something* **important** [here](https://example.com/).")
+    assert_equal "Something important here.", r.description
+  end
+
   private
 
   def assert_html(richtext, &block)