Class: Sourcerer::MarkDownGrade::LiWithNestedLists

Inherits:
ReverseMarkdown::Converters::Base
  • Object
show all
Defined in:
lib/sourcerer/mark_down_grade.rb

Overview

List item converter that handles nested lists and checklists.

Instance Method Summary collapse

Instance Method Details

#convert(node, state = {}) ⇒ Object



583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
# File 'lib/sourcerer/mark_down_grade.rb', line 583

def convert node, state={}
  indentation = indentation_from(state)

  content_parts = []
  nested_lists = []

  # Check for checkbox in this LI or its first paragraph
  # Asciidoctor often puts the checkbox inside a <p> tag
  checkbox = node.at_xpath('./input[@type="checkbox"] | ./p/input[@type="checkbox"][1]')

  prefix = if checkbox
             is_checked = checkbox['checked'] || checkbox['data-item-complete'] == '1'
             # Remove the checkbox from the DOM so it doesn't get rendered again
             checkbox.remove
             is_checked ? '- <!--CHECKBOX_CHECKED--> ' : '- <!--CHECKBOX_UNCHECKED--> '
           else
             prefix_for(node)
           end

  node.children.each do |child|
    if child.element? && %w[ol ul].include?(child.name)
      nested_lists << child
    else
      content_parts << treat(child, state)
    end
  end

  content = content_parts.join.strip
  result = "#{indentation}#{prefix}#{content}\n"

  nested_lists.each do |nested_list|
    # Pass the same state; the Ul/Ol converter will handle ol_count incrementing.
    # Use sub to strip only the leading newline emitted by the Ul/Ol converter,
    # preserving per-line indentation built by indentation_from.
    nested_md = treat(nested_list, state).sub(/\A\n+/, '').rstrip
    result << "#{nested_md}\n" unless nested_md.strip.empty?
  end

  result
end