diff --git a/actiontext/CHANGELOG.md b/actiontext/CHANGELOG.md index bcf0052afe..17b606d6ad 100644 --- a/actiontext/CHANGELOG.md +++ b/actiontext/CHANGELOG.md @@ -1,3 +1,7 @@ +* Fix an issue with how nested lists were displayed when converting to plain text + + *Matt Swanson* + * Allow passing in a custom `direct_upload_url` or `blob_url_template` to `rich_text_area_tag`. *Lucas Mansur* diff --git a/actiontext/lib/action_text/plain_text_conversion.rb b/actiontext/lib/action_text/plain_text_conversion.rb index f7ae60f59c..408f243f8a 100644 --- a/actiontext/lib/action_text/plain_text_conversion.rb +++ b/actiontext/lib/action_text/plain_text_conversion.rb @@ -33,10 +33,18 @@ module ActionText "#{remove_trailing_newlines(plain_text_for_node_children(node))}\n\n" end - %i[ h1 p ul ol ].each do |element| + %i[ h1 p ].each do |element| alias_method :"plain_text_for_#{element}_node", :plain_text_for_block end + def plain_text_for_list(node, index) + "#{break_if_nested_list(node, plain_text_for_block(node))}" + end + + %i[ ul ol ].each do |element| + alias_method :"plain_text_for_#{element}_node", :plain_text_for_list + end + def plain_text_for_br_node(node, index) "\n" end @@ -61,7 +69,9 @@ module ActionText def plain_text_for_li_node(node, index) bullet = bullet_for_li_node(node, index) text = remove_trailing_newlines(plain_text_for_node_children(node)) - "#{bullet} #{text}\n" + indentation = indentation_for_li_node(node) + + "#{indentation}#{bullet} #{text}\n" end def remove_trailing_newlines(text) @@ -79,5 +89,24 @@ module ActionText def list_node_name_for_li_node(node) node.ancestors.lazy.map(&:name).grep(/^[uo]l$/).first end + + def indentation_for_li_node(node) + depth = list_node_depth_for_node(node) + if depth > 1 + " " * (depth - 1) + end + end + + def list_node_depth_for_node(node) + node.ancestors.map(&:name).grep(/^[uo]l$/).count + end + + def break_if_nested_list(node, text) + if list_node_depth_for_node(node) > 0 + "\n#{text}" + else + text + end + end end end diff --git a/actiontext/test/unit/plain_text_conversion_test.rb b/actiontext/test/unit/plain_text_conversion_test.rb index e3e0a8e00e..ffe4e577e7 100644 --- a/actiontext/test/unit/plain_text_conversion_test.rb +++ b/actiontext/test/unit/plain_text_conversion_test.rb @@ -52,6 +52,27 @@ class ActionText::PlainTextConversionTest < ActiveSupport::TestCase ) end + test "basic nested