BigW Consortium Gitlab

taskable.rb 2.18 KB
Newer Older
1
require 'task_list'
Robert Speicher committed
2
require 'task_list/filter'
3

4 5 6 7 8 9
# Contains functionality for objects that can have task lists in their
# descriptions.  Task list items can be added with Markdown like "* [x] Fix
# bugs".
#
# Used by MergeRequest and Issue
module Taskable
10 11
  COMPLETED    = 'completed'.freeze
  INCOMPLETE   = 'incomplete'.freeze
12 13
  ITEM_PATTERN = /
    ^
14 15 16 17
    \s*(?:[-+*]|(?:\d+\.)) # list prefix required - task item has to be always in a list
    \s+                       # whitespace prefix has to be always presented for a list item
    (\[\s\]|\[[xX]\])         # checkbox
    (\s.+)                    # followed by whitespace and some text.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
  /x

  def self.get_tasks(content)
    content.to_s.scan(ITEM_PATTERN).map do |checkbox, label|
      # ITEM_PATTERN strips out the hyphen, but Item requires it. Rabble rabble.
      TaskList::Item.new("- #{checkbox}", label.strip)
    end
  end

  def self.get_updated_tasks(old_content:, new_content:)
    old_tasks, new_tasks = get_tasks(old_content), get_tasks(new_content)

    new_tasks.select.with_index do |new_task, i|
      old_task = old_tasks[i]
      next unless old_task

34
      new_task.source == old_task.source && new_task.complete? != old_task.complete?
35 36 37
    end
  end

38 39 40
  # Called by `TaskList::Summary`
  def task_list_items
    return [] if description.blank?
41

42
    @task_list_items ||= Taskable.get_tasks(description)
43
  end
44

45 46
  def tasks
    @tasks ||= TaskList.new(self)
47 48 49 50
  end

  # Return true if this object's description has any task list items.
  def tasks?
51
    tasks.summary.items?
52 53 54
  end

  # Return a string that describes the current state of this Taskable's task
55
  # list items, e.g. "12 of 20 tasks completed"
56
  def task_status(short: false)
57
    return '' if description.blank?
58

59 60 61 62 63 64
    prep, completed = if short
                        ['/', '']
                      else
                        [' of ', ' completed']
                      end

65
    sum = tasks.summary
66 67 68 69 70 71 72
    "#{sum.complete_count}#{prep}#{sum.item_count} #{'task'.pluralize(sum.item_count)}#{completed}"
  end

  # Return a short string that describes the current state of this Taskable's
  # task list items -- for small screens
  def task_status_short
    task_status(short: true)
73 74
  end
end