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



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/sourcerer/mark_down_grade.rb', line 498

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|
    nested_state = state.merge(ol_count: state.fetch(:ol_count, 0) + 1)
    nested_md = treat(nested_list, nested_state).strip
    result << "#{nested_md}\n" unless nested_md.empty?
  end

  result
end