summaryrefslogtreecommitdiff
path: root/js/codeq/hint.js
blob: 5db9fca3fefaa545287e92e38d02fc7361186aba (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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/**
 * 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, problemDef, commonDef) {
        var hintCounter = 0, // for generating unique class-names
            hintCleaners = [],
            popoverHintCleaners = [], // we require separate cleaners for popups, because they are rebuilt when the editor's DOM changes
            popoverCreators = [], // functions that rebuild popover handlers after the editor's DOM changes
            planIdx = 0,
            dictionary = [],
            jqHintsContainer = jqHints.parent(),
            hintProblemDefs = problemDef.hint_type,
            hintCommonDefs = commonDef.hint_type,
            hintProblemTr = problemDef.hint,
            hintCommonTr = commonDef.hint,
            planDef = problemDef.plan,
            templatePath = [problemDef.language, problemDef.group, problemDef.problem],
            templateName = templatePath.join('/'),
            guiDict = codeq.tr.getDictionary('gui'),
            btnMoreTranslations = guiDict['btn_more'] || {}, // get the default translations for the "more..." button

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

            addMark = function (start, end, style) {
                var posStart = editor.posFromIndex(start),
                    posEnd = editor.posFromIndex(end),
                    doc = editor.getDoc(),
                    mark = doc.markText(posStart, posEnd, {'className': 'editor-mark _emark_' + hintCounter + ' ' + style}),
                    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) {
                var fn = codeq.templator(template, templatePath, templateName);
                return fn(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;');
                });*/
            },

            prepareStaticHintContent = function (hintContent, indices, hintId) {
                var content = {},
                    langs = codeq.availableLangs,
                    skippedLangs = [],
                    Nhints = 0, // count hints and remember the count
                    haveIndices = indices instanceof Array,
                    i, lang, j, node, tmpContent;
                langLoop:
                for (j = langs.length - 1; j >= 0; j--) {
                    lang = langs[j];
                    node = hintContent[lang];
                    if (!node) {
                        // no translation for this language, mark for later
                        skippedLangs.push(lang);
                    }
                    else {
                        if (haveIndices) {
                            // traverse node's indices
                            for (i = 0; i < indices.length; i++) {
                                node = node[indices[i]];
                                if (!node) {
                                    // index out of bounds, mark this language for later
                                    codeq.log.error('Cannot reference hint ' + hintId + ' with indices ' + indices);
                                    skippedLangs.push(lang);
                                    continue langLoop;
                                }
                            }
                        }
                        if (typeof node === 'string') {
                            // we have a single string (= a simplex message), put it into an array
                            content[lang] = [node];
                            if (Nhints < 1) Nhints = 1;
                        }
                        else if (node instanceof Array) {
                            // we already have an array
                            if (node.length == 0) {
                                if (haveIndices) codeq.log.error('Hint ' + hintId + ' with indices ' + indices + ' for language ' + lang + ' contains an empty array');
                                else codeq.log.error('Hint ' + hintId + ' for language ' + lang + ' contains an empty array');
                                skippedLangs.push(lang);
                                continue;
                            }
                            // verify that each array element is a string or an object with a message
                            for (i = node.length - 1; i >= 0; i--) {
                                tmpContent = node[i];
                                if (typeof tmpContent === 'string') {
                                    // this is okay
                                }
                                else if (tmpContent && (typeof tmpContent === 'object')) {
                                    if (typeof tmpContent.message !== 'string') {
                                        if (haveIndices) tmpContent.message = 'There is no message defined for hint ' + hintId + 'with indices ' + indices + ' in language ' + lang + ' at index ' + i;
                                        else tmpContent.message = 'There is no message defined for hint ' + hintId + ' in language ' + lang + ' at index ' + i;
                                        codeq.log.error(tmpContent.message);
                                    }
                                }
                                else {
                                    // not a string or an object with a message
                                    if (haveIndices) tmpContent = 'There is no message defined for hint ' + hintId + 'with indices ' + indices + ' in language ' + lang + ' at index ' + i;
                                    else tmpContent = 'There is no message defined for hint ' + hintId + ' in language ' + lang + ' at index ' + i;
                                    node[i] = tmpContent;
                                    codeq.log.error(tmpContent);
                                }
                            }
                            content[lang] = node;
                            if (Nhints < node.length) Nhints = node.length;
                        }
                        else if (node && (typeof node === 'object') && (typeof node.message === 'string')) {
                            // we have a single object with a message (= a complex message), put it into an array
                            content[lang] = [node];
                            if (Nhints < 1) Nhints = 1;
                        }
                        else {
                            if (haveIndices) codeq.log.error('Hint ' + hintId + ' with indices ' + indices + ' did not result in a terminal node for language ' + lang + ', but: ' + node);
                            else codeq.log.error('Hint ' + hintId + ' probably needs indices because it does not have a terminal node for language ' + lang + ', but: ' + node);
                            skippedLangs.push(lang);
                        }
                    }
                }
                if (Nhints === 0) {
                    // provide error feedback on display when there is no hint translation available in any language
                    if (haveIndices) tmpContent = ['No hints found for hint ' + hintId + ' with indices ' + indices];
                    else tmpContent = ['No hints found for hint ' + hintId];
                    codeq.log.error(tmpContent[0]);
                    for (j = langs.length - 1; j >= 0; j--) {
                        content[langs[j]] = tmpContent;
                    }
                    Nhints = 1;
                }
                else if (skippedLangs.length > 0) {
                    // choose a default content and assign it to skipped languages
                    lang = 'en'; // try English first
                    tmpContent = content[lang];
                    if (!tmpContent) {
                        // if no English exists, find one that does
                        for (lang in content) {
                            if (!content.hasOwnProperty(lang)) continue;
                            tmpContent = content[lang];
                            if (tmpContent) break;
                        }
                    }
                    codeq.log.error('Translations in languages ' + skippedLangs.join(', ') + ' are missing or erroneous for hint ' + hintId + ', replacing their content with translation for ' + lang);
                    // assign the default content to skipped languages
                    for (j = skippedLangs.length - 1; j >= 0; j--) {
                        content[skippedLangs[j]] = tmpContent;
                    }
                }
                content.hintLength = Nhints;
                return content;
            },

            ta = function (trObj) { // an object of the form: {'en': 'english content', 'sl': 'slovenska vsebina'}
                var result = ['data-dict="', trNamespace, '" data-tkey="', dictionary.length, '"'].join('');
                dictionary.push(trObj);
                return result;
            },

            typeHandlers = {
                'static': function (type, template, serverHint, hintId) {
                    var content = prepareStaticHintContent(template, serverHint.indices, hintId),
                        args = serverHint ? serverHint.args : null,
                        hintIndex = 0,
                        trButton = {},
                        Nhints = content.hintLength,
                        nextJqHint = function () {
                            var trContent = {},
                                langs = codeq.availableLangs,
                                lang, i, msg, jq, deltaHeight;
                            for (i = langs.length - 1; i >= 0; i--) {
                                lang = langs[i];
                                try {
                                    msg = content[lang][hintIndex];
                                    if (typeof msg === 'string') {
                                        trContent[lang] = processTemplate(msg, args);
                                        trButton[lang] = btnMoreTranslations[lang] || 'More...';
                                    }
                                    else {
                                        trContent[lang] = processTemplate(msg.message, args);
                                        trButton[lang] = msg.linkText;
                                    }
                                }
                                catch (e) {
                                    msg = 'Error processing hint ' + hintId + ' at index ' + hintIndex + ' for language ' + lang + ': ' + e;
                                    codeq.log.error(msg, e);
                                    trContent[lang] = msg;
                                }
                            }
                            jq = $('<div class="hint-static" ' + ta(trContent) + '></div>');
                            hintIndex++;
                            if (jqButton) {
                                if (hintIndex < Nhints) {
                                    jqButton.before(jq);
                                    codeq.tr.translateDom(jqButton);
                                }
                                else {
                                    jqButton.remove();
                                    jqContainer.append(jq);
                                }
                            }
                            else {
                                jqContainer.prepend(jq);
                            }
                            codeq.tr.translateDom(jq);
                            //// scroll into view if overflowing
                            //deltaHeight = jqHints.height() - jqHintsContainer.height();
                            //if (deltaHeight > 0) {
                            //    jqHintsContainer.scrollTop(deltaHeight);
                            //}
                            jqHintsContainer.scrollTop(0);
                        },
                        jqContainer, jqButton;

                    if (Nhints > 1) {
                        // hint sequence
                        jqContainer = $('<div class="hint-static-group"></div>');
                        jqButton = $('<a class="hint-static-link" ' + ta(trButton) + '></a>');
                        jqHints.prepend(jqContainer);
                        jqContainer.append(jqButton);
                        jqButton.on('click', function () {
                            nextJqHint();
                        });
                    }
                    else {
                        // a single hint
                        jqContainer = jqHints;
                        jqButton = null;
                    }
                    nextJqHint();

                    // no hint cleaner here, a static hint remains on the screen
                },

                'popup': function (type, template, serverHint) {
                    codeq.log.debug('Processing popup hint');
                    var args = serverHint.args,
                        style = serverHint.style || '',
                        mark = addMark(serverHint.start, serverHint.end, style), // add the mark
                        langs = codeq.availableLangs,
                        translations = {},
                        lang, i, content, htmlPrefix, instFunc;

                    // execute templates for all languages
                    for (i = langs.length - 1; i >= 0; i--) {
                        lang = langs[i];
                        content = template[lang];
                        if (typeof content === 'string') {
                            translations[lang] = processTemplate(content, args);
                        }
                        else {
                            translations[lang] = 'No translation in ' + lang + ' available for ' + type + ' hint ' + serverHint.id;
                            codeq.log.error(translations[lang]);
                        }
                    }
                    // construct the wrapper element for the translation mechanism
                    htmlPrefix = '<span ' + ta(translations) + '>';
                    // create the popover after all the DOM modifications have been made, otherwise only the last made popover can be triggered
                    instFunc = function () {
                        var jqMark = jqEditor.find('.' + mark.className);
                        jqMark.popover({
                            'content': function () {
                                // decide on what to display only after the popup is triggered, so we can choose the correct translation
                                return htmlPrefix + translations[codeq.settings['gui_lang']] + '</span>';
                            },
                            'html': true,
                            'placement': 'auto bottom',
                            'trigger': 'hover focus click',
                            'container': 'body'
                        });
                        // remove the popup on next hint pack
                        popoverHintCleaners.push(function () { if (jqMark) { jqMark.popover('destroy'); jqMark = null; } });
                    };
                    popoverCreators.push(instFunc);
                    return instFunc;
                },

                '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);
                }
            },

            /**
             * When the editor updates its DOM, we have to re-register any popup hints.
             */
            onEditorUpdate = function () {
                var i;
                for (i = 0; i < popoverHintCleaners.length; i++) popoverHintCleaners[i]();
                for (i = 0; i < popoverCreators.length; i++) popoverCreators[i]();
            };

        codeq.tr.registerDictionary(trNamespace, dictionary);
        editor.on('update', onEditorUpdate);

        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], {}, 'plan');
                    planIdx++;
                }
                return planIdx < planDef.length;
            },

            'hasNextPlan': function () {
                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,
                    finalizers = [],
                    i, serverHint, hintId, hintDef, hintContent, hintType, t, fn, ret;

                clearHints();
                mainLoop:
                for (i = 0; i < n; i++) {
                    serverHint = serverHints[i];
                    hintId = serverHint.id;
                    hintDef = hintProblemDefs[hintId] || hintCommonDefs[hintId];
                    if (!hintDef) {
                        codeq.log.error('Undefined hint: ' + hintId);
                        continue;
                    }
                    hintContent = hintProblemTr[hintId] || hintCommonTr[hintId];
                    if (!hintContent) {
                        codeq.log.error('Hint without content: ' + hintId);
                        continue;
                    }

                    t = typeof hintDef;
                    if (t === 'string') hintType = hintDef; // currently a hint type is a string
                    else if ((t === 'object') && (hintDef !== null)) hintType = hintDef.type; // but in future we may use an object, if a definition becomes more complex
                    else {
                        codeq.log.error('Cannot determine the type of hint ' + hintId + ' from: ' + hintDef);
                        continue;
                    }

                    fn = typeHandlers[hintType];
                    if (!fn) codeq.log.error('Unsupported hint type: ' + hintType);
                    else {
                        ret = fn(hintType, hintContent, serverHint, hintId);
                        if (typeof ret === 'function') finalizers.push(ret);
                    }
                }
                // invoke any finalizers
                for (i = 0; i < finalizers.length; i++) {
                    finalizers[i]();
                }
            },

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