Class: Mato::HtmlFilters::TaskList

Inherits:
Object
  • Object
show all
Defined in:
lib/mato/html_filters/task_list.rb

Constant Summary collapse

CHECKED_MARK =
"[x] "
UNCHECKED_MARK =
"[ ] "
DEFAULT_TASK_LIST_CLASS =
"task-list-item"
DEFAULT_CHECKBOX_CLASS =
"task-list-item-checkbox"

Instance Method Summary collapse

Constructor Details

#initialize(task_list_class: DEFAULT_TASK_LIST_CLASS, checkbox_class: DEFAULT_CHECKBOX_CLASS) ⇒ TaskList

Returns a new instance of TaskList.



12
13
14
15
# File 'lib/mato/html_filters/task_list.rb', line 12

def initialize(task_list_class: DEFAULT_TASK_LIST_CLASS, checkbox_class: DEFAULT_CHECKBOX_CLASS)
  @task_list_class = task_list_class
  @checkbox_class = checkbox_class
end

Instance Method Details

#build_checkbox_node(checked) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/mato/html_filters/task_list.rb', line 55

def build_checkbox_node(checked)
  Nokogiri::HTML.fragment('<input type="checkbox"/>').tap do |fragment|
    checkbox = fragment.children.first
    checkbox["class"] = @checkbox_class
    checkbox["disabled"] = 'disabled'
    checkbox["checked"] = 'checked' if checked
  end
end

#call(doc) ⇒ Object

Parameters:

  • doc (Nokogiri::HTML::DocumentFragment)


18
19
20
21
22
# File 'lib/mato/html_filters/task_list.rb', line 18

def call(doc)
  doc.search("li").each do |li|
    weave(li)
  end
end

#has_checked_mark?(text_node) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/mato/html_filters/task_list.rb', line 39

def has_checked_mark?(text_node)
  text_node&.content&.start_with?(CHECKED_MARK)
end

#has_unchecked_mark?(text_node) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/mato/html_filters/task_list.rb', line 43

def has_unchecked_mark?(text_node)
  text_node&.content&.start_with?(UNCHECKED_MARK)
end

#trim_mark(content, checked) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/mato/html_filters/task_list.rb', line 47

def trim_mark(content, checked)
  if checked
    content.sub(CHECKED_MARK, '')
  else
    content.sub(UNCHECKED_MARK, '')
  end
end

#weave(li) ⇒ Object

Parameters:

  • li (Nokogiri::XML::Node)


25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mato/html_filters/task_list.rb', line 25

def weave(li)
  text_node = li.xpath('.//text()').first
  checked = has_checked_mark?(text_node)
  unchecked = has_unchecked_mark?(text_node)

  return unless checked || unchecked

  li["class"] = @task_list_class

  text_node.content = trim_mark(text_node.content, checked)
  checkbox = build_checkbox_node(checked)
  text_node.add_previous_sibling(checkbox)
end