task_list.js 2.32 KB
Newer Older
1
import $ from 'jquery';
2
import 'deckar01-task_list';
3
import { __ } from '~/locale';
4
import axios from './lib/utils/axios_utils';
Phil Hughes's avatar
Phil Hughes committed
5
import Flash from './flash';
6

7
export default class TaskList {
8 9 10
  constructor(options = {}) {
    this.selector = options.selector;
    this.dataType = options.dataType;
11
    this.fieldName = options.fieldName;
Brett Walker's avatar
Brett Walker committed
12
    this.lockVersion = options.lockVersion;
13
    this.taskListContainerSelector = `${this.selector} .js-task-list-container`;
Fatih Acet's avatar
Fatih Acet committed
14 15
    this.updateHandler = this.update.bind(this);
    this.onSuccess = options.onSuccess || (() => {});
16 17 18 19
    this.onError =
      options.onError ||
      function showFlash(e) {
        let errorMessages = '';
20

21 22 23
        if (e.response.data && typeof e.response.data === 'object') {
          errorMessages = e.response.data.errors.join(' ');
        }
24

25
        return new Flash(errorMessages || __('Update failed'), 'alert');
26
      };
27

28 29 30 31
    this.init();
  }

  init() {
Fatih Acet's avatar
Fatih Acet committed
32 33
    this.disable(); // Prevent duplicate event bindings

34
    $(this.taskListContainerSelector).taskList('enable');
Fatih Acet's avatar
Fatih Acet committed
35
    $(document).on('tasklist:changed', this.taskListContainerSelector, this.updateHandler);
36 37
  }

38 39
  getTaskListTarget(e) {
    return e && e.currentTarget ? $(e.currentTarget) : $(this.taskListContainerSelector);
40 41 42 43
  }

  disableTaskListItems(e) {
    this.getTaskListTarget(e).taskList('disable');
44 45
  }

46 47
  enableTaskListItems(e) {
    this.getTaskListTarget(e).taskList('enable');
48 49 50 51
  }

  disable() {
    this.disableTaskListItems();
52
    $(document).off('tasklist:changed', this.taskListContainerSelector);
53 54 55
  }

  update(e) {
56
    const $target = $(e.target);
57
    const { index, checked, lineNumber, lineSource } = e.detail;
Simon Knox's avatar
Simon Knox committed
58
    const patchData = {};
59

60
    patchData[this.dataType] = {
61
      [this.fieldName]: $target.val(),
62
      lock_version: this.lockVersion,
63
      update_task: {
64 65
        index,
        checked,
66 67 68
        line_number: lineNumber,
        line_source: lineSource,
      },
69
    };
70

71
    this.disableTaskListItems(e);
72

73 74
    return axios
      .patch($target.data('updateUrl') || $('form.js-issuable-update').attr('action'), patchData)
75 76
      .then(({ data }) => {
        this.lockVersion = data.lock_version;
77
        this.enableTaskListItems(e);
78

79 80
        return this.onSuccess(data);
      })
81
      .catch(({ response }) => {
82
        this.enableTaskListItems(e);
83 84 85

        return this.onError(response.data);
      });
86 87
  }
}