]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/plugins-tasklist.js
Changed to a psuedo-style approach for tasklist in wysiwyg
[bookstack] / resources / js / wysiwyg / plugins-tasklist.js
1 /**
2  * @param {Editor} editor
3  * @param {String} url
4  */
5
6 function register(editor, url) {
7
8     editor.on('PreInit', () => {
9
10         editor.parser.addNodeFilter('li', function(nodes) {
11             for (const node of nodes) {
12                 if (node.attributes.map.class === 'task-list-item') {
13                     parseTaskListNode(node);
14                 }
15             }
16         });
17
18         editor.serializer.addNodeFilter('li', function(nodes) {
19             for (const node of nodes) {
20                 if (node.attributes.map.class === 'task-list-item') {
21                     serializeTaskListNode(node);
22                 }
23             }
24         });
25
26     });
27
28 }
29
30 /**
31  * @param {AstNode} node
32  */
33 function parseTaskListNode(node) {
34     // Force task list item class
35     node.attr('class', 'task-list-item');
36
37     // Copy checkbox status and remove checkbox within editor
38     for (const child of node.children()) {
39         if (child.name === 'input') {
40             if (child.attr('checked') === 'checked') {
41                 node.attr('checked', 'checked');
42             }
43             child.remove();
44         }
45     }
46 }
47
48 /**
49  * @param {AstNode} node
50  */
51 function serializeTaskListNode(node) {
52     const isChecked = node.attr('checked') === 'checked';
53     node.attr('checked', null);
54
55     const inputAttrs = {type: 'checkbox', disabled: 'disabled'};
56     if (isChecked) {
57         inputAttrs.checked = 'checked';
58     }
59
60     const checkbox = new tinymce.html.Node.create('input', inputAttrs);
61     checkbox.shortEnded = true;
62     node.firstChild ? node.insert(checkbox, node.firstChild, true) : node.append(checkbox);
63 }
64
65 /**
66  * @param {WysiwygConfigOptions} options
67  * @return {register}
68  */
69 export function getPlugin(options) {
70     return register;
71 }