diff options
author | Brett Walker <bwalker@gitlab.com> | 2019-01-23 03:05:38 +0300 |
---|---|---|
committer | Fatih Acet <acetfatih@gmail.com> | 2019-01-31 01:18:16 +0300 |
commit | d9c5668d2915d64cbd91880e1ff1c0c743e8aa99 (patch) | |
tree | 50b2362104953265170ae25a9026c6ad102e0b0d /app/models/concerns/taskable.rb | |
parent | 6243c04e20b480c8353ac820ac4eb7ea43b92718 (diff) |
Refactor toggling of task list item
Diffstat (limited to 'app/models/concerns/taskable.rb')
-rw-r--r-- | app/models/concerns/taskable.rb | 46 |
1 files changed, 43 insertions, 3 deletions
diff --git a/app/models/concerns/taskable.rb b/app/models/concerns/taskable.rb index 603d4d62578..547afd5ee06 100644 --- a/app/models/concerns/taskable.rb +++ b/app/models/concerns/taskable.rb @@ -9,9 +9,11 @@ require 'task_list/filter' # # Used by MergeRequest and Issue module Taskable - COMPLETED = 'completed'.freeze - INCOMPLETE = 'incomplete'.freeze - ITEM_PATTERN = %r{ + COMPLETED = 'completed'.freeze + INCOMPLETE = 'incomplete'.freeze + COMPLETE_PATTERN = /(\[[xX]\])/.freeze + INCOMPLETE_PATTERN = /(\[[\s]\])/.freeze + ITEM_PATTERN = %r{ ^ \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 @@ -37,6 +39,44 @@ module Taskable end end + def self.toggle_task(content, content_html, index:, currently_checked:, line_source:, line_number:) + source_lines = content.split("\n") + markdown_task = source_lines[line_number - 1] + output = {} + + if markdown_task == line_source + html = Nokogiri::HTML.fragment(content_html) + html_checkbox = html.css('.task-list-item-checkbox')[index - 1] + # html_checkbox = html.css(".task-list-item[data-sourcepos^='#{changed_line_number}:'] > input.task-list-item-checkbox").first + updated_task = toggle_task_source(line_source, currently_checked: currently_checked) + + if html_checkbox && updated_task + source_lines[line_number - 1] = updated_task + + if currently_checked + html_checkbox.remove_attribute('checked') + else + html_checkbox[:checked] = 'checked' + end + + output[:content] = source_lines.join("\n") + output[:content_html] = html.to_html + end + end + + output + end + + def self.toggle_task_source(markdown_line, currently_checked:) + if source_checkbox = ITEM_PATTERN.match(markdown_line) + if TaskList::Item.new(source_checkbox[1]).complete? + markdown_line.sub(COMPLETE_PATTERN, '[ ]') if currently_checked + else + markdown_line.sub(INCOMPLETE_PATTERN, '[x]') unless currently_checked + end + end + end + # Called by `TaskList::Summary` def task_list_items return [] if description.blank? |