Welcome to mirror list, hosted at ThFree Co, Russian Federation.

widgetMenu.js « javascripts « Dashboard « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f3752eb6e30e4e5a0f563d1dcc888fdbec63e9b0 (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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*!
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

function widgetsHelper() {
}

/**
 * Returns the available widgets fetched via AJAX (if not already done)
 *
 * @return {object} object containing available widgets
 */
widgetsHelper.getAvailableWidgets = function (callback) {

    function mergeCategoriesAndSubCategories(availableWidgets)
    {
        var categorized = {};

        $.each(availableWidgets, function (index, widget) {
            var category = widget.category.name;

            if (!categorized[category]) {
                categorized[category] = {'-': []};
            }

            var subcategory = '-';
            if (widget.subcategory && widget.subcategory.name) {
                subcategory = widget.subcategory.name;
            }

            if (!categorized[category][subcategory]) {
                categorized[category][subcategory] = [];
            }

            categorized[category][subcategory].push(widget);
        });

        var moved = {};

        $.each(categorized, function (category, widgets) {
            $.each(widgets, function (subcategory, subwidgets) {

                var categoryToUse = category;
                if (subwidgets.length >= 3 && subcategory !== '-') {
                    categoryToUse = category + ' - ' + subcategory;
                }

                if (!moved[categoryToUse]) {
                    moved[categoryToUse] = [];
                }

                $.each(subwidgets, function (index, widget) {
                    moved[categoryToUse].push(widget);
                });
            });
        });

        return moved;
    }

    if (!widgetsHelper.availableWidgets) {
        var ajaxRequest = new ajaxHelper();
        ajaxRequest._mixinDefaultGetParams = function (params) {
            return params;
        };
        ajaxRequest.addParams({
            module: 'API',
            method: 'API.getWidgetMetadata',
            filter_limit: '-1',
            format: 'JSON',
            deep: '1',
            idSite:  piwik.idSite || broadcast.getValueFromUrl('idSite')
        }, 'get');
        ajaxRequest.setCallback(
            function (data) {
                widgetsHelper.availableWidgets = mergeCategoriesAndSubCategories(data);

                if (callback) {
                    callback(widgetsHelper.availableWidgets);
                }
            }
        );
        ajaxRequest.setErrorCallback(function (deferred, status) {
            if (status == 'abort' || !deferred || deferred.status < 400 || deferred.status >= 600) {
                return;
            }
            $('#loadingError').show();
        });
        ajaxRequest.send();
        return;
    }

    if (callback) {
        callback(widgetsHelper.availableWidgets);
    }
};

/**
 * Determines the complete widget object by its unique id and sends it to callback method
 *
 * @param {string} uniqueId
 * @param {function} callback
 */
widgetsHelper.getWidgetObjectFromUniqueId = function (uniqueId, callback) {
    widgetsHelper.getAvailableWidgets(function(widgets){
        for (var widgetCategory in widgets) {
            var widgetInCategory = widgets[widgetCategory];
            for (var i in widgetInCategory) {
                if (widgetInCategory[i]["uniqueId"] == uniqueId) {
                    callback(widgetInCategory[i]);
                    return;
                }
            }
        }
        callback(false);
    });
};

/**
 * Determines the name of a widget by its unique id and sends it to the callback
 *
 * @param {string} uniqueId  unique id of the widget
 * @param {function} callback
 * @return {string}
 */
widgetsHelper.getWidgetNameFromUniqueId = function (uniqueId, callback) {
    this.getWidgetObjectFromUniqueId(uniqueId, function(widget) {
        if (widget == false) {
            callback(false);
        }
        callback(widget["name"]);
    });
};

/**
 * Sends and ajax request to query for the widgets html
 *
 * @param {string} widgetUniqueId             unique id of the widget
 * @param {object} widgetParameters           parameters to be used for loading the widget
 * @param {function} onWidgetLoadedCallback   callback to be executed after widget is loaded
 * @return {object}
 */
widgetsHelper.loadWidgetAjax = function (widgetUniqueId, widgetParameters, onWidgetLoadedCallback, onWidgetErrorCallback) {
    var disableLink = broadcast.getValueFromUrl('disableLink');
    widgetParameters['disableLink'] = disableLink.length || $('body#standalone').length;

    widgetParameters['widget'] = 1;

    var ajaxRequest = new ajaxHelper();
    ajaxRequest.addParams(widgetParameters, 'get');
    ajaxRequest.setCallback(onWidgetLoadedCallback);
    if (onWidgetErrorCallback) {
        ajaxRequest.setErrorCallback(onWidgetErrorCallback);
    }
    ajaxRequest.setFormat('html');
    ajaxRequest.send();
    return ajaxRequest;
};

(function ($, require) {
    var exports = require('piwik/UI/Dashboard');

    /**
     * Singleton instance that creates widget elements. Normally not needed even
     * when embedding/re-using dashboard widgets, but it can be useful when creating
     * elements with the same look and feel as dashboard widgets, but different
     * behavior (such as the widget preview in the dashboard manager control).
     *
     * @constructor
     */
    var WidgetFactory = function () {
        // empty
    };

    /**
     * Creates an HTML element for displaying a widget.
     *
     * @param {string} uniqueId     unique id of the widget
     * @param {string} widgetName   name of the widget
     * @return {Element} the empty widget
     */
    WidgetFactory.prototype.make = function (uniqueId, widgetName) {
        var $result = this.getWidgetTemplate().clone();
        $result.attr('id', uniqueId).find('.widgetName').append(widgetName);
        return $result;
    };

    /**
     * Returns the base widget template element. The template is stored in the
     * element with id == 'widgetTemplate'.
     *
     * @return {Element} the widget template
     */
    WidgetFactory.prototype.getWidgetTemplate = function () {
        if (!this.widgetTemplate) {
            this.widgetTemplate = $('#widgetTemplate').find('>.widget').detach();
        }
        return this.widgetTemplate;
    };

    exports.WidgetFactory = new WidgetFactory();
})(jQuery, require);

/**
 * widgetPreview jQuery Extension
 *
 * Converts an dom element to a widget preview
 * Widget preview contains an categorylist, widgetlist and a preview
 */
(function ($) {
    $.extend({
        widgetPreview: new function () {

            /**
             * Default settings for widgetPreview
             * @type {object}
             */
            var defaultSettings = {
                /**
                 * handler called after a widget preview is loaded in preview element
                 * @type {function}
                 */
                onPreviewLoaded: function () {},
                /**
                 * handler called on click on element in widgetlist or widget header
                 * @type {function}
                 */
                onSelect: function () {},
                /**
                 * callback used to determine if a widget is available or not
                 * unavailable widgets aren't chooseable in widgetlist
                 * @type {function}
                 */
                isWidgetAvailable: function (widgetUniqueId) { return true; },
                /**
                 * should the lists and preview be reset on widget selection?
                 * @type {boolean}
                 */
                resetOnSelect: false,
                /**
                 * css classes for various elements
                 * @type {string}
                 */
                baseClass: 'widgetpreview-base',
                categorylistClass: 'widgetpreview-categorylist',
                widgetlistClass: 'widgetpreview-widgetlist',
                widgetpreviewClass: 'widgetpreview-preview',
                choosenClass: 'widgetpreview-choosen',
                unavailableClass: 'widgetpreview-unavailable'
            };

            /**
             * Returns the div to show category list in
             * - if element doesn't exist it will be created and added
             * - if element already exist it's content will be removed
             *
             * @return {$} category list element
             */
            function createWidgetCategoryList(widgetPreview, availableWidgets) {

                var settings = widgetPreview.settings;

                if (!$('.' + settings.categorylistClass, widgetPreview).length) {
                    $(widgetPreview).append('<ul class="' + settings.categorylistClass + '"></ul>');
                } else {
                    $('.' + settings.categorylistClass, widgetPreview).empty();
                }

                for (var widgetCategory in availableWidgets) {
                    $('.' + settings.categorylistClass, widgetPreview).append($('<li>').text(widgetCategory));
                }

                return $('.' + settings.categorylistClass, widgetPreview);
            }

            /**
             * Returns the div to show widget list in
             * - if element doesn't exist it will be created and added
             * - if element already exist it's content will be removed
             *
             * @return {$} widget list element
             */
            function createWidgetList(widgetPreview) {
                var settings = widgetPreview.settings;

                if (!$('.' + settings.widgetlistClass, widgetPreview).length) {
                    $(widgetPreview).append('<ul class="' + settings.widgetlistClass + '"></ul>');
                } else {
                    $('.' + settings.widgetlistClass + ' li', widgetPreview).off('mouseover');
                    $('.' + settings.widgetlistClass + ' li', widgetPreview).off('click');
                    $('.' + settings.widgetlistClass, widgetPreview).empty();
                }

                if ($('.' + settings.categorylistClass + ' .' + settings.choosenClass, widgetPreview).length) {
                    var position = $('.' + settings.categorylistClass + ' .' + settings.choosenClass, widgetPreview).position().top -
                        $('.' + settings.categorylistClass, widgetPreview).position().top +
                        $('.dashboard-manager .addWidget').outerHeight();

                    if (!$('#content.admin').length) {
                        position += 5; // + padding defined in dashboard view
                    }

                    $('.' + settings.widgetlistClass, widgetPreview).css('top', position);
                    $('.' + settings.widgetlistClass, widgetPreview).css('marginBottom', position);
                }

                return $('.' + settings.widgetlistClass, widgetPreview);
            }

            /**
             * Display the given widgets in a widget list
             *
             * @param {object} widgets widgets to be displayed
             * @return {void}
             */
            function showWidgetList(widgets, widgetPreview) {
                var settings = widgetPreview.settings;

                var widgetList = createWidgetList(widgetPreview),
                    widgetPreviewTimer;

                for (var j = 0; j < widgets.length; j++) {
                    var widgetName = widgets[j]["name"];
                    var widgetUniqueId = widgets[j]["uniqueId"];
                    var widgetCategoryId = widgets[j].category ? widgets[j].category.id : null;
                    var widgetClass = '';
                    if (!settings.isWidgetAvailable(widgetUniqueId) && widgetCategoryId !== 'General_KpiMetric') {
                        widgetClass += ' ' + settings.unavailableClass;
                    }

                    widgetName = piwikHelper.escape(piwikHelper.htmlEntities(widgetName));

                    widgetList.append('<li class="' + widgetClass + '" uniqueid="' + widgetUniqueId + '">' + widgetName + '</li>');
                }

                // delay widget preview a few millisconds
                $('li', widgetList).on('mouseenter', function () {
                    var that = this,
                        widgetUniqueId = $(this).attr('uniqueid');
                    clearTimeout(widgetPreview);
                    widgetPreviewTimer = setTimeout(function () {
                        $('li', widgetList).removeClass(settings.choosenClass);
                        $(that).addClass(settings.choosenClass);

                        showPreview(widgetUniqueId, widgetPreview);
                    }, 400);
                });

                // clear timeout after mouse has left
                $('li:not(.' + settings.unavailableClass + ')', widgetList).on('mouseleave', function () {
                    clearTimeout(widgetPreview);
                });

                $('li', widgetList).on('click', function () {
                    if (!$('.widgetLoading', widgetPreview).length) {
                        settings.onSelect($(this).attr('uniqueid'));
                        $(widgetPreview).closest('.dashboard-manager').removeClass('expanded');
                        if (settings.resetOnSelect) {
                            resetWidgetPreview(widgetPreview);
                        }
                    }
                    return false;
                });
            }

            /**
             * Returns the div to show widget preview in
             * - if element doesn't exist it will be created and added
             * - if element already exist it's content will be removed
             *
             * @return {$} preview element
             */
            function createPreviewElement(widgetPreview) {
                var settings = widgetPreview.settings;

                if (!$('.' + settings.widgetpreviewClass, widgetPreview).length) {
                    $(widgetPreview).append('<div class="' + settings.widgetpreviewClass + '"></div>');
                } else {
                    $('.' + settings.widgetpreviewClass + ' .widgetTop', widgetPreview).off('click');
                    $('.' + settings.widgetpreviewClass, widgetPreview).empty();
                }

                return $('.' + settings.widgetpreviewClass, widgetPreview);
            }

            /**
             * Show widget with the given uniqueId in preview
             *
             * @param {string} widgetUniqueId unique id of widget to display
             * @param          widgetPreview
             * @return {void}
             */
            function showPreview(widgetUniqueId, widgetPreview) {
                // do not reload id widget already displayed
                if ($('[id="' + widgetUniqueId + '"]', widgetPreview).length) return;

                var settings = widgetPreview.settings;

                var previewElement = createPreviewElement(widgetPreview);

                widgetsHelper.getWidgetObjectFromUniqueId(widgetUniqueId, function(widget) {
                    var widgetParameters = widget['parameters'];

                    var emptyWidgetHtml = require('piwik/UI/Dashboard').WidgetFactory.make(
                        widgetUniqueId,
                        $('<span/>')
                            .attr('title', _pk_translate("Dashboard_AddPreviewedWidget"))
                            .text(_pk_translate('Dashboard_WidgetPreview'))
                    );
                    previewElement.html(emptyWidgetHtml);

                    var onWidgetLoadedCallback = function (response) {
                        var widgetElement = $(document.getElementById(widgetUniqueId));
                        // document.getElementById needed for widgets with uniqueid like widgetOpens+Contact+Form
                        $('.widgetContent', widgetElement).html($(response));
                        piwikHelper.compileAngularComponents($('.widgetContent', widgetElement), { forceNewScope: true });
                        $('.widgetContent', widgetElement).trigger('widget:create');
                        settings.onPreviewLoaded(widgetUniqueId, widgetElement);
                        $('.' + settings.widgetpreviewClass + ' .widgetTop', widgetPreview).on('click', function () {
                            settings.onSelect(widgetUniqueId);
                            $(widgetPreview).closest('.dashboard-manager').removeClass('expanded');
                            if (settings.resetOnSelect) {
                                resetWidgetPreview(widgetPreview);
                            }
                            return false;
                        });
                    };

                    // abort previous sent request
                    if (widgetPreview.widgetAjaxRequest) {
                        widgetPreview.widgetAjaxRequest.abort();
                    }

                    widgetPreview.widgetAjaxRequest = widgetsHelper.loadWidgetAjax(widgetUniqueId, widgetParameters, onWidgetLoadedCallback);
                });
            }

            /**
             * Reset function
             *
             * @return {void}
             */
            function resetWidgetPreview(widgetPreview) {
                var settings = widgetPreview.settings;

                $('.' + settings.categorylistClass + ' li', widgetPreview).removeClass(settings.choosenClass);
                createWidgetList(widgetPreview);
                createPreviewElement(widgetPreview);
            }

            /**
             * Constructor
             *
             * @param {object} userSettings Settings to be used
             * @return {void}
             */
            this.construct = function (userSettings) {

                if (userSettings == 'reset') {
                    resetWidgetPreview(this);
                    return;
                }

                this.widgetAjaxRequest = null;

                $(this).addClass('widgetpreview-base');

                this.settings = jQuery.extend({}, defaultSettings, userSettings);

                // set onSelect callback
                if (typeof this.settings.onSelect == 'function') {
                    this.onSelect = this.settings.onSelect;
                }

                // set onPreviewLoaded callback
                if (typeof this.settings.onPreviewLoaded == 'function') {
                    this.onPreviewLoaded = this.settings.onPreviewLoaded;
                }

                var self = this;
                widgetsHelper.getAvailableWidgets(function (availableWidgets) {

                    var categoryList = createWidgetCategoryList(self, availableWidgets);

                    $('li', categoryList).on('mouseover', function () {
                        var category = $(this).text();
                        var widgets = availableWidgets[category];
                        $('li', categoryList).removeClass(self.settings.choosenClass);
                        $(this).addClass(self.settings.choosenClass);
                        showWidgetList(widgets, self);
                        createPreviewElement(self); // empty preview
                    });
                });

            };
        }
    });

    /**
     * Makes widgetPreview available with $().widgetPreview()
     */
    $.fn.extend({
        widgetPreview: $.widgetPreview.construct
    })
})(jQuery);