summaryrefslogtreecommitdiff
path: root/js/codeq/hint.js
blob: 1b97afc977deb452533d5654aac18b40a12d1362 (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
220
221
222
223
224
225
226
/**
 * Creates a hint handler, displaying hints inside the provided jqHints <div>.
 */

(function () {
    // constants
    var firstCharacterPos = {'line': 0, 'ch': 0},
        sel_no_scroll = {'scroll': false};

    codeq.makeHinter = function (jqHints, jqEditor, editor, trNamespace, hintDefsA, commonHintDefsA, planDef) {
        var hintCounter = 0, // for generating unique class-names
            hintCleaners = [],
            planIdx = 0,
            dictionary = [],

            clearHints = function () {
                var i;
                for (i = hintCleaners.length - 1; i >= 0; i--) {
                    hintCleaners[i]();
                }
                hintCleaners.length = 0;
                hintCounter = 0;
            },

            addMark = function (start, end) {
                var posStart = editor.posFromIndex(start),
                    posEnd = editor.posFromIndex(end),
                    doc = editor.getDoc(),
                    mark = doc.markText(posStart, posEnd, {'className': 'editor-mark _emark_' + hintCounter}),
                    result = {'start': posStart, 'end': posEnd, 'mark': mark, 'className': '_emark_' + hintCounter};
                hintCleaners.push(function () { mark.clear(); mark = null; doc = null; result.mark = null; });
                hintCounter++;
                return result;
            },

            processTemplate = function (template, args) {
                if (!args)
                    return template;
                return template.replace(/\[%=(\w+)%\]/g, function(match, name) {
                    return args[name].toString()
                                     .replace(/&/g, '&amp')
                                     .replace(/</g, '&lt;')
                                     .replace(/>/g, '&gt;');
                });
            },

            typeHandlers = {
                'static': function (type, template, serverHint) {
                    var args = serverHint ? serverHint.args : null,
                        jqContainer, jqButton, i, N, tmpl, tmplIsObject;
                    if (template instanceof Array) { // unwrap the template if there's only one
                        if (template.length == 0) template = '';
                        else if (template.length == 1) template = template[0] + ''; // it must be a string
                    }
                    if (template instanceof Array) {
                        codeq.log.debug('Processing an array of static hints');
                        jqContainer = $('<div class="hint-static-group"></div>');
                        jqButton = $('<a class="hint-static-link"></a>');
                        jqHints.append(jqContainer);
                        N = template.length;
                        tmpl = template[0];
                        tmplIsObject = (typeof tmpl === 'object') && (tmpl !== null);
                        jqContainer.append('<div class="hint-static">' + processTemplate((tmplIsObject ? tmpl.message : tmpl) || '', args) + '</div>');
                        jqContainer.append(jqButton);
                        jqButton.text(tmplIsObject && tmpl.linkText ? tmpl.linkText : 'More...'); // TODO: translate "more"
                        i = 1;
                        jqButton.on('click', function () {
                            var tmpl = template[i],
                                tmplIsObject = (typeof tmpl === 'object') && (tmpl !== null),
                                jqNext = $('<div class="hint-static">' + processTemplate((tmplIsObject ? tmpl.message : tmpl) || '', args) + '</div>');
                            i++;
                            if (i < N) {
                                jqButton.before(jqNext);
                                jqButton.text(tmplIsObject && tmpl.linkText ? tmpl.linkText : 'More...'); // TODO: translate "more"
                            }
                            else {
                                jqButton.remove();
                                jqContainer.append(jqNext);
                            }
                        });
                    }
                    else {
                        codeq.log.debug('Processing a single static hint');
                        jqHints.append('<div class="hint-static">' + processTemplate(template, args) + '</div>');
                    }
                    // no hint cleaner here, a static hint remains on the screen
                },

                'popup': function (type, template, serverHint) {
                    codeq.log.debug('Processing popup hint');
                    var message = processTemplate(template, serverHint.args),
                        mark = addMark(serverHint.start, serverHint.end), // add the mark
                        jqMark = jqEditor.find('.' + mark.className);

                    jqMark.popover({'content': message, 'html': true, 'placement': 'auto bottom', 'trigger': 'hover focus click', 'container': 'body'});
                    hintCleaners.push(function () { if (jqMark) { jqMark.popover('destroy'); jqMark = null; } });

                    mark.mark.on('', function () {});
                },

                'dropdown': function (type, template, serverHint) {
                    codeq.log.debug('Processing dropdown hint');
                    var completion = null, // the completion object, created in showHint()
                        close = function () {
                            if (completion) {
                                completion.close();
                                completion = null;
                            }
                        };

                    if (/*(editor.listSelections().length > 1) ||*/ editor.somethingSelected()) {
                        // showHint() doesn't work if a selection is activeparts
                        editor.setSelection(firstCharacterPos, firstCharacterPos, sel_no_scroll); // deselect anything
                    }

                    editor.showHint({
                        hint: function () {
                            var hints = {
                                list: serverHint.choices,
                                from: editor.posFromIndex(serverHint.start),
                                to: editor.posFromIndex(serverHint.end)
                            };
                            completion = editor.state.completionActive;
                            return hints;
                        },
                        completeOnSingleClick: true,
                        completeSingle: false
                    });

                    hintCleaners.push(close);
                }
            };

        codeq.tr.registerDictionary(trNamespace, dictionary);

        // TODO: below is a temporary code to bridge the old implementation with the new data format
        if (planDef.sl) planDef = planDef.sl;
        else planDef = planDef.en || [];
        var hintDefs = {}, t1, t2, k;
        if (hintDefsA.sl) t1 = hintDefsA.sl;
        else t1 = hintDefsA.en || {};
        if (commonHintDefsA.sl) t2 = commonHintDefsA.sl;
        else t2 = commonHintDefsA.en || {};
        for (k in t2) {
            if (!t2.hasOwnProperty(k)) continue;
            hintDefs[k] = t2[k];
        }
        for (k in t1) {
            if (!t1.hasOwnProperty(k)) continue;
            hintDefs[k] = t1[k];
        }

        return {
            /** Display the next "planning" hint and return whether there are
             * any more available.
             */
            'planNext': function () {
                if (planIdx < planDef.length) {
                    typeHandlers['static']('static', planDef[planIdx], null);
                    planIdx++;
                }
                return planIdx < planDef.length;
            },

            /**
             * Processes and display appropriately the server hints.
             * TODO: sort hints so static and popup hints come first, and a (single) drop-down hint last
             *
             * @param {ServerHint[]} serverHints an array of hints from the server
             */
            'handle': function (serverHints) {
                var n = serverHints.length,
                    /** number */ i,
                    /** ServerHint */ serverHint,
                    /** HintDefinition */ hintDef,
                    hintType, hintTemplate, t, fn, indices;
                clearHints();
                mainLoop:
                for (i = 0; i < n; i++) {
                    serverHint = serverHints[i];
                    hintDef = hintDefs[serverHint.id];
                    if (!hintDef) {
                        codeq.log.error('Undefined hint ' + serverHint.id);
                        continue;
                    }
                    if (serverHint.indices) {
                        indices = serverHint.indices;
                        for (i = 0; i < indices.length; i++) {
                            hintDef = hintDef[indices[i]];
                            if (!hintDef) {
                                codeq.log.error('Undefined hint ' + serverHint.id + ' with indices ' + serverHint.indices);
                                continue mainLoop;
                            }
                        }
                    }
                    t = typeof hintDef;
                    if ((t === 'string') || (hintDef instanceof Array)) {
                        hintType = 'static';
                        hintTemplate = hintDef;
                    }
                    else if (t === 'object') {
                        hintType = hintDef.type;
                        hintTemplate = hintDef.message;
                    }
                    else {
                        codeq.log.error('Unsupported hint definition: ' + t);
                        continue;
                    }

                    fn = typeHandlers[hintType];
                    if (!fn) codeq.log.error('Unsupported hint type: ' + hintType);
                    else fn(hintType, hintTemplate, serverHint);
                }
            },

            'destroy': function () {
                clearHints();
                codeq.tr.unregisterDictionary(trNamespace);
                jqHints.empty();
                jqHints = null;
                jqEditor = null;
                editor = null;
            }
        };
    };
})();