summaryrefslogtreecommitdiff
path: root/assets/js/components/suggest-menu.js
blob: 63a7551c0c82a28b57dd4ca408e497e2c59cd787 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
KB.component('suggest-menu', function(containerElement, options) {

    function onKeyDown(e) {
        switch (e.keyCode) {
            case 27:
                destroy();
                break;
            case 38:
                e.preventDefault();
                e.stopImmediatePropagation();
                moveUp();
                break;
            case 40:
                e.preventDefault();
                e.stopImmediatePropagation();
                moveDown();
                break;
            case 13:
                e.preventDefault();
                e.stopImmediatePropagation();
                insertSelectedItem();
                break;
        }
    }

    function onClick() {
        insertSelectedItem();
    }

    function onMouseOver(element) {
        if (KB.dom(element).hasClass('suggest-menu-item')) {
            KB.find('.suggest-menu-item.active').removeClass('active');
            KB.dom(element).addClass('active');
        }
    }

    function insertSelectedItem() {
        var element = KB.find('.suggest-menu-item.active');
        var value = element.data('value');
        var trigger = element.data('trigger');
        var content = containerElement.value;
        var text = getLastWord(containerElement);
        var substitute = trigger + value + ' ';
        var before = content.substring(0, containerElement.selectionStart - text.length);
        var after = content.substring(containerElement.selectionEnd);
        var position = before.length + substitute.length;

        containerElement.value = before + substitute + after;
        containerElement.setSelectionRange(position, position);

        destroy();
    }

    function getLastWord(element) {
        var lines = element.value.substring(0, element.selectionEnd).split("\n");
        var lastLine = lines[lines.length - 1];
        var words = lastLine.split(' ');
        return words[words.length - 1];
    }

    function getParentElement() {
        var selectors = ['.popover-form', '#popover-content', 'body'];

        for (var i = 0; i < selectors.length; i++) {
            var element = document.querySelector(selectors[i]);

            if (element !== null) {
                return element;
            }
        }

        return null;
    }

    function resetSelection() {
        var elements = document.querySelectorAll('.suggest-menu-item');

        for (var i = 0; i < elements.length; i++) {
            if (KB.dom(elements[i]).hasClass('active')) {
                KB.dom(elements[i]).removeClass('active');
                break;
            }
        }

        return {items: elements, index: i};
    }

    function moveUp() {
        var result = resetSelection();

        if (result.index > 0) {
            result.index = result.index - 1;
        }

        KB.dom(result.items[result.index]).addClass('active');
    }

    function moveDown() {
        var result = resetSelection();

        if (result.index < result.items.length - 1) {
            result.index++;
        }

        KB.dom(result.items[result.index]).addClass('active');
    }

    function destroy() {
        var element = KB.find('#suggest-menu');

        if (element !== null) {
            element.remove();
        }

        document.removeEventListener('keydown', onKeyDown, false);
    }

    function search(element) {
        var text = getLastWord(element);
        var trigger = getTrigger(text, options.triggers);

        destroy();

        if (trigger !== null) {
            fetchItems(trigger, text.substring(trigger.length), options.triggers[trigger]);
        }
    }

    function getTrigger(text, triggers) {
        for (var trigger in triggers) {
            if (triggers.hasOwnProperty(trigger) && text.indexOf(trigger) === 0) {
                return trigger;
            }
        }

        return null;
    }

    function fetchItems(trigger, text, value) {
        if (typeof value === 'string') {
            KB.http.get(value).success(function (response) {
                onItemFetched(trigger, text, response);
            });
        } else {
            onItemFetched(trigger, text, value);
        }
    }

    function onItemFetched(trigger, text, items) {
        items = filterItems(text, items);

        if (items.length > 0) {
            renderMenu(buildItems(trigger, items));
        }
    }

    function filterItems(text, items) {
        var filteredItems = [];

        if (text.length === 0) {
            return items;
        }

        for (var i = 0; i < items.length; i++) {
            if (items[i].value.toLowerCase().indexOf(text.toLowerCase()) === 0) {
                filteredItems.push(items[i]);
            }
        }

        return filteredItems;
    }

    function buildItems(trigger, items) {
        var elements = [];

        for (var i = 0; i < items.length; i++) {
            var className = 'suggest-menu-item';

            if (i === 0) {
                className += ' active';
            }

            elements.push({
                class: className,
                html: items[i].html,
                'data-value': items[i].value,
                'data-trigger': trigger
            });
        }

        return elements;
    }

    function renderMenu(items) {
        var parentElement = getParentElement();
        var caretPosition = getCaretCoordinates(containerElement, containerElement.selectionEnd);
        var left = caretPosition.left + containerElement.offsetLeft;
        var top = caretPosition.top + containerElement.offsetTop + 16;

        document.addEventListener('keydown', onKeyDown, false);

        var menu = KB.dom('ul')
            .attr('id', 'suggest-menu')
            .click(onClick)
            .mouseover(onMouseOver)
            .style('left', left + 'px')
            .style('top', top + 'px')
            .for('li', items)
            .build();

        parentElement.appendChild(menu);
    }

    this.render = function () {
        containerElement.addEventListener('input', function () {
            search(this);
        });
    };
});