Passed
Pull Request — master (#40)
by Michael
03:13
created

script/Menu/Dropdown.js   A

Size

Lines of Code 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 1
rs 10
noi 0
1
const { MenuItem } = require('./MenuItem');
2
3
class Dropdown extends MenuItem {
4
    constructor(content, options) {
5
        super({
6
            command: () => true,
7
            render: view => this.renderIcon(view, options),
8
        });
9
        this.content = Array.isArray(content) ? content : [content];
10
    }
11
12
    renderIcon(editorView, options) {
13
        const $menuItemContainer = jQuery('<span>').addClass('dropdown menuitem');
14
        const $dropdownLabel = jQuery('<span>').text(options.label).addClass('menulabel');
15
        $menuItemContainer.append($dropdownLabel);
16
17
        jQuery($dropdownLabel).on('mousedown', (e) => {
18
            e.preventDefault();
19
            e.stopPropagation();
20
            if (this.open) {
21
                this.open = false;
22
                this.hideContent();
23
            } else {
24
                this.open = true;
25
                this.showContent();
26
            }
27
        });
28
29
        this.renderDropdownItems(editorView, $menuItemContainer);
30
        this.hideContent();
31
32
        return $menuItemContainer.get(0);
33
    }
34
35
    showContent() {
36
        // TODO: add listener to close it by clicking anywhere else
37
        this.contentDom.style.display = 'block';
38
    }
39
40
    hideContent() {
41
        this.contentDom.style.display = 'none';
42
    }
43
44
45
    renderDropdownItems(editorView, $menuItemContainer) {
46
        this.contentDom = document.createElement('div');
47
        this.contentDom.className = 'dropdown_content';
48
        this.content.forEach((item) => {
49
            const itemDom = item.render(editorView);
50
            this.contentDom.appendChild(itemDom);
51
        });
52
        $menuItemContainer.append(this.contentDom);
53
    }
54
55
    update(editorView) {
56
        this.content.forEach((item) => {
57
            item.update(editorView);
58
        });
59
60
        if (this.isActive(editorView.state)) {
61
            this.dom.classList.add('is-active');
62
        } else {
63
            this.dom.classList.remove('is-active');
64
        }
65
66
        const isAnyItemEnabled = this.content.some(item => item.options.command(editorView.state, null, editorView));
67
        this.dom.style.display = isAnyItemEnabled ? '' : 'none';
68
    }
69
70
    isActive(state) {
71
        return this.content.some(item => item.isActive(state));
72
    }
73
}
74
75
exports.Dropdown = Dropdown;
76