summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/behaviors/markdown/nodes/task_list_item.js
blob: 095634340c110fbce7c0a12f98d6a0588edb9ed7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { HIGHER_PARSE_RULE_PRIORITY } from '../constants';

// Transforms generated HTML back to GFM for Banzai::Filter::TaskListFilter
export default () => ({
  name: 'task_list_item',
  schema: {
    attrs: {
      state: {
        default: null,
      },
    },
    defining: true,
    draggable: false,
    content: 'paragraph block*',
    parseDOM: [
      {
        priority: HIGHER_PARSE_RULE_PRIORITY,
        tag: 'li.task-list-item',
        getAttrs: (el) => {
          const checkbox = el.querySelector('input[type=checkbox].task-list-item-checkbox');
          if (checkbox?.matches('[data-inapplicable]')) {
            return { state: 'inapplicable' };
          } else if (checkbox?.checked) {
            return { state: 'done' };
          }

          return {};
        },
      },
    ],
    toDOM(node) {
      return [
        'li',
        {
          class: () => {
            if (node.attrs.state === 'inapplicable') {
              return 'task-list-item inapplicable';
            }

            return 'task-list-item';
          },
        },
        [
          'input',
          {
            type: 'checkbox',
            class: 'task-list-item-checkbox',
            checked: node.attrs.state === 'done',
            'data-inapplicable': node.attrs.state === 'inapplicable',
          },
        ],
        ['div', { class: 'todo-content' }, 0],
      ];
    },
  },
  toMarkdown(state, node) {
    switch (node.attrs.state) {
      case 'done':
        state.write('[x] ');
        break;
      case 'inapplicable':
        state.write('[~] ');
        break;
      default:
        state.write('[ ] ');
        break;
    }
    state.renderContent(node);
  },
});