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

widgetloader.directive.js « widget-loader « angularjs « CoreHome « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b1c0c3a11d2f48a70eecbe09164a381d15e907bc (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
/*!
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

/**
 * Loads any custom widget or URL based on the given parameters.
 *
 * The currently active idSite, period, date and segment (if needed) is automatically appended to the parameters. If
 * this widget is removed from the DOM and requests are in progress, these requests will be aborted. A loading message
 * or an error message on failure is shown as well. It's kinda similar to ng-include but there it is not possible to
 * listen to HTTP errors etc.
 *
 * Example:
 * <div piwik-widget-loader="{module: '', action: '', ...}"></div>
 */
(function () {
    angular.module('piwikApp').directive('piwikWidgetLoader', piwikWidgetLoader);

    piwikWidgetLoader.$inject = ['piwik', 'piwikUrl', '$http', '$compile', '$q', '$location', 'notifications', '$rootScope', '$timeout', 'piwikComparisonsService'];

    function piwikWidgetLoader(piwik, piwikUrl, $http, $compile, $q, $location, notifications, $rootScope, $timeout, piwikComparisonsService){
        return {
            restrict: 'A',
            transclude: true,
            scope: {
                piwikWidgetLoader: '=',
                widgetName: '@',
                loadingMessage: '@'
            },
            templateUrl: 'plugins/CoreHome/angularjs/widget-loader/widgetloader.directive.html?cb=' + piwik.cacheBuster,
            compile: function (element, attrs) {

                return function (scope, element, attrs, ngModel) {
                    scope.widgetName = attrs.widgetName;

                    if (!attrs.widgetName) {
                        scope.loadingMessage = _pk_translate('General_LoadingData');
                    } else {
                        scope.loadingMessage = _pk_translate('General_LoadingPopover', [attrs.widgetName]);
                    }

                    var changeCounter = 0,
                        currentScope,
                        currentElement,
                        httpCanceler,
                        contentNode = element.find('.theWidgetContent');

                    var cleanupLastWidgetContent = function() {
                        if (currentElement) {
                            currentElement.remove();
                            currentElement = null;
                        }
                        if (currentScope) {
                            currentScope.$destroy();
                            currentScope = null;
                        }
                    };

                    var abortHttpRequestIfNeeded = function () {
                        if (httpCanceler) {
                            httpCanceler.resolve();
                            httpCanceler = null;
                        }
                    }

                    function getFullWidgetUrl(parameters) {

                        var url = $.param(parameters);

                        var $urlParams = $location.search();

                        delete $urlParams['comparePeriods[]'];
                        delete $urlParams['compareDates[]'];
                        delete $urlParams['compareSegments[]'];

                        if ($.isEmptyObject($urlParams) || !$urlParams || !$urlParams['idSite']) {
                            // happens eg in exported widget etc when URL does not have #?...
                            $urlParams = {idSite: 'idSite', period: 'period',date: 'date'};
                            if (piwikUrl.getSearchParam('widget')) {
                                $urlParams['widget'] = 'widget';
                            }
                        } else {
                            $urlParams = angular.copy($urlParams);
                            delete $urlParams['category'];
                            delete $urlParams['subcategory'];
                        }

                        if (piwikUrl.getSearchParam('segment')) {
                            $urlParams['segment'] = 'segment';
                        }

                        angular.forEach($urlParams, function (value, key) {
                            if (!(key in parameters)) {
                                url += '&' + key + '=' + piwikUrl.getSearchParam(key);
                            }
                        });

                        if (piwikComparisonsService.isComparisonEnabled()) {
                            ['comparePeriods', 'compareDates', 'compareSegments'].forEach(function (paramName) {
                                var value = piwikUrl.getSearchParam(paramName);
                                if (value) {
                                    var map = {};
                                    map[paramName] = value;
                                    url += '&' + $.param(map);
                                }
                            });
                        }

                        if (!parameters || !('showtitle' in parameters)) {
                            url += '&showtitle=1';
                        }

                        if (piwik.shouldPropagateTokenAuth && broadcast.getValueFromUrl('token_auth')) {
                            url += '&force_api_session=1&token_auth=' + broadcast.getValueFromUrl('token_auth');
                        }

                        url += '&random=' + parseInt(Math.random() * 10000);

                        return '?' + url;
                    }

                    function loadWidgetUrl(parameters, thisChangeId)
                    {
                        scope.loading = true;

                        var url = getFullWidgetUrl(parameters);

                        abortHttpRequestIfNeeded();
                        cleanupLastWidgetContent();

                        httpCanceler = $q.defer();

                        $http.get(url, {timeout: httpCanceler.promise, headers: {'X-Requested-With': 'XMLHttpRequest'}}).then(function(response) {
                            if (thisChangeId !== changeCounter || !response.data) {
                                // another widget was requested meanwhile, ignore this response
                                return;
                            }

                            httpCanceler = null;

                            var newScope = scope.$new();
                            currentScope = newScope;

                            scope.loading = false;
                            scope.loadingFailed = false;

                            currentElement = contentNode.html(response.data).children();

                            if (scope.widgetName) {
                                // we need to respect the widget title, which overwrites a possibly set report title
                                var $title = currentElement.find('> .card-content .card-title');
                                if (!$title.length) {
                                    $title = currentElement.find('> h2');
                                }

                                if ($title.length) {
                                    $title.html(piwik.helper.htmlEntities(scope.widgetName));
                                }
                            }

                            $compile(currentElement)(newScope);

                            notifications.parseNotificationDivs();

                            $timeout(function () {
                                $rootScope.$emit('widget:loaded', {
                                    parameters: parameters,
                                    element: currentElement,
                                });
                            });
                        })['catch'](function (response) {
                            if (thisChangeId !== changeCounter) {
                                // another widget was requested meanwhile, ignore this response
                                return;
                            }

                            httpCanceler = null;

                            cleanupLastWidgetContent();

                            scope.loading = false;

                            if (response.xhrStatus === 'abort') {
                                return;
                            };

                            scope.loadingFailed = true;
                        });
                    }

                    scope.$watch('piwikWidgetLoader', function (parameters, oldUrl) {
                        if (parameters) {
                            loadWidgetUrl(parameters, ++changeCounter);
                        }
                    });

                    element.on('$destroy', function() {
                        abortHttpRequestIfNeeded();
                    });
                };
            }
        };
    }
})();