-
Notifications
You must be signed in to change notification settings - Fork 351
/
page-controller.js
419 lines (378 loc) · 15.1 KB
/
page-controller.js
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
define(function(require, exports, module) {
'use strict';
const $ = require('jquery');
const _ = require('underscore');
const Chaplin = require('chaplin');
const __ = require('orotranslation/js/translator');
const BaseController = require('oroui/js/app/controllers/base/controller');
const PageModel = require('oroui/js/app/models/page-model');
const errorHandler = require('oroui/js/error');
const tools = require('oroui/js/tools');
let config = require('module-config').default(module.id);
const document = window.document;
const location = window.location;
const history = window.history;
const utils = Chaplin.utils;
const mediator = Chaplin.mediator;
config = _.extend({
fullRedirect: false
}, config);
const PageController = BaseController.extend({});
_.extend(PageController.prototype, {
fullRedirect: config.fullRedirect,
/**
* Creates page model
* @override
*/
initialize: function(...args) {
PageController.__super__.initialize.apply(this, args);
const page = new PageModel();
this.listenTo(page, 'request', this.onPageRequest);
this.listenTo(page, 'sync', this.onPageLoaded);
this.listenTo(page, 'invalid', this.onPageInvalid);
this.listenTo(page, 'error', this.onPageError);
this.model = page;
// application is in action till first 'page:afterChange' event
let isInAction = true;
this.subscribeEvent('page:beforeChange', function() {
isInAction = true;
});
this.subscribeEvent('page:afterChange', function() {
isInAction = false;
});
mediator.setHandler('isInAction', function() {
return isInAction;
});
this._setNavigationHandlers();
},
/**
* Disposes page components
* @override
*/
dispose: function() {
if (this.disposed) {
return;
}
PageController.__super__.dispose.call(this);
},
/**
* Main action point
* - does background work before page loading
* - fetches page data from server
*
* @param {Object} params
* @param {Object} route
* @param {Object} options
*/
index: function(params, route, options) {
const url = this._combineRouteUrl(route);
const args = {// collect arguments to reuse in events of page_fetch state change
params: params,
route: route,
options: options
};
if (!route.previous) {
// page just loaded from server, does not require extra request
this.onPageLoaded(this.model, {}, {actionArgs: args});
return;
}
if (!this._beforePageLoad(route, params, options)) {
// prevent page loading, if there's redirect found
return;
}
delete options.redirection;
const cacheItem = this.cache.get(route.path);
if (cacheItem && cacheItem.page && route.query === cacheItem.query && options.force !== true) {
options.fromCache = true;
this.onPageRequest(this.model, null, {actionArgs: args});
this.model.set(cacheItem.page, {actionArgs: args});
// manually call onPageLoaded() since there is no 'sync' event triggered
this.onPageLoaded(this.model, {}, {actionArgs: args});
} else {
this.model.fetch({
url: url,
validate: true,
actionArgs: args
});
}
},
/**
* Does preparation for page loading
* - adds event listeners on page model
* - triggers 'page:beforeChange' event with two parameters oldRoute and newRoute
* - handle route change, if it has place to be
*
* @param {Object} route
* @param {Object} params
* @param {Object} options
* @returns {boolean}
* @private
*/
_beforePageLoad: function(route, params, options) {
let url;
let opts;
const oldRoute = route.previous;
const newRoute = _.extend(_.omit(route, ['previous']), {params: params});
this.publishEvent('page:beforeChange', oldRoute, newRoute, options);
// if route has been changed during 'page:beforeChange' event,
// redirect to a new URL and stop processing current
if (route.path !== newRoute.path || route.query !== newRoute.query) {
url = this._combineRouteUrl(newRoute);
opts = _.pick(options, ['forceStartup', 'changeURL', 'force', 'silent']);
opts.replace = true;
_.defer(function() {
mediator.execute('redirectTo', {url: url}, opts);
});
return false;
}
return true;
},
/**
* Handles page request
* - triggers 'page:request' event
*
* @param {Chaplin.Model} model
* @param {XMLHttpRequest} jqXHR
* @param {Object} options
*/
onPageRequest: function(model, jqXHR, options) {
this.publishEvent('page:request', options.actionArgs);
},
/**
* Handles page request done
* - triggers 'page:update' event with
* - updates page title
*
* @param {Chaplin.Model} model
* @param {Object} result
* @param {Object} options
*/
onPageLoaded: function(model, result, options) {
const self = this;
const updatePromises = [];
const pageData = model.getAttributes();
const actionArgs = options.actionArgs;
const jqXHR = options.xhr;
if (pageData.title) {
this.adjustTitle(pageData.title);
}
this.publishEvent('page:update', pageData, actionArgs, jqXHR, updatePromises);
// execute callback function when all promises are either resolved or rejected
function waitPromises(promises, callback) {
$.when(...promises).always(function() {
const pendingPromises = _.filter(promises, function(promise) {
return promise.state() === 'pending';
});
if (pendingPromises.length) {
waitPromises(pendingPromises, callback);
} else {
callback();
}
}).catch(function(error) {
if (error) {
errorHandler.showError(error);
}
});
}
// once all views has been updated, trigger page:afterChange
waitPromises(updatePromises, function() {
self.publishEvent('page:afterChange');
});
},
/**
* Handles invalid page load
* - process redirect of it was found
*
* @param {Chaplin.Model} model
* @param {*} error
* @param {Object} options
*/
onPageInvalid: function(model, error, options) {
let pathDesc;
let redirectOptions;
if (error.redirect) {
pathDesc = {url: error.location};
redirectOptions = _.extend(
{replace: true},
options.actionArgs.options,
_.pick(error, ['redirect', 'fullRedirect'])
);
this._processRedirect(pathDesc, redirectOptions);
}
},
/**
* Handles page loading error
* - tries to parse raw data and keep updating page
*
* @param {Chaplin.Model} model
* @param {XMLHttpRequest} jqXHR
* @param {Object} options
*/
onPageError: function(model, jqXHR, options) {
const rawData = jqXHR.responseText;
let data = {};
if (jqXHR.status === 200 && rawData.indexOf('http') === 0) {
data = {redirect: true, fullRedirect: true, location: rawData};
model.set(data, options);
return;
}
const payload = {stopPageProcessing: false};
this.publishEvent('page:beforeError', jqXHR, payload);
if (payload.stopPageProcessing) {
history.back();
return;
}
data = this._parseRawData(rawData);
if (_.isObject(data)) {
model.set(data, options);
} else {
errorHandler.showError(new Error(__('oro.ui.error.unexpected')));
}
this.publishEvent('page:error', model.getAttributes(), options.actionArgs, jqXHR);
this.publishEvent('page:afterChange');
},
/**
* Process redirect response
* see documentation for Chaplin.utils.redirectTo() method
*
* @param {Object|string} pathDesc
* @param {Object=} params
* @param {Object=} options
* @private
*/
_processRedirect: function(pathDesc, params, options) {
let parser;
let pathname;
let query;
const getUrl = function(pathname, query) {
query = utils.queryParams.parse(query);
query._rand = Math.random();
query = utils.queryParams.stringify(query);
return pathname + (query && ('?' + query));
};
options = options || {};
if (typeof pathDesc === 'object' && pathDesc.url !== null && pathDesc.url !== void 0) {
options = params || {};
// Redirect to absolute URL if presented
if (/^[\w]+:\/\//.test(pathDesc.url) && pathDesc.url.match(location.origin) === null) {
if (options.target === '_blank') {
window.open(pathDesc.url, '_blank');
return;
}
location[options.replace ? 'replace' : 'assign'](pathDesc.url);
return;
}
// fetch from URL only pathname and query
parser = document.createElement('a');
parser.href = pathDesc.url;
// IE removes starting slash
pathname = (parser.pathname[0] === '/' ? '' : '/') + parser.pathname;
query = parser.search.substr(1);
pathDesc.url = pathname + (query && ('?' + query));
}
options = _.defaults(options, {
fullRedirect: this.fullRedirect
});
if (options.target === '_blank') {
// Solution with `window.open(getUrl(pathname, query), '_blank');` does not work in iOS Safari
tools.windowOpen(getUrl(pathname, query), '_blank');
return;
}
if (options.fullRedirect) {
location[options.replace ? 'replace' : 'assign'](getUrl(pathname, query));
return;
}
if (options.redirect) {
_.extend(options, {forceStartup: true, force: true, redirection: true});
this.publishEvent('page:redirect', pathDesc, options);
utils.redirectTo(pathDesc, options);
return;
}
utils.redirectTo(pathDesc, params, options);
},
/**
* Register handler for page reload and redirect
*
* @private
*/
_setNavigationHandlers: function() {
mediator.setHandler('redirectTo', function(pathDesc, params, options) {
const queue = [];
mediator.trigger('page:beforeRedirectTo', queue, pathDesc, params, options);
return $.when(...queue).done(() => {
this._processRedirect(pathDesc, params, options);
});
}, this);
mediator.setHandler('refreshPage', function(options) {
const queue = [];
mediator.trigger('page:beforeRefresh', queue);
options = options || {};
_.defaults(options, {forceStartup: true, force: true});
return $.when(...queue).done(customOptions => {
_.extend(options, customOptions || {});
this._processRedirect({url: location.href}, options);
mediator.trigger('page:afterRefresh');
});
}, this);
mediator.setHandler('submitPage', this._submitPage, this);
},
/**
* Make data more bulletproof.
*
* @param {string} rawData
* @param {number=} prevPos
* @returns {Object}
*/
_parseRawData: function(rawData, prevPos) {
if (_.isUndefined(prevPos)) {
prevPos = -1;
}
rawData = rawData.trim();
const jsonStartPos = rawData.indexOf('{', prevPos + 1);
let additionalData = '';
let dataObj = null;
let data;
if (jsonStartPos > 0) {
additionalData = rawData.substr(0, jsonStartPos);
data = rawData.substr(jsonStartPos);
try {
dataObj = JSON.parse(data);
} catch (err) {
return this._parseRawData(rawData, jsonStartPos);
}
} else if (jsonStartPos === 0) {
dataObj = JSON.parse(rawData);
} else {
// there's nothing to do
dataObj = rawData;
}
if (additionalData) {
additionalData = '<div class="alert alert-info fade in top-messages alert-dismissible " role="alert">' +
'<button type="button" class="close" ' +
'data-dismiss="alert" aria-label="' + _.escape(__('Close')) + '">' +
'<span aria-hidden="true">×</span>' +
'</button>' +
'<div class="message">' + additionalData + '</div>' +
'</div>';
}
if (dataObj.content !== undefined) {
dataObj.content = additionalData + dataObj.content;
}
return dataObj;
},
/**
* Performs save call for a model
* (is used for saving forms, all data should be already packet into options)
*
* @param options
* @private
*/
_submitPage: function(options) {
this.publishEvent('page:beforeChange');
options.actionArgs = options.actionArgs || {};
_.defaults(options.actionArgs, {params: {}, route: {}, options: {}});
this.model.save(null, options);
}
});
return PageController;
});