Class: GithubMarkdownPreview::Pipeline::TaskListFilter

Inherits:
HTML::Pipeline::Filter
  • Object
show all
Defined in:
lib/github-markdown-preview/filter/task_list_filter.rb

Overview

HTML filter that replaces ‘[ ] task` and `[x] task` list items with “task list” checkboxes

Can be configured to render disabled checkboxes for the task by adding :disabled_tasks => true to the Html pipeline context

Constant Summary collapse

COMPLETE_TASK_PATTERN =
/^[\s]*(\[\s\])([\s]+[^\s]*)/
INCOMPLETE_TASK_PATTERN =
/^[\s]*(\[x\])([\s]+[^\s]*)/

Instance Method Summary collapse

Instance Method Details

#callObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/github-markdown-preview/filter/task_list_filter.rb', line 27

def call
  process_task = Proc.new do |node|
    first_child = node.children.first
    next unless first_child.text?
    content = first_child.to_html
    html = task_list_item_filter(content)
    next if html == content
    (first_child.ancestors('li').first || { })['class'] = 'task-list-item'
    (first_child.ancestors('ul').first || { })['class'] = 'task-list'
    first_child.replace(html)
  end
  doc.search('ul/li').each &process_task
  doc.search('ul/li/p').each &process_task
  doc
end

#disabled_tasksObject



14
15
16
# File 'lib/github-markdown-preview/filter/task_list_filter.rb', line 14

def disabled_tasks
  !!context[:disabled_tasks]
end

#task_list_item_filter(text) ⇒ Object

Replace “[ ]” or “[x]” with corresponding checkbox input



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/github-markdown-preview/filter/task_list_filter.rb', line 44

def task_list_item_filter(text)
  return text unless text.include?('[ ]') || text.include?('[x]')

  [true, false].each do |complete|
    text = text.gsub task_pattern(complete) do
      task_markup(complete) + $2
    end
  end

  text
end

#task_markup(complete) ⇒ Object



23
24
25
# File 'lib/github-markdown-preview/filter/task_list_filter.rb', line 23

def task_markup(complete)
  "<input class=\"task-list-item-checkbox\" type=\"checkbox\" #{complete ? 'checked' : ''} #{disabled_tasks ? 'disabled' : ''}>"
end

#task_pattern(complete) ⇒ Object



18
19
20
21
# File 'lib/github-markdown-preview/filter/task_list_filter.rb', line 18

def task_pattern(complete)
  task_character = complete ? 'x' : '\s'
  /^[\s]*(\[#{task_character}\])([\s]+[^\s]*)/
end