/
app.js
1827 lines (1688 loc) 路 54.7 KB
/
app.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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* wq.app 1.1.1 - wq/app.js
* Utilizes store and pages to dynamically load and render
* content from a wq.db-compatible REST service
* (c) 2012-2019, S. Andrew Sheppard
* https://wq.io/license
*/
define(['jquery', 'jquery.mobile',
'./store', './model', './outbox', './router', './template',
'./spinner', './console'],
function($, jqm, ds, model, outbox, router, tmpl, spin, console) {
var app = {
'OFFLINE': 'offline',
'FAILURE': 'failure',
'ERROR': 'error'
};
app.models = {};
app.plugins = {};
var _saveTransition = "none",
_register = {},
_onShow = {};
app.init = function(config) {
// Router (wq/router.js) configuration
if (!config.router) {
config.router = {
'base_url': ''
};
}
// Store (wq/store.js) configuration
if (!config.store) {
config.store = {
'service': config.router.base_url,
'defaults': {'format': 'json'}
};
}
if (!config.store.fetchFail) {
config.fetchFail = _fetchFail;
}
for (var plugin in app.plugins) {
if (app.plugins[plugin].ajax) {
config.store.ajax = app.plugins[plugin].ajax;
}
}
// Outbox (wq/outbox.js) configuration
if (!config.outbox) {
config.outbox = {};
}
if (!config.outbox.updateModels) {
config.outbox.updateModels = _updateModels;
}
// Propagate debug setting to other modules
if (config.debug) {
config.router.debug = config.debug;
config.store.debug = config.debug;
config.template.debug = config.debug;
}
// Load missing (non-local) content as JSON, or as server-rendered HTML?
// Default (as of 1.0) is to load JSON and render on client.
config.loadMissingAsJson = (
config.loadMissingAsJson || !config.loadMissingAsHtml
);
config.loadMissingAsHtml = !config.loadMissingAsJson;
// After a form submission, sync in the background, or wait before
// continuing? Default is to sync in the background.
config.backgroundSync = (
config.backgroundSync || !config.noBackgroundSync
);
config.noBackgroundSync = !config.backgroundSync;
app.config = config;
app.wq_config = config;
app['native'] = !!window.cordova;
app.can_login = !!config.pages.login;
// Initialize wq/store.js
ds.init(config.store);
app.service = ds.service;
// Initialize wq/outbox.js
outbox.init(config.outbox);
// Initialize wq/router.js
router.init(config.router);
app.base_url = router.info.base_url;
// Initialize wq/template.js
tmpl.init(config.template);
tmpl.setDefault('native', app['native']);
tmpl.setDefault('app_config', app.config);
tmpl.setDefault('wq_config', app.wq_config);
tmpl.setDefault('svc', app.service);
// Option to submit forms in the background rather than wait for each post
var seconds;
if (config.backgroundSync) {
seconds = config.backgroundSync;
if (seconds === true) {
seconds = 30;
}
if (seconds > 0) {
app._syncInterval = setInterval(function() {
app.sync();
}, seconds * 1000);
}
}
// Option to override various hooks
[
'postsave',
'saveerror',
'showOutboxErrors',
'_addOutboxItemsToContext',
'presync',
'postsync'
].forEach(function(hook) {
if (config[hook]) {
app[hook] = config[hook];
}
});
// Initialize authentication, if applicable
var ready;
if (app.can_login) {
router.register('logout\/?', app.logout);
// Load some values from store - not ready till this is done.
ready = ds.get(['user', 'csrf_token']).then(function(values) {
var user = values[0];
var csrfReady = _setCSRFToken(values[1]);
if (!user) {
return csrfReady;
}
app.user = user;
tmpl.setDefault('user', user);
tmpl.setDefault('is_authenticated', true);
return ds.get('/config').then(function(wq_config) {
app.wq_config = wq_config;
tmpl.setDefault('wq_config', app.wq_config);
$('body').trigger('login');
return csrfReady;
});
});
ready = ready.then(_checkLogin);
} else {
ready = ds.ready;
}
ready = ready.then(function() {
return outbox.unsynced().then(function(unsynced) {
tmpl.setDefault('unsynced', unsynced);
});
});
// Configure jQuery Mobile transitions
if (config.transitions) {
var def = "default";
if (config.transitions[def]) {
jqm.defaultPageTransition = config.transitions[def];
}
if (config.transitions.dialog) {
jqm.defaultDialogTransition = config.transitions.dialog;
}
if (config.transitions.save) {
_saveTransition = config.transitions.save;
}
jqm.maxTransitionWidth = config.transitions.maxwidth || 800;
}
Object.keys(app.wq_config.pages).forEach(function(page) {
app.wq_config.pages[page].name = page;
});
_callPlugins('init', app.config);
// Register routes with wq/router.js
var root = false;
Object.keys(app.wq_config.pages).forEach(function(page) {
var conf = _getConf(page);
if (!conf.url) {
root = true;
}
if (conf.list) {
conf.modes.forEach(function(mode) {
var register = _register[mode] || _register.detail;
var onShow = _onShow[mode] || _onShow.detail;
register(page, mode);
onShow(page, mode);
});
(conf.server_modes || []).forEach(function(mode) {
var onShow = _onShow[mode] || _onShow.detail;
onShow(page, mode);
});
app.models[page] = model(conf);
} else if (conf) {
if (!conf.server_only) {
_registerOther(page);
}
_onShowOther(page);
}
});
// Register outbox
router.register('outbox', _renderOutboxList);
router.register('outbox/', _renderOutboxList);
router.addRoute('outbox', 's', _showOutboxList);
router.register('outbox/<slug>', _renderOutboxItem('detail'));
router.register('outbox/<slug>/edit', _renderOutboxItem('edit'));
router.addRoute('outbox/<slug>', 's', _showOutboxItem('detail'));
router.addRoute('outbox/<slug>/edit', 's', _showOutboxItem('edit'));
// Fallback index page
if (!root && !app.wq_config.pages.index &&
config.template.templates.index) {
router.register('', function(match, ui) {
var context = {};
context.pages = Object.keys(app.wq_config.pages).map(
function(page) {
var conf = app.wq_config.pages[page];
return {
'name': page,
'url': conf.url,
'list': conf.list
};
}
);
router.go('', 'index', context, ui);
});
}
// Handle form events
$(document).on('submit', 'form', _handleForm);
$(document).on('click', 'form [type=submit]', _submitClick);
if (app.config.jqmInit) {
ready = ready.then(app.jqmInit);
}
return ready;
};
var pcount = 0;
app.use = function(plugin) {
pcount++;
if (!plugin.name) {
plugin.name = 'plugin' + pcount;
}
app.plugins[plugin.name] = plugin;
plugin.app = app;
};
app.prefetchAll = function() {
return Promise.all(Object.keys(app.models).map(function(name) {
return app.models[name].prefetch();
}));
};
app.jqmInit = router.jqmInit;
app.logout = function() {
if (!app.can_login) {
return;
}
delete app.user;
tmpl.setDefault('user', null);
tmpl.setDefault('is_authenticated', false);
app.wq_config = app.config;
tmpl.setDefault('wq_config', app.wq_config);
ds.set('user', null).then(function() {
$('body').trigger('logout');
});
// Notify server (don't need to wait for this)
ds.fetch('/logout').then(function(result) {
_setCSRFToken(result.csrftoken);
});
};
// Determine appropriate context & template for router.go
app.go = function(page, ui, params, itemid, mode, url, context) {
if (ui && ui.options && ui.options.data) {
return; // Ignore form actions
}
var conf = _getConf(page);
if (!conf.list) {
_renderOther(page, ui, params, url, context);
return;
}
var model = app.models[page];
spin.start();
if (itemid) {
if (itemid == 'new') {
return _displayItem(
itemid, {}, page, ui, params, mode, url, context
);
} else {
var localOnly = !app.config.loadMissingAsJson;
return model.find(itemid, 'id', localOnly).then(function(item) {
_displayItem(
itemid, item, page, ui, params, mode, url, context
);
});
}
} else {
return _displayList(page, ui, params, url, context);
}
};
// Run any/all plugins on the specified page
app.runPlugins = function(page, mode, itemid, url, parentInfo) {
var lastRoute = router.info,
context = lastRoute.context,
routeInfo, getItem;
routeInfo = _getRouteInfo(
page, mode, itemid,
url.replace(app.base_url + '/', ''),
parentInfo
);
if (itemid) {
if (lastRoute.path == routeInfo.path && context &&
(context.id || 'new') == itemid) {
getItem = Promise.resolve(context);
if (context.outbox_id) {
routeInfo.outbox_id = context.outbox_id;
}
} else {
getItem = app.models[page].find(itemid);
}
} else {
getItem = Promise.resolve({});
}
getItem.then(function(item) {
routeInfo.item = item;
if (window.MSApp && window.MSApp.execUnsafeLocalFunction) {
window.MSApp.execUnsafeLocalFunction(function() {
_callPlugins('run', undefined, [jqm.activePage, routeInfo]);
});
} else {
_callPlugins('run', undefined, [jqm.activePage, routeInfo]);
}
});
};
// Sync outbox and handle result
app.sync = function(retryAll) {
if (app.syncing) {
return;
}
outbox.unsynced().then(function(unsynced) {
if (!unsynced) {
return;
}
app.syncing = true;
tmpl.setDefault('syncing', true);
app.presync();
outbox.sendAll(retryAll).then(function(items) {
app.syncing = false;
tmpl.setDefault('syncing', false);
app.postsync(items);
});
});
};
app.emptyOutbox = function(confirmFirst) {
/* global confirm */
if (confirmFirst) {
if (navigator.notification && navigator.notification.confirm) {
navigator.notification.confirm('Empty Outbox?', function(button) {
if (button == 1) {
app.emptyOutbox();
}
});
return;
} else {
if (!confirm('Empty Outbox?')) {
return;
}
}
}
return outbox.model.overwrite([]).then(function() {
app.syncRefresh([null]);
});
};
app.confirmSubmit = function(form, message) {
/* global confirm */
var $form;
if (navigator.notification && navigator.notification.confirm) {
$form = $(form);
if ($form.data('wq-confirm-submit')) {
return true;
}
navigator.notification.confirm(message, function(button) {
if (button == 1) {
$form.data('wq-confirm-submit', true);
$form.trigger('submit');
}
});
} else {
if (confirm(message)) {
return true;
}
}
return false;
};
// Hook for handling navigation after form submission
app.postsave = function(item, backgroundSync) {
var options = {
'reverse': true,
'transition': _saveTransition,
'allowSamePageTransition': true
};
var postsave, pconf, match, mode, url, itemid, modelConf;
// conf.postsave can be set redirect to another page
modelConf = item.options.modelConf;
if (item.deletedId) {
postsave = modelConf.postdelete;
} else {
postsave = modelConf.postsave;
}
if (!postsave) {
// Otherwise, default is to return the page for the item just saved
if (backgroundSync || item.deletedId) {
// If backgroundSync, return to list view while syncing
postsave = modelConf.name + '_list';
} else {
// If noBackgroundSync, return to the newly synced item
postsave = modelConf.name + '_detail';
}
}
// conf.postsave should explicitly indicate which template mode to use
match = postsave.match(/^([^\/]+)_([^_\/]+)$/);
if (match) {
postsave = match[1];
mode = match[2];
}
// Retrieve configuration for postsave page, if any
pconf = _getConf(postsave, true);
// Compute URL
if (!pconf) {
// If conf.postsave is not the name of a list page, assume it's a
// simple page or a URL
var urlContext;
if (item.deletedId) {
urlContext = $.extend({'deleted': true}, router.info.context);
} else {
urlContext = item.result || item.data;
}
url = app.base_url + '/' + tmpl.render(postsave, urlContext);
} else if (!pconf.list) {
url = app.base_url + '/' + pconf.url;
} else {
if (pconf.modes.indexOf(mode) == -1) {
throw "Unknown template mode!";
}
// For list pages, the url can differ depending on the mode
url = app.base_url + '/' + pconf.url + '/';
if (mode != 'list') {
// Detail or edit view; determine item id and add to url
if (postsave == modelConf.name && !item.synced) {
// Config indicates return to detail/edit view of the model
// that was just saved, but the item hasn't been synced yet.
// Navigate to outbox URL instead.
url = app.base_url + '/outbox/' + item.id;
if (mode != 'edit' && item.error) {
// Return to edit form if there was an error
mode = 'edit';
}
} else {
// Item has been successfully synced
if (postsave == modelConf.name) {
// If postsave page is the same as the item's page, use the
// new id
itemid = item.result && item.result.id;
} else {
// Otherwise, look for a foreign key reference
// FIXME: what if the foreign key has a different name?
itemid = item.result && item.result[postsave + '_id'];
}
if (!itemid) {
throw "Could not find " + postsave + " id in result!";
}
url += itemid;
}
if (mode != "detail") {
url += "/" + mode;
}
}
}
// Navigate to computed URL
if (app.config.debug) {
console.log("Successfully saved; continuing to " + url);
}
jqm.changePage(url, options);
};
// Hook for handling navigation / alerts after a submission error
// (only used when noBackgroundSync is set)
app.saveerror = function(item, reason, $form) {
/* jshint unused: false */
// Save failed for some reason, perhaps due to being offline
// (override to customize behavior, e.g. display an outbox)
if (app.config.debug) {
console.warn("Could not save: " + reason);
}
if (reason == app.OFFLINE) {
app.postsave(item, false);
} else {
app.showOutboxErrors(item, $form);
}
};
// Hook for handling alerts before a background sync event
// (only used when backgroundSync is set)
app.presync = function() {
if (app.config.debug) {
console.log("Syncing...");
}
};
// Hook for handling alerts after a background sync event
app.postsync = function(items) {
/* jshint unused: false */
// Called after every sync with result from outbox.sendAll().
// (override to customize behavior, e.g. update a status icon)
var msg;
if (app.config.debug && items.length) {
var result = true;
items.forEach(function(item) {
if (!item) {
result = null;
}
if (!item.synced && result) {
result = false;
}
});
if (result) {
console.log("Successfully synced.");
} else {
if (result === false) {
msg = "Sync error!";
} else {
msg = "Sync failed!";
}
outbox.unsynced().then(function(unsynced) {
console.warn(msg + " " + unsynced + " items remain unsynced");
});
}
}
app.syncRefresh(items);
};
app.syncRefresh = function(items) {
if (!items.length || !jqm.activePage.data('wq-sync-refresh')) {
return;
}
outbox.unsynced().then(function(unsynced) {
tmpl.setDefault('unsynced', unsynced);
app.refresh();
});
};
// Return a list of all foreign key fields
app.getParents = function(page) {
var conf = _getConf(page);
return conf.form.filter(function(field) {
return field['wq:ForeignKey'];
}).map(function(field) {
return field['wq:ForeignKey'];
});
};
// Shortcuts for $.mobile.changePage
app.nav = function(url, options) {
url = app.base_url + '/' + url;
if (!options) {
options = {};
}
options.allowSamePageTransition = true;
jqm.changePage(url, options);
};
app.replaceState = function(url) {
app.nav(url, {
'transition': 'none',
'changeHash': false
});
setTimeout(function() {
window.history.replaceState(null, '', app.base_url + '/' + url);
var hist = jqm.navigate.history;
hist.stack = [hist.stack[hist.stack.length - 1]];
hist.activeIndex = 0;
}, 300);
};
app.refresh = function() {
jqm.changePage(jqm.activePage.data('url'), {
'transition': 'none',
'allowSamePageTransition': true
});
};
// Internal variables and functions
function _setCSRFToken(csrftoken) {
outbox.setCSRFToken(csrftoken);
tmpl.setDefault('csrf_token', csrftoken);
return ds.set('csrf_token', csrftoken);
}
function _callPlugins(method, lookup, args) {
var plugin, fn, fnArgs, queue = [];
for (plugin in app.plugins) {
fn = app.plugins[plugin][method];
if (args) {
fnArgs = args;
} else if (lookup) {
fnArgs = [lookup[plugin]];
}
if (fn) {
queue.push(fn.apply(app.plugins[plugin], fnArgs));
}
}
return queue;
}
function _getRouteInfo(page, mode, itemid, url, parentInfo) {
var conf = _getConf(page, true);
if (!conf) {
conf = {
'name': page,
'page': page,
'form': [],
'modes': []
};
}
router.setPath(url);
return $.extend(
parentInfo || {},
router.info,
{
'page': page,
'page_config': conf,
'mode': mode,
'item_id': itemid
}
);
}
// Generate list view context and render with [url]_list template;
// handles requests for [url] and [url]/
_register.list = function(page) {
var conf = _getConf(page);
router.register(conf.url, go);
router.register(conf.url + '/', go);
function go(match, ui, params) {
app.go(page, ui, params);
}
// Special handling for /[parent_list_url]/[parent_id]/[url]
app.getParents(page).forEach(function(ppage) {
var pconf = _getConf(ppage);
var url = pconf.url;
if (url) {
url += '/';
}
url += '<slug>/' + conf.url;
router.register(url, goUrl(ppage, url));
router.register(url + '/', goUrl(ppage, url));
});
function goUrl(ppage, url) {
return function(match, ui, params) {
var pconf = _getConf(ppage);
var pageurl = url.replace('<slug>', match[1]);
spin.start();
app.models[ppage].find(match[1]).then(function(pitem) {
spin.stop();
var context = {
'parent_id': match[1],
'parent_url': (pitem && (pconf.url + '/' + pitem.id)) ||
('outbox/' + match[1].split('-')[1]),
'parent_label': pitem && pitem.label,
'parent_page': ppage
};
context['parent_is_' + ppage] = true;
app.go(page, ui, params, undefined, false, pageurl, context);
});
};
}
};
_onShow.list = function(page) {
var conf = _getConf(page);
var url = conf.url ? conf.url + '/?' : '';
router.addRoute(url, 's', function(match) {
app.runPlugins(page, 'list', null, match[0]);
});
// Special handling for /[parent_list_url]/[parent_id]/[url]
app.getParents(page).forEach(function(ppage) {
var pconf = app.config.pages[ppage];
var purl = pconf.url;
if (purl) {
purl += '/';
}
purl = '(' + purl + ')<slug>/' + conf.url;
router.addRoute(purl + '/?', 's', goUrl(ppage));
});
function goUrl(ppage) {
return function(match) {
var parentInfo = {
'parent_id': match[2],
'parent_url': match[1] + match[2],
'parent_page': ppage
};
app.runPlugins(page, 'list', null, match[0], parentInfo);
};
}
};
app._addOutboxItemsToContext = function(context, unsyncedItems) {
// Add any outbox items to context
context.unsynced = unsyncedItems.length;
context.unsyncedItems = unsyncedItems;
};
function _displayList(page, ui, params, url, context) {
spin.stop();
var conf = _getConf(page);
var model = app.models[page];
var pnum = model.opts.page, next = null, prev = null, filter;
if (url === undefined) {
url = conf.url;
if (url) {
url += '/';
}
}
if ((params && $.param(params)) || (context && context.parent_page)) {
if (params && $.param(params)) {
url += "?" + $.param(params);
}
if (params && params.page) {
pnum = params.page;
}
filter = {};
for (var key in params || {}) {
if (key != 'page') {
filter[key] = params[key];
}
}
if (context && context.parent_page) {
conf.form.forEach(function(field) {
if (field['wq:ForeignKey'] == context.parent_page) {
filter[field.name + '_id'] = context.parent_id;
}
});
}
}
if (filter && !Object.keys(filter).length) {
filter = null;
}
// Load from server if data might not exist locally
if (app.config.loadMissingAsHtml) {
if (!model.opts.client) {
return _loadFromServer(url, ui);
}
if (filter && model.opts.server) {
return _loadFromServer(url, ui);
}
if (pnum > model.opts.page) {
return _loadFromServer(url, ui);
}
}
if (!pnum && !model.opts.client) {
pnum = 1;
}
function getData() {
if (filter) {
return model.filterPage(filter);
} else if (pnum > model.opts.page) {
return model.page(pnum);
} else {
return model.load();
}
}
function getUnsynced() {
if (pnum == model.opts.page || (pnum == 1 && !model.opts.client)) {
return model.unsyncedItems();
} else {
return Promise.resolve([]);
}
}
// If the number of unsynced records changes while loading the data,
// load the data a second time to make sure the list is up to date.
// (this is rare except for cache=none lists with background sync)
return getUnsynced().then(function(unsynced1) {
return getData().then(function(data1) {
return getUnsynced().then(function(unsynced2) {
if (unsynced1 && unsynced2 &&
unsynced1.length != unsynced2.length) {
return getData().then(function(data2) {
return [data2, unsynced2];
});
} else {
return [data1, unsynced2];
}
});
});
}).then(function(results) {
var data = results[0],
unsyncedItems = results[1],
parentInfo = {}, routeInfo,
prevIsLocal, currentIsLocal;
['parent_id', 'parent_url', 'parent_page'].forEach(function(key) {
if (context && context[key]) {
parentInfo[key] = context[key];
}
});
routeInfo = _getRouteInfo(page, 'list', null, url, parentInfo);
if (pnum > model.opts.page && (model.opts.client || pnum > 1)) {
prev = conf.url + '/';
if (+pnum - 1 > model.opts.page &&
(model.opts.client || pnum > 2)) {
prev += '?' + $.param({
'page': +pnum - 1
});
} else if (pnum == 1) {
prevIsLocal = true;
}
}
if (pnum < data.pages && (model.opts.server || pnum)) {
var nextp = {'page': +pnum + 1};
next = conf.url + '/?' + $.param(nextp);
if (nextp.page == 1) {
currentIsLocal = true;
}
}
context = $.extend({'page_config': conf}, data, {
'previous': prev ? '/' + prev : null,
'next': next ? '/' + next : null,
'multiple': model.opts.server && data.pages > model.opts.page,
'previous_is_local': prevIsLocal,
'current_is_local': currentIsLocal
}, context);
app._addOutboxItemsToContext(context, unsyncedItems);
return _addLookups(page, context, false, routeInfo).then(
function(context) {
return router.go(
url, page + '_list', context, ui, conf.once ? true : false
);
}
);
});
}
// Generate item detail view context and render with [url]_detail template;
// handles requests for [url]/[id]
_register.detail = function(page, mode) {
var conf = _getConf(page);
var url = _getDetailUrl(conf.url, mode);
var reserved = _getDetailReserved(conf.url);
router.register(url, function(match, ui, params) {
if (reserved.indexOf(match[1]) > -1) {
return;
}
app.go(page, ui, params, match[1], mode);
});
};
// Register an onshow event for item detail views
_onShow.detail = function(page, mode) {
var conf = _getConf(page);
var url = _getDetailUrl(conf.url, mode);
var reserved = _getDetailReserved(conf.url);
router.addRoute(url, 's', function(match) {
if (reserved.indexOf(match[1]) > -1) {
return;
}
app.runPlugins(page, mode, match[1], match[0]);
});
};
function _getDetailUrl(url, mode) {
if (url) {
url += "/";
}
url += '<slug>';
if (mode != 'detail') {
url += '/' + mode;
}
return url;
}
function _getDetailReserved(url) {
var reserved = ["new"];
if (!url) {
// This list is bound to root URL, don't mistake other lists for items
for (var key in app.wq_config.pages) {
reserved.push(app.wq_config.pages[key].url);
}
}
return reserved;
}
// Generate item edit context and render with [url]_edit template;
// handles requests for [url]/[id]/edit and [url]/new
_register.edit = function(page) {
var conf = _getConf(page);
router.register(conf.url + '/<slug>/edit', go);
router.register(conf.url + '/(new)', go);
function go(match, ui, params) {
app.go(page, ui, params, match[1], 'edit');
}
};
// Register an onshow event for item edit views
_onShow.edit = function(page) {
var conf = _getConf(page);
var url = conf.url ? conf.url + '/' : '';
router.addRoute(url + '<slug>/edit', 's', go);
router.addRoute(url + '(new)', 's', go);
function go(match) {
var itemid = match[1];
app.runPlugins(page, 'edit', itemid, match[0]);
}
};
function _displayItem(itemid, item, page, ui, params, mode, url, context) {
var conf = _getConf(page);
var model = app.models[page];
spin.stop();
if (url === undefined) {
url = conf.url;
if (url) {
url += '/';
}
url += itemid;
if (mode != 'detail' && itemid != 'new') {
url += '/' + mode;
}
if (params && $.param(params)) {
url += '?' + $.param(params);
}
}
if (item) {
if (mode == 'edit') {
return _renderEdit(itemid, item, page, ui, params, url, context);
} else {
return _renderDetail(item, page, mode, ui, params, url, context);
}
} else {
if (model.opts.server && app.config.loadMissingAsHtml) {
// opts.server indicates that the local list does not represent
// the entire dataset; if an item is not found, attempt to load
// HTML directly from the server (using built-in jQM loader)
return _loadFromServer(url, ui);
} else {
// If opts.server is false, locally stored list is assumed to
// contain the entire dataset, so the item probably does not exist.
return router.notFound(url);
}
}
}
function _renderDetail(item, page, mode, ui, params, url, context) {
var conf = _getConf(page),
routeInfo = _getRouteInfo(page, mode, item.id || 'new', url, null);
if (context && context.outbox_id) {
routeInfo.outbox_id = context.outbox_id;
}
context = $.extend({'page_config': conf}, item, context);