/
directory.js
420 lines (361 loc) · 11.7 KB
/
directory.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
/**
* _ _
* | | | |
* __ _ _ __ _ __ ___ ___| | ___ _ __ __ _| |_ ___ _ __
* / _` | '_ \| '_ \ / __/ _ \ |/ _ \ '__/ _` | __/ _ \| '__|
* | (_| | |_) | |_) | (_| __/ | __/ | | (_| | || (_) | |
* \__,_| .__/| .__/ \___\___|_|\___|_| \__,_|\__\___/|_|
* | | | |
* |_| |_|
*
*
* @overview
* This is the controller file for the Directory View. The directory view loads data from
* a flat file, and derives a Sectioned and Indexed (iOS) ListView displaying all contacts.
* The Directory has two ListView Templates, one for standard contacts, the other to denote
* that you have a marked the contact as a Bookmark (or Favorite). Also, the Directory View
* can be filtered so that it only displays bookmarked or favorited contacts.
*
* @copyright
* Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
*
* @license
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
/**
* Instantiate the local variables for this controller
*/
var _args = arguments[0] || {}, // Any passed in arguments will fall into this property
App = Alloy.Globals.App, // reference to the APP singleton object
$FM = require('favoritesmgr'), // FavoritesManager object (see lib/utilities.js)
users = null, // Array placeholder for all users
indexes = []; // Array placeholder for the ListView Index (used by iOS only);
/**
* Appcelerator Analytics Call
*/
var title = _args.title ? _args.title.toLowerCase() : "directory";
Ti.Analytics.featureEvent(Ti.Platform.osname+"."+title+".viewed");
/**
* Function to inialize the View, gathers data from the flat file and sets up the ListView
*/
function init(){
/**
* Access the FileSystem Object to read in the information from a flat file (lib/userData/data.js)
* DOCS: http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Filesystem
*/
var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + "userData/data.json");
/**
* Populate the users variable from the file this call returns an array
*/
users = JSON.parse(file.read().text).users;
/**
* Sorts the `users` array by the lastName property of the user (leverages UnderscoreJS _.sortBy function)
*/
users = _.sortBy(users, function(user){
return user.lastName
});
/**
* IF the users array exists
*/
if(users) {
/**
* Setup our Indexes and Sections Array for building out the ListView components
*
*/
indexes = [];
var sections = [];
/**
* Group the data by first letter of last name to make it easier to create
* sections. (leverages the UndrescoreJS _.groupBy function)
*/
var userGroups = _.groupBy(users, function(item){
return item.lastName.charAt(0);
});
/**
* Iterate through each group created, and prepare the data for the ListView
* (Leverages the UnderscoreJS _.each function)
*/
_.each(userGroups, function(group){
/**
* Take the group data that is passed into the function, and parse/transform
* it for use in the ListView templates as defined in the directory.xml file.
*/
var dataToAdd = preprocessForListView(group);
/**
* Check to make sure that there is data to add to the table,
* if not lets exit
*/
if(dataToAdd.length < 1) return;
/**
* Lets take the first Character of the LastName and push it onto the index
* Array - this will be used to generate the indices for the ListView on IOS
*/
indexes.push({
index: indexes.length,
title: group[0].lastName.charAt(0)
});
/**
* Create the ListViewSection header view
* DOCS: http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.ListSection-property-headerView
*/
var sectionHeader = Ti.UI.createView({
backgroundColor: "#ececec",
width: Ti.UI.FILL,
height: 30
});
/**
* Create and Add the Label to the ListView Section header view
*/
var sectionLabel = Ti.UI.createLabel({
text: group[0].lastName.charAt(0),
left: 20,
font:{
fontSize: 20
},
color: "#666"
});
sectionHeader.add(sectionLabel);
/**
* Create a new ListViewSection, and ADD the header view created above to it.
*/
var section = Ti.UI.createListSection({
headerView: sectionHeader
});
/**
* Add Data to the ListViewSection
*/
section.items = dataToAdd;
/**
* Push the newly created ListViewSection onto the `sections` array. This will be used to populate
* the ListView
*/
sections.push(section);
});
/**
* Add the ListViewSections and data elements created above to the ListView
*/
$.listView.sections = sections;
/**
* For iOS, we add an event listener on the swipe of the ListView to display the index of the ListView we
* created above. The `sectionIndexTitles` property is only valid on iOS, so we put these handlers in the iOS block.
*/
if(OS_IOS) {
$.wrapper.addEventListener("swipe", function(e){
if(e.direction === "left"){
$.listView.sectionIndexTitles = indexes;
}
if(e.direction === "right"){
$.listView.sectionIndexTitles = null;
}
});
}
}
/**
* Update the Window title if required (only used when we create the Bookmarks View)
*/
if(_args.title){
$.wrapper.title = _args.title;
}
/**
* Check to see if the `restrictToFavorites` flag has been passed in as an argument, and
* hide the favorite icon accordingly
*/
if(_args.restrictToFavorites){
OS_IOS && ($.searchBar.showBookmark = false);
}
else {
if(OS_IOS){
$.wrapper.leftNavButton = Ti.UI.createLabel({
text: "\ue601",
color: "#C41230",
font:{
fontFamily:"icomoon",
fontSize:36
}
});
}
}
};
/**
* Convert an array of data from a JSON file into a format that can be added to the ListView
*
* @param {Object} Raw data elements from the JSON file.
*/
var preprocessForListView = function(rawData) {
/**
* If we need to filter the view to only show bookmars, check to see if the `restrictToFavorites`
* flag has been passed in as an argument to the controller, and only show users that are favorites
*/
if(_args.restrictToFavorites) {
/**
* redefines the collection to only have users that are currently listed as favorites (leverages
* the UnderscoreJS _.filter function )
*/
rawData = _.filter(rawData, function(item){
/**
* each item (or user) that is referenced, we look to see if the user id is included in favorites array
* retrieved from persistent storage above
*/
return $FM.exists(item.id);
});
}
/**
* Using the rawData collection, we map data properties of the users in this array to an array that maps an array to properly
* display the data in the ListView based on the templates defined in directory.xml (levearges the _.map Function of UnderscoreJS)
*/
return _.map(rawData, function(item) {
/**
* Need to check to see if this user item is a favorite. If it is, we will use the `favoriteTemplate` in the ListView.
* (leverages the _.find function of UnderscoreJS)
*/
var isFavorite = $FM.exists(item.id);
/**
* Create the new user object which is added to the Array that is returned by the _.map function.
*/
return {
template: isFavorite ? "favoriteTemplate" : "userTemplate",
properties: {
searchableText: item.firstName + ' ' + item.lastName + ' ' + item.company + ' ' + item.email,
user: item,
editActions: [
{title: isFavorite ? "- Favorite" : "+ Favorite", color: isFavorite ? "#C41230" : "#038BC8" }
],
canEdit:true
},
userName: {text: item.firstName+" "+item.lastName},
userCompany: {text: item.company},
userPhoto: {image: item.photo},
userEmail: {text: item.email}
};
});
};
/**
* This function handles the click events for the rows in the ListView.
* We want to capture the user property associated with the row, and pass
* it into the profile View
*
* @param {Object} Event data passed to the function
*/
function onItemClick(e){
/**
* Appcelerator Analytics Call
*/
Ti.Analytics.featureEvent(Ti.Platform.osname+"."+title+".contact.clicked");
/**
* Get the Item that was clicked
*/
var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
/**
* Open the profile view, and pass in the user data for this contact
*/
Alloy.Globals.Navigator.open("profile", item.properties.user);
}
/**
* This code is only relevant to iOS - to make it cleaner, we are declaring variables, and
* then assigning them to functions within an iOS Block. On MobileWeb, Android, etc this code block will not
* exist
*/
var onSearchChange, onSearchFocus, onSearchCancel;
/**
* Handles the favorite icon click event. Launches this same control as a child window, but limits the view
* to only favoitems.
*
* @param {Object} Event data passed to the function
*/
var onBookmarkClick = function onClick (e){
/**
* Appcelerator Analytics Call
*/
Ti.Analytics.featureEvent(Ti.Platform.osname+"."+title+".favorites.clicked");
/**
* Open this same controller into a new page, pass the flag to restrict the list only to favorite Contacts and force the title
*/
Alloy.Globals.Navigator.open("directory", {restrictToFavorites:true, title:"Favorites", displayHomeAsUp:true});
};
/**
* Handles the SearchBar OnChange event
*
* @description On iOS we want the search bar to always be on top, so we use the onchange event to tie it back
* to the ListView
*
* @param {Object} Event data passed to the function
*/
onSearchChange = function onChange(e){
$.listView.searchText = e.source.value;
};
if(OS_IOS){
/**
* Updates the UI when the SearchBar gains focus. Hides the Bookmark icon and shows
* the Cancel button.
*
* @description We want to use both the bookmark feature and Cancel, but don't want them to show up together (EWW!)
* so we use the focus event to show the Cancel button and hide the bookmark
*
* @param {Object} Event data passed to the function
*/
onSearchFocus = function onFocus(e){
$.searchBar.showBookmark = false;
$.searchBar.showCancel = true;
};
/**
* Updates the UI when the Cancel button is clicked within the search bar. Hides the Cancel button and shows
* the Bookmark icon
*
* @param {Object} Event data passed to the function
*/
onSearchCancel = function onCancel(e){
if(!_args.restrictToFavorites){
$.searchBar.showBookmark = true;
$.searchBar.showCancel = false;
}
$.searchBar.blur();
};
/**
* Updates user record favorite classification and the list elements
*
* @param {Object} e Event data passed to the function
*/
function onRowAction(e){
var row = e.section.getItemAt(e.itemIndex);
var id = row.properties.user.id;
if(e.action === "+ Favorite") {
$FM.add(id);
}
else {
$FM.remove(id);
}
$.listView.editing = false;
init();
}
/*
* Assign `editaction` event listener to ListView
*
* NOTE: Updated to 'editaction' instead of 'rowAction' per
* ticket
* https://jira.appcelerator.org/browse/TIMOB-19096
*/
$.listView.addEventListener("editaction", onRowAction);
}
/**
* Hide Bookmark Icon (Android)
*/
$.wrapper.addEventListener("open", function onWindowOpen(){
if(OS_ANDROID && _args.restrictToFavorites){
var activity = $.wrapper.getActivity();
activity.onCreateOptionsMenu = function(e) {
e.menu.clear();
};
activity.invalidateOptionsMenu();
}
});
/**
* Listen for the refresh event, and re-initialize
*/
Ti.App.addEventListener("refresh-data", function(e){
init();
});
/**
* Initialize View
*/
init();