-
Notifications
You must be signed in to change notification settings - Fork 1
/
crf7.js
404 lines (362 loc) · 12 KB
/
crf7.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
var riot = require('riot'),
async = require('async'),
$ = require('Dom7'),
fm7 = require('./fm7'),
utils = require('./utils');
/**
* Server response messages
*/
class Messages {
constructor(messages) {
this.numErrors = 0;
if (messages == null) {
messages = [];
}
if (Array.isArray(messages)) {
this.messages = [].concat(messages);
} else if (messages.msg != null) {
this.messages = [{
msg: messages.msg,
error: !!messages.error
}];
} else {
throw new Error('Invalid argument specified: ' + messages);
}
for (var i = 0; i < messages.length; ++i) {
if (messages[i].error) {
this.numErrors++;
break;
}
}
}
get length() {
return this.messages.length;
}
get hasErrors() {
return (this.numErrors > 0);
}
report() {
if (this.length > 0) {
//todo use gui?
console.error(this.messages);
}
}
toString() {
var out = [];
out.push('Messages{');
this.messages.forEach((m) => {
out.push('\t' + (m.error ? '! ' : '* ') + m.msg);
});
out.push('}');
return out.join('\n');
}
}
/**
* Main application object.
*
* Events:
*
* `init` - application initialization started
* `root` - root tag mounted
*
*/
class App {
constructor(opts, sysopts) {
window.app = this;
riot.observable(this);
this.preroutes = [];
this.opts = new utils.Options(opts);
this.sysopts = sysopts = sysopts || {};
if (sysopts['messagesReportConsole'] == null) {
sysopts['messagesReportConsole'] = true;
}
if (sysopts['messagesReportGUI'] == null) {
sysopts['messagesReportGUI'] = false;
}
this.mainView = sysopts['mainView'] || 'view-main';
this.xhdrPrefix = sysopts['xhdrPrefix'] || 'X-App';
this._preloaders = 0;
$(document).on('deviceready', () => {
this.init();
}, false);
$(document).on('backbutton', (e) => {
this.onBack();
e.preventDefault();
}, false);
this.one('init', () => {
this.ready = true;
})
}
onBack() {
var me = this;
var view = this.fm7.getCurrentView();
if (view) {
var i = 0;
var modals = [
'.modal.modal-in:not(.modal-out)',
'.login-screen.modal-in:not(.modal-out)',
'.picker-modal.modal-in:not(.modal-out)',
'.popover.modal-in:not(.modal-out)'
];
for (i = 0; i < modals.length && !tryCloseModal(modals[i]); ++i);
function tryCloseModal(m) {
var modal = $(m);
if (modal.length && modal[0].offsetParent != null) {
me.fm7.closeModal(m);
return true;
}
return false;
}
}
return false;
}
checks() {
if (!window.device) {
throw new Error('Seems to be not a Cordova environment');
}
console.log('Device platform: ' + window.device.platform);
if (!window.FormData) {
throw new Error('Missing window.FormData object');
}
this.isAndroid = (window.device.platform === 'Android');
this.isBrowser = (window.device.platform === 'browser');
this.isIOS = (window.device.platform === 'iOS');
}
reportError(err, action) {
if ((typeof action === 'string') && action.length > 0) {
action = action.charAt(0).toLocaleLowerCase() + action.substring(1);
}
if (this.opts.get('errors.hide')) {
err = null;
}
if (err != null && typeof err === 'object' && 'messages' in err) {
err = err['messages'];
}
if (err instanceof Messages) {
if (this.sysopts['messagesReportConsole']) {
console.warn(err.toString());
}
if (this.messagesTag && this.sysopts['messagesReportGUI']) {
this.messages = err;
this.messagesTag.update();
this.popup('#messages');
}
} else {
console.error(`Application error: ${err}\nAction: ${action}`);
this.alert(`Произошла ошибка${err ? ': ' + err + '.' : '.'} Пожалуйста,
повторите действие еще раз.`, `Ошибка${action ? ': ' + action : '!'}`);
}
}
showPreloader(title) {
if (this._preloaders == 0) {
this._preloaders++;
return this.fm7.showPreloader(title);
}
}
hidePreloader() {
if (this._preloaders > 0) {
this._preloaders = 0;
return this.fm7.hidePreloader();
}
}
alert(text, title, callbackOk) {
return this.fm7.alert(text, title, callbackOk);
};
confirm(text, title, callbackOk, callbackCancel) {
return this.fm7.confirm(text, title, callbackOk, callbackCancel);
}
loginScreen() {
return this.fm7.loginScreen();
}
closeLoginScreen() {
return this.fm7.closeLoginScreen();
}
popup(selector = '.popup', removeOnClose = true) {
return this.fm7.popup(selector, removeOnClose);
}
pickerModal(selector, removeOnClose = true) {
return this.fm7.pickerModal(selector, removeOnClose);
}
loadTagPage(tagName) {
return this.router.loadPage(tagName);
}
get router() {
var view = this.fm7.getCurrentView();
if (view) {
return view.router;
} else {
throw new Error('No current view is set');
}
}
clearHistory() {
var view = this.fm7.getCurrentView();
if (view) {
//todo
}
}
createMessages(src) {
return new Messages(src);
}
translate(msg) {
return msg;
}
translateOrNull(msg) {
return this.translateOrDefault(msg, null);
}
translateOrDefault(msg, def) {
var ret = this.translate(msg);
return ret === msg ? def : ret;
}
/**
* Perform GET AJAX request.
* @param {?string} url Resource URL
* @param {!object} options Extra request options
* @returns {Promise}
*/
ajaxGET(url, options) {
options = Object.assign({}, options);
options.url = url;
return this.ajax(options);
}
/**
* Perform AJAX request.
* @param options Ajax request options
* @returns {Promise}
*/
ajax(options) {
console.log('AJAX: ' + options.url);
if (!options.url) {
throw new Error('Ajax options must contain "url" parameter');
}
var app = this;
return new Promise(function (resolve, reject) {
var user = options.user, password = options.password,
reportMessages = !!options.reportMessages;
if (user != null) {
delete options.user;
delete options.password;
var headers = options.headers = options.headers || {};
headers['Authorization'] = 'Basic ' + btoa(user + ':' + password);
}
options.success = function (data, status, xhr) {
var messages = checkResponse(xhr);
if (reportMessages) {
messages.report();
}
if (messages.numErrors) {
reject({messages, xhr});
} else {
resolve({
data,
messages,
status,
xhr
});
}
};
options.error = function (xhr, status) {
var messages = checkResponse(xhr, status, true);
if (reportMessages) {
messages.report();
}
reject({messages, xhr});
};
function checkResponse(xhr, status, err) {
var c, mh, messages = [];
try {
if (xhr.getResponseHeader(app.xhdrPrefix + '-Login') != null) {
if (app.crm.currentSession) {
app.crm.currentSession.destroy();
//todo review
messages.push({
msg: 'User not logged',
error: true
});
return new Messages(messages);
}
}
for (c = 0; (mh = xhr.getResponseHeader(app.xhdrPrefix + '-Err' + c)) != null; ++c) {
messages.push({
msg: decodeURIComponent(mh.replace(/\+/g, ' ')),
error: true
});
}
for (c = 0; (mh = xhr.getResponseHeader(app.xhdrPrefix + '-Msg' + c)) != null; ++c) {
messages.push({
msg: decodeURIComponent(mh.replace(/\+/g, ' ')),
error: false
});
}
if (!messages.length && status && status >= 400 && status !== 404) {
messages.push({
msg: xhr.statusText || ("" + status),
error: true
})
}
} catch (e) {
console.error(e);
}
if (err && messages.length == 0) {
messages.push({
msg: app.translateOrDefault('fm7.ajax.connection.fail', 'Connection fail'),
error: true
})
}
return new Messages(messages);
}
$.ajax(options);
});
}
wa(action, promise) {
this.showPreloader(action);
return promise.catch((err) => {
this.reportError(err, action);
return err;
}).finally(() => {
this.hidePreloader();
});
}
init() {
var app = this;
this.checks();
// Riot tags mixins
riot.mixin('AppTag', function () {
this.init = function () {
app.initAppTagMixin(this);
}
});
// F7 initialization
(function () {
app.fm7 = fm7.application(riot,
Object.assign({
fastClicks: true,
modalTitle: app.translateOrNull('fm7.modal.title'),
modalPreloaderTitle: app.translateOrNull('fm7.modal.preloader.title'),
smartSelectPickerCloseText: app.translateOrNull('fm7.smartselect.picker.close'),
smartSelectPopupCloseText: app.translateOrNull('fm7.smartselect.popup.close'),
modalButtonOk: app.translateOrNull('fm7.modal.ok'),
modalButtonCancel: app.translateOrNull('fm7.modal.cancel'),
smartSelectOpenIn: 'picker',
preroute(view, options, cb) {
console.log('PREROUTE LOAD: ' + JSON.stringify(options));
async.applyEachSeries(app.preroutes, view, options, cb);
}
}, app.sysopts['fm7'])
);
app.fm7.addViewTag(app.mainView);
})();
if (!this.messagesTag) {
this.messagesTag = riot.mount('messages')[0];
}
}
initAppTagMixin(mixin) {
mixin.app = app;
mixin.tr = (msg) => {
return this.translate(msg);
};
}
}
module.exports = {
Messages,
App
};