-
Notifications
You must be signed in to change notification settings - Fork 32
/
shoppinglist.js
547 lines (498 loc) · 15 KB
/
shoppinglist.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
// this will be the PouchDB database
var db = new PouchDB('shopping');
// template shopping list object
const sampleShoppingList = {
"_id": "",
"type": "list",
"version": 1,
"title": "",
"checked": false,
"place": {
"title": "",
"license": null,
"lat": null,
"lon": null,
"address": {}
},
"createdAt": "",
"updatedAt": ""
};
// template shopping list item object
const sampleListItem = {
"_id": "",
"type": "item",
"version": 1,
"title": "",
"checked": false,
"createdAt": "",
"updatedAt": ""
};
/**
* Sort comparison function to sort an object by "createdAt" field
*
* @param {String} a
* @param {String} b
* @returns {Number}
*/
const newestFirst = (a, b) => {
if (a.createdAt > b.createdAt) return -1;
if (a.createdAt < b.createdAt) return 1;
return 0
};
/**
* Perform an "AJAX" request i.e call the URL supplied with the
* a querystring constructed from the supplied object
*
* @param {String} url
* @param {Object} querystring
* @returns {Promise}
*/
const ajax = function (url, querystring) {
return new Promise(function(resolve, reject) {
// construct URL
var qs = [];
for(var i in querystring) { qs.push(i + '=' + encodeURIComponent(querystring[i]))}
url = url + '?' + qs.join('&');
// make HTTP GET request
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
resolve(obj);
} else {
reject(null);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
});
};
// Vue Material plugin
Vue.use(VueMaterial);
// Vue Material theme
Vue.material.registerTheme('default', {
primary: 'blue',
accent: 'white',
warn: 'red',
background: 'grey'
});
// this is the Vue.js app. It contains
// el - the HTML element where the app is rendered
// data - the data the app needs to be rendered
// computed - derived data required for the display logic
// method - JavaScript functions
var app = new Vue({
el: '#app',
data: {
mode: 'showlist',
pagetitle: 'Shopping Lists',
shoppingLists: [],
shoppingListItems: [],
singleList: null,
currentListId: null,
newItemTitle:'',
places: [],
selectedPlace: null,
syncURL:'',
syncStatus: 'notsyncing'
},
// computed functions return data derived from the core data.
// if the core data changes, then this function will be called too.
computed: {
/**
* Calculates the counts of items and which items are checked
* grouped by shopping list
*
* @returns {Object}
*/
counts: function() {
var obj = {};
// count #items and how many are checked
for(var i in this.shoppingListItems) {
var d = this.shoppingListItems[i];
if (!obj[d.list]) {
obj[d.list] = { total: 0, checked: 0};
}
obj[d.list].total++;
if (d.checked) {
obj[d.list].checked++;
}
}
return obj;
},
/**
* Calculates the shopping list but sorted into
* date order - newest first
*
* @returns {Array}
*/
sortedShoppingLists: function() {
return this.shoppingLists.sort(newestFirst);
},
/**
* Calculates the shopping list items but sorted into
* date order - newest first
*
* @returns {Array}
*/
sortedShoppingListItems: function() {
return this.shoppingListItems.sort(newestFirst);
}
},
/**
* Called once when the app is first loaded
*/
created: function() {
// create database index on 'type'
db.createIndex({ index: { fields: ['type'] }}).then(() => {
// load all 'list' items
var q = {
selector: {
type: 'list'
}
};
return db.find(q);
}).then((data) => {
// write the data to the Vue model, and from there the web page
app.shoppingLists = data.docs;
// get all of the shopping list items
var q = {
selector: {
type: 'item'
}
};
return db.find(q);
}).then((data) => {
// write the shopping list items to the Vue model
app.shoppingListItems = data.docs;
// load settings (Cloudant sync URL)
return db.get('_local/user');
}).then((data) => {
// if we have settings, start syncing
this.syncURL = data.syncURL;
this.startSync();
}).catch((e) => {})
},
methods: {
/**
* Called when the settings button is pressed. Sets the mode
* to 'settings' so the Vue displays the settings panel.
*/
onClickSettings: function() {
this.mode = 'settings';
},
/**
* Called when the about button is pressed. Sets the mode
* to 'about' so the Vue displays the about panel.
*/
onClickAbout: function() {
this.mode = 'about';
},
/**
* Saves 'doc' to PouchDB. It first checks whether that doc
* exists in the database. If it does, it overwrites it - if
* it doesn't, it just writes it.
* @param {Object} doc
* @returns {Promise}
*/
saveLocalDoc: function(doc) {
return db.get(doc._id).then((data) => {
doc._rev = data._rev;
return db.put(doc);
}).catch((e) => {
return db.put(doc);
});
},
/**
* Called when save button on the settings panel is clicked. The
* Cloudant sync URL is saved in PouchDB and the sync process starts.
*/
onClickStartSync: function() {
var obj = {
'_id': '_local/user',
'syncURL': this.syncURL
};
this.saveLocalDoc(obj).then( () => {
this.startSync();
});
},
/**
* Called when the sync process is to start. Initiates a PouchDB to
* to Cloudant two-way sync and listens to the changes coming in
* from the Cloudant feed. We need to monitor the incoming change
* so that the Vue.js model is kept in sync.
*/
startSync: function() {
this.syncStatus = 'notsyncing';
if (this.sync) {
this.sync.cancel();
this.sync = null;
}
if (!this.syncURL) { return; }
this.syncStatus = 'syncing';
this.sync = db.sync(this.syncURL, {
live: true,
retry: false
}).on('change', (info) => {
// handle change
// if this is an incoming change
if (info.direction == 'pull' && info.change && info.change.docs) {
// loop through all the changes
for(var i in info.change.docs) {
var change = info.change.docs[i];
var arr = null;
// see if it's an incoming item or list or something else
if (change._id.match(/^item/)) {
arr = this.shoppingListItems;
} else if (change._id.match(/^list/)) {
arr = this.shoppingLists;
} else {
continue;
}
// locate the doc in our existing arrays
var match = this.findDoc(arr, change._id);
// if we have it already
if (match.doc) {
// and it's a deletion
if (change._deleted == true) {
// remove it
arr.splice(match.i, 1);
} else {
// modify it
delete change._revisions;
Vue.set(arr, match.i, change);
}
} else {
// add it
if (!change._deleted) {
arr.unshift(change);
}
}
}
}
}).on('error', (e) => {
this.syncStatus = 'syncerror';
}).on('denied', (e) => {
this.syncStatus = 'syncerror';
}).on('paused', (e) => {
if (e) {
this.syncStatus = 'syncerror';
}
});;
},
/**
* Given a list of docs and an id, find the doc in the list that has
* an '_id' (key) that matches the incoming id. Returns an object
* with the
* i - the index where the item was found
* doc - the matching document
* @param {Array} docs
* @param {String} id
* @param {String} key
* @returns {Object}
*/
findDoc: function (docs, id, key) {
if (!key) {
key = '_id';
}
var doc = null;
for(var i in docs) {
if (docs[i][key] == id) {
doc = docs[i];
break;
}
}
return { i: i, doc: doc };
},
/**
* Given a list of docs and an id, find the doc in the list that has
* an '_id' (key) that matches the incoming id. Updates its "updatedAt"
* attribute and write it back to PouchDB.
* i - the index where the item was found
* doc - the matching document
* @param {Array} docs
* @param {String} id
*/
findUpdateDoc: function (docs, id) {
// locate the doc
var doc = this.findDoc(docs, id).doc;
// if it exits
if (doc) {
// modift the updated date
doc.updatedAt = new Date().toISOString();
// write it on the next tick (to give Vue.js chance to sync state)
this.$nextTick(() => {
// write to database
db.put(doc).then((data) => {
// retain the revision token
doc._rev = data.rev;
});
});
}
},
/**
* Called when the user clicks the Add Shopping List button. Sets
* the mode to 'addlist' to reveal the add shopping list form and
* resets the form variables.
*/
onClickAddShoppingList: function() {
// open shopping list form
this.singleList = JSON.parse(JSON.stringify(sampleShoppingList));
this.singleList._id = 'list:' + cuid();
this.singleList.createdAt = new Date().toISOString();
this.pagetitle = 'New Shopping List';
this.places = [];
this.selectedPlace = null;
this.mode='addlist';
},
/**
* Called when the Save Shopping List button is pressed.
* Writes the new list to PouchDB and adds it to the Vue
* model's shoppingLists array
*/
onClickSaveShoppingList: function() {
// add timestamps
this.singleList.updatedAt = new Date().toISOString();
// add to on-screen list, if it's not there already
if (typeof this.singleList._rev === 'undefined') {
this.shoppingLists.unshift(this.singleList);
}
// write to database
db.put(this.singleList).then((data) => {
// keep the revision tokens
this.singleList._rev = data.rev;
// switch mode
this.onBack();
});
},
/**
* Called when the Back button is pressed. Returns to the
* home screen with a lit of shopping lists.
*/
onBack: function() {
this.mode='showlist';
this.pagetitle='Shopping Lists';
},
/**
* Called when the Edit button is pressed next to a shopping list.
* We locate the list document by id and change mode to "addlist",
* pre-filling the form with that document's details.
* @param {String} id
* @param {String} title
*/
onClickEdit: function(id, title) {
this.singleList = this.findDoc(this.shoppingLists, id).doc;
this.pagetitle = 'Edit - ' + title;
this.places = [];
this.selectedPlace = null;
this.mode='addlist';
},
/**
* Called when the delete button is pressed next to a shopping list.
* The shopping list document is located, removed from PouchDB and
* removed from Vue's shoppingLists array.
* @param {String} id
*/
onClickDelete: function(id) {
var match = this.findDoc(this.shoppingLists, id);
db.remove(match.doc).then(() => {
this.shoppingLists.splice(match.i, 1);
});
},
// the user wants to see the contents of a shopping list
// we load it and switch views
/**
* Called when the user wants to edit the contents of a shopping list.
* The mode is set to 'itemedit'. Vue's currentListId is set to this list's
* id field.
* @param {String} id
* @param {String} title
*/
onClickList: function(id, title) {
this.currentListId = id;
this.pagetitle = title;
this.mode = 'itemedit';
},
/**
* Called when a new shopping list item is added. A new shopping list item
* object is created with a unique id. It is written to PouchDB and added
* to Vue's shoppingListItems array
*/
onAddListItem: function() {
if (!this.newItemTitle) return;
var obj = JSON.parse(JSON.stringify(sampleListItem));
obj._id = 'item:' + cuid();
obj.title = this.newItemTitle;
obj.list = this.currentListId;
obj.createdAt = new Date().toISOString();
obj.updatedAt = new Date().toISOString();
db.put(obj).then( (data) => {
obj._rev = data.rev;
this.shoppingListItems.unshift(obj);
this.newItemTitle = '';
});
},
/**
* Called when an item is checked or unchecked from a shopping list.
* The item is located and written to PouchDB
* @param {String} id
*/
onCheckListItem: function(id) {
this.findUpdateDoc(this.shoppingListItems, id);
},
/**
* Called when the Lookup button is pressed. We make an API call to
* OpenStreetMap passing in the user-supplied name of the place. If
* the API returns something, the options are added to Vue's "places"
* array and become a pull-down list of options on the front end.
*/
onClickLookup: function() {
// make request to the OpenStreetMap API
var url = 'https://nominatim.openstreetmap.org/search';
var qs = {
format: 'json',
addressdetails: 1,
namedetails: 1,
q: this.singleList.place.title
};
ajax(url, qs).then((d) => {
// add the list of places to our list
this.places = d;
// if there is only one item in the list
if (d.length ==1) {
// simulate selection of first and only item
this.onChangePlace(d[0].place_id);
}
});
},
// when a place is selected from the list, we find the object in the list
// and copy the lat/long, licence and name over to our database
/**
* Called when an item is selected from the places pull-down list. The
* place is found in the "places" array and its lat/long, licnece and
* address are moved to the Vue object linked with the front-end form.
* @param {String} v
*/
onChangePlace: function(v) {
var doc = this.findDoc(this.places, v, 'place_id').doc;
this.singleList.place.lat = doc.lat;
this.singleList.place.lon = doc.lon;
this.singleList.place.license = doc.licence;
this.singleList.place.address = doc.address;
},
/**
* Called when an item is deleted from a shopping list. We locate the item
* in the list, delete it from PouchDB and remove it from the shoppingListItems
* Vue array.
* @param {String} id
*/
onDeleteItem: function(id) {
var match = this.findDoc(this.shoppingListItems, id);
db.remove(match.doc).then((data) => {
this.shoppingListItems.splice(match.i, 1);
});
}
}
})