summaryrefslogtreecommitdiffstats
path: root/public/js/icinga/history.js
blob: 150be7ca3e7b60cfd7ed0bf8967ab5dc90b81531 (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
/*! Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

/**
 * Icinga.History
 *
 * This is where we care about the browser History API
 */
(function (Icinga, $) {

    'use strict';

    Icinga.History = function (icinga) {

        /**
         * YES, we need Icinga
         */
        this.icinga = icinga;

        /**
         * Our base url
         */
        this.baseUrl = icinga.config.baseUrl;

        /**
         * Initial URL at load time
         */
        this.initialUrl = location.href;

        /**
         * Whether the History API is enabled
         */
        this.enabled = false;
    };

    Icinga.History.prototype = {

        /**
         * Icinga will call our initialize() function once it's ready
         */
        initialize: function () {

            // History API will not be enabled without browser support, no fallback
            if ('undefined' !== typeof window.history  &&
                typeof window.history.pushState === 'function'
            ) {
                this.enabled = true;
                this.icinga.logger.debug('History API enabled');
                this.applyLocationBar(true);
                $(window).on('popstate', { self: this }, this.onHistoryChange);
            }

        },

        /**
         * Get the current state (url and title) as object
         *
         * @returns {object}
         */
        getCurrentState: function () {
            if (! this.enabled) {
                return null;
            }

            var title = null;
            var url = null;

            // We only store URLs of containers sitting directly under #main:
            $('#main > .container').each(function (idx, container) {
                var $container = $(container),
                    cUrl = $container.data('icingaUrl'),
                    cTitle = $container.data('icingaTitle');

                // TODO: I'd prefer to have the rightmost URL first
                if ('undefined' !== typeof cUrl) {
                    // TODO: solve this on server side cUrl = icinga.utils.removeUrlParams(cUrl, blacklist);
                    if (! url) {
                        url = cUrl;
                    } else {
                        url = url + '#!' + cUrl;
                    }
                }

                if (typeof cTitle !== 'undefined') {
                    title = cTitle; // Only uses the rightmost title
                }
            });

            return {
                title: title,
                url: url,
            };
        },

        /**
         * Detect active URLs and push combined URL to history
         *
         * TODO: How should we handle POST requests? e.g. search VS login
         */
        pushCurrentState: function () {
            // No history API, no action
            if (! this.enabled) {
                return;
            }

            var state = this.getCurrentState();

            // Did we find any URL? Then push it!
            if (state.url) {
                this.icinga.logger.debug('Pushing current state to history');
                this.push(state.url);
            }
            if (state.title) {
                this.icinga.ui.setTitle(state.title);
            }
        },

        /**
         * Replace the current history entry with the current state
         */
        replaceCurrentState: function () {
            if (! this.enabled) {
                return;
            }

            var state = this.getCurrentState();

            if (state.url) {
                this.icinga.logger.debug('Replacing current history state');
                this.lastPushUrl = state.url;
                window.history.replaceState(
                    this.getBehaviorState(),
                    null,
                    state.url
                );
            }
        },

        /**
         * Push the given url as the new history state, unless the history is disabled
         *
         * @param   {string}    url     The full url path, including anchor
         */
        pushUrl: function (url) {
            // No history API, no action
            if (!this.enabled) {
                return;
            }
            this.push(url);
        },

        /**
         * Execute the history state, preserving the current state of behaviors
         *
         * Used internally by the history and should not be called externally, instead use {@link pushUrl}.
         *
         * @param   {string}    url
         */
        push: function (url) {
            url = url.replace(/[\?&]?_(render|reload)=[a-z0-9]+/g, '');
            if (this.lastPushUrl === url) {
                this.icinga.logger.debug(
                    'Ignoring history state push for url ' + url + ' as it\' currently on top of the stack'
                );
                return;
            }
            this.lastPushUrl = url;
            window.history.pushState(
                this.getBehaviorState(),
                null,
                url
            );
        },

        /**
         * Fetch the current state of all JS behaviors that need history support
         *
         * @return {Object} A key-value map, mapping behavior names to state
         */
        getBehaviorState: function () {
            var data = {};
            $.each(this.icinga.behaviors, function (i, behavior) {
                if (behavior.onPushState instanceof Function) {
                    data[i] = behavior.onPushState();
                }
            });
            return data;
        },

        /**
         * Event handler for pop events
         *
         * TODO: Fix active selection, multiple cols
         */
        onHistoryChange: function (event) {

            var _this   = event.data.self,
                icinga = _this.icinga;

            icinga.logger.debug('Got a history change');

            // We might find browsers showing strange behaviour, this log could help
            if (event.originalEvent.state === null) {
                icinga.logger.debug('No more history steps available');
            } else {
                icinga.logger.debug('History state', event.originalEvent.state);
            }

            // keep the last pushed url in sync with history changes
            _this.lastPushUrl = location.href;

            _this.applyLocationBar();

            // notify behaviors of the state change
            $.each(this.icinga.behaviors, function (i, behavior) {
                if (behavior.onPopState instanceof Function && history.state) {
                    behavior.onPopState(location.href, history.state[i]);
                }
            });
        },

        /**
         * Update the application containers to match the current url
         *
         * Read the pane url from the current URL and load the corresponding panes into containers to
         * match the current history state.
         *
         * @param   {Boolean}  onload  Set to true when the main pane should not be updated, defaults to false
         */
        applyLocationBar: function (onload = false) {
            let col2State = this.getCol2State();

            if (onload && document.querySelector('#layout > #login')) {
                // The user landed on the login
                let redirectInput = document.querySelector('#login form input[name=redirect]');
                redirectInput.value = redirectInput.value + col2State;
                return;
            }

            let col1 = document.getElementById('col1'),
                col2 = document.getElementById('col2'),
                col1Url = document.location.pathname + document.location.search;

            let col2Url;
            if (col2State && col2State.match(/^#!/)) {
                col2Url = col2State.split(/#!/)[1];
            }

            // This uses jQuery only because of its internal data attribute cache -.-
            let currentCol1Url = $(col1).data('icingaUrl'),
                currentCol2Url = $(col2).data('icingaUrl');

            let loadCol1 = ! onload,
                loadCol2 = !! col2Url;
            if (currentCol2Url === col1Url) {
                // User navigated forward
                this.icinga.ui.moveToLeft();
                loadCol1 = false;
            } else if (currentCol1Url === col2Url) {
                // User navigated back
                this.icinga.ui.moveToRight();
                loadCol2 = false;
            }

            if (loadCol1 && currentCol1Url !== col1Url) {
                let anchor = this.getPaneAnchor(0);
                if (anchor) {
                    col1Url += '#' + anchor;
                }

                this.icinga.loader.loadUrl(col1Url, $(col1)).addToHistory = false;
            }

            if (loadCol2 && currentCol2Url !== col2Url) {
                let col2Req = this.icinga.loader.loadUrl(col2Url, $(col2));
                col2Req.addToHistory = false;
                col2Req.scripted = onload;

                this.icinga.ui.layout2col();
            } else if (! loadCol2 && ! col2Url) {
                this.icinga.ui.layout1col();
            }
        },

        /**
         * Get the state of the selected pane
         *
         * @param   col {int}       The column index 0 or 1
         *
         * @returns     {String}    The string representing the state
         */
        getPaneAnchor: function (col) {
            if (col !== 1 && col !== 0) {
                throw 'Trying to get anchor for non-existing column: ' + col;
            }
            var panes = document.location.toString().split('#!')[col];
            return panes && panes.split('#')[1] || '';
        },

        /**
         * Get the side pane state after (and including) the #!
         *
         * @returns {string}    The pane url
         */
        getCol2State: function () {
            var hash = document.location.hash;
            if (hash) {
                if (hash.match(/^#[^!]/)) {
                    var hashs = hash.split('#');
                    hashs.shift();
                    hashs.shift();
                    hash = '#' + hashs.join('#');
                }
            }
            return hash || '';
        },

        /**
         * Return the main pane state fragment
         *
         * @returns {string}    The main url including anchors, without #!
         */
        getCol1State: function () {
            var anchor = this.getPaneAnchor(0);
            var hash = window.location.pathname + window.location.search +
                (anchor.length ? ('#' + anchor) : '');
            return hash || '';
        },

        /**
         * Cleanup
         */
        destroy: function () {
            $(window).off('popstate', this.onHistoryChange);
            this.icinga = null;
        }
    };

}(Icinga, jQuery));