1 // ==========================================================================
  2 // Project:   The M-Project - Mobile HTML5 Application Framework
  3 // Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
  4 //            (c) 2011 panacoda GmbH. All rights reserved.
  5 // Creator:   Dominik
  6 // Date:      03.11.2010
  7 // License:   Dual licensed under the MIT or GPL Version 2 licenses.
  8 //            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
  9 //            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
 10 // ==========================================================================
 11 
 12 m_require('ui/search_bar.js');
 13 
 14 /**
 15  * @class
 16  *
 17  * M.ListView is the prototype of any list view. It is used to display static or dynamic
 18  * content as vertically aligned list items (M.ListItemView). A list view provides some
 19  * easy to use helper method, e.g. an out-of-the-box delete view for items.
 20  *
 21  * @extends M.View
 22  */
 23 M.ListView = M.View.extend(
 24 /** @scope M.ListView.prototype */ {
 25 
 26     /**
 27      * The type of this object.
 28      *
 29      * @type String
 30      */
 31     type: 'M.ListView',
 32 
 33     /**
 34      * Determines whether to remove all item if the list is updated or not.
 35      *
 36      * @type Boolean
 37      */
 38     removeItemsOnUpdate: YES,
 39 
 40     /**
 41      * Determines whether to display the list as a divided list or not.
 42      *
 43      * @type Boolean
 44      */
 45     isDividedList: NO,
 46 
 47     /**
 48      * If the list view is a divided list, this property can be used to customize the style
 49      * of the list's dividers.
 50      *
 51      * @type String
 52      */
 53     cssClassForDivider: null,
 54 
 55     /**
 56      * Determines whether to display the the number of child items for each list item view.
 57      *
 58      * @type Boolean
 59      */
 60     isCountedList: NO,
 61 
 62     /**
 63      * If the list view is a counted list, this property can be used to customize the style
 64      * of the list item's counter.
 65      *
 66      * @type String
 67      */
 68     cssClassForCounter: null,
 69 
 70     /**
 71      * This property can be used to customize the style of the list view's split view. For example
 72      * the toggleRemove() of a list view uses the built-in split view functionality.
 73      *
 74      * @type String
 75      */
 76     cssClassForSplitView: null,
 77 
 78     /**
 79      * The list view's items, respectively its child views.
 80      *
 81      * @type Array
 82      */
 83     items: null,
 84 
 85     /**
 86      * States whether the list view is currently in edit mode or not. This is mainly used by the
 87      * built-in toggleRemove() functionality. 
 88      *
 89      * @type Boolean
 90      */
 91     inEditMode: NO,
 92 
 93     /**
 94      * This property contains all available options for the edit mode. For example the target and action
 95      * of the automatically rendered delete button can be specified using this property.
 96      *
 97      * @type Object
 98      */
 99     editOptions: null,
100 
101     /**
102      * Defines if the ListView is rendered with prefixed numbering for each item.
103      *
104      * @type Boolean
105      */
106     isNumberedList: NO,
107 
108     /**
109      * This property contains the list view's template view, the blueprint for every child view.
110      *
111      * @type M.ListItemView
112      */
113     listItemTemplateView: null,
114 
115     /**
116      * Determines whether to display the list view 'inset' or at full width.
117      *
118      * @type Boolean
119      */
120     isInset: NO,
121 
122     /**
123      * The list view's search bar.
124      *
125      * @type Object
126       */
127     searchBar: M.SearchBarView,
128 
129     /**
130      * Determines whether or not to display a search bar at the top of the list view. 
131      *
132      * @type Boolean
133      */
134     hasSearchBar: NO,
135 
136     /**
137      * If the hasSearchBar property is set to YES, this property determines whether to use the built-in
138      * simple search filters or not. If set to YES, the list is simply filtered on the fly according
139      * to the entered search string. Only list items matching the entered search string will be visible.
140      *
141      * If a custom search behaviour is needed, this property must be set to NO.
142      *
143      * @type Boolean
144      */
145     usesDefaultSearchBehaviour: YES,
146 
147     /**
148      * If the hasSearchBar property is set to YES and the usesDefaultSearchBehaviour is set to YES, this
149      * property can be used to specify the inital text for the search bar. This text will be shown as long
150      * as nothing else is entered into the search bar text field.
151      *
152      * @type String
153      */
154     searchBarInitialText: 'Search...',
155 
156     /**
157      * An object containing target and action to be triggered if the search string changes.
158      *
159      * @type Object
160      */
161     onSearchStringDidChange: null,
162 
163     /**
164      * An optional String defining the id property that is passed in view as record id
165      *
166      * @type String
167      */
168     idName: null,
169 
170     /**
171      * Contains a reference to the currently selected list item.
172      *
173      * @type Object
174      */
175     selectedItem: null,
176 
177     /**
178      * This method renders the empty list view either as an ordered or as an unordered list. It also applies
179      * some styling, if the corresponding properties where set.
180      *
181      * @private
182      * @returns {String} The list view's styling as html representation.
183      */
184     render: function() {
185         /* add the list view to its surrounding page */
186         if(!M.ViewManager.currentlyRenderedPage.listList) {
187             M.ViewManager.currentlyRenderedPage.listList = [];
188         }
189         M.ViewManager.currentlyRenderedPage.listList.push(this);
190 
191         if(this.hasSearchBar && !this.usesDefaultSearchBehaviour) {
192             this.searchBar.isListViewSearchBar = YES;
193             this.searchBar.listView = this;
194             this.searchBar = M.SearchBarView.design(this.searchBar);
195             this.html += this.searchBar.render();
196         }
197 
198         var listTagName = this.isNumberedList ? 'ol' : 'ul';
199         this.html += '<' + listTagName + ' id="' + this.id + '" data-role="listview"' + this.style() + '></' + listTagName + '>';
200 
201         return this.html;
202     },
203 
204     /**
205      * This method is responsible for registering events for view elements and its child views. It
206      * basically passes the view's event-property to M.EventDispatcher to bind the appropriate
207      * events.
208      *
209      * It extend M.View's registerEvents method with some special stuff for list views and their
210      * internal events.
211      */
212     registerEvents: function() {
213         /*this.internalEvents = {
214             focus: {
215                 target: this,
216                 action: 'gotFocus'
217             },
218             blur: {
219                 target: this,
220                 action: 'lostFocus'
221             },
222             keyup: {
223                 target: this,
224                 action: 'setValueFromDOM'
225             }
226         }*/
227         this.bindToCaller(this, M.View.registerEvents)();
228         if(this.hasSearchBar && !this.usesDefaultSearchBehaviour) {
229             this.searchBar.registerEvents();
230         }
231     },
232 
233     /**
234      * This method adds a new list item to the list view by simply appending its html representation
235      * to the list view inside the DOM. This method is based on jQuery's append().
236      *
237      * @param {String} item The html representation of a list item to be added.
238      */
239     addItem: function(item) {
240         $('#' + this.id).append(item);
241     },
242 
243     /**
244      * This method removes all of the list view's items by removing all of its content in the DOM. This
245      * method is based on jQuery's empty().
246      */
247     removeAllItems: function() {
248         $('#' + this.id).empty();
249     },
250 
251     /**
252      * Updates the the list view by re-rendering all of its child views, respectively its item views. There
253      * is no rendering done inside this method itself. It is more like the manager of the rendering process
254      * and delegates the responsibility to renderListItemDivider() and renderListItemView() based on the
255      * given list view configuration.
256      *
257      * @private
258      */
259     renderUpdate: function() {
260 
261         /* Remove all list items if the removeItemsOnUpdate property is set to YES */
262         if(this.removeItemsOnUpdate) {
263             this.removeAllItems();
264         }
265 
266         /* Save this in variable that for later use within an other scope (e.g. _each()) */
267         var that = this;
268 
269         /* Get the list view's content as an object from the assigned content binding */
270         if(this.contentBinding && typeof(this.contentBinding.target) === 'object' && typeof(this.contentBinding.property) === 'string' && this.contentBinding.target[this.contentBinding.property]) {
271             var content = this.contentBinding.target[this.contentBinding.property];
272         } else {
273             M.Logger.log('The specified content binding for the list view (' + this.id + ') is invalid!', M.WARN);
274             return;
275         }
276 
277         /* Get the list view's template view for each list item */
278         var templateView = this.listItemTemplateView;
279 
280         /* if there is no template, log error and stop */
281         if(!templateView) {
282             M.Logger.log('The template view could not be loaded! Maybe you forgot to use m_require to set up the correct load order?', M.ERR);
283             return;
284         }
285 
286         /* If there is an items property, re-assign this to content, otherwise iterate through content itself */
287         if(this.items) {
288             content = content[this.items];
289         }
290 
291         if(this.isDividedList) {
292             _.each(content, function(items, divider) {
293                 that.renderListItemDivider(divider);
294                 that.renderListItemView(items, templateView);
295             });
296         } else {
297             this.renderListItemView(content, templateView);
298         }
299 
300         /* Finally let the whole list look nice */
301         this.themeUpdate();
302 
303         /* At last fix the toolbar */
304         $.mobile.fixedToolbars.show();
305     },
306 
307     /**
308      * Renders a list item divider based on a string given by its only parameter.
309      *
310      * @param {String} name The name of the list divider to be rendered.
311      * @private
312      */
313     renderListItemDivider: function(name) {
314         var obj = M.ListItemView.design({});
315         obj.value = name;
316         obj.isDivider = YES,
317         this.addItem(obj.render());
318         obj.theme();
319     },
320 
321     /**
322      * This method renders list items based on the passed parameters.
323      *
324      * @param {Array} content The list items to be rendered.
325      * @param {M.ListItemView} templateView The template for for each list item.
326      * @private
327      */
328     renderListItemView: function(content, templateView) {
329         /* Save this in variable that for later use within an other scope (e.g. _each()) */
330         var that = this;
331 
332         _.each(content, function(item) {
333 
334             /* Create a new object for the current template view */
335             var obj = templateView.design({});
336             /* If item is a model, assign the model's id to the view's modelId property */
337             if(item.type === 'M.Model') {
338                 obj.modelId = item.m_id;
339             /* Otherwise, if there is an id property, save this automatically to have a reference */
340             } else if(item.id || !isNaN(item.id)) {
341                 obj.modelId = item.id;
342             } else if(item[that.idName] || item[that.idName] === "") {
343                 obj.modelId = item[that.idName];
344             }
345 
346             /* Get the child views as an array of strings */
347             var childViewsArray = obj.getChildViewsAsArray();
348 
349             /* If the item is a model, read the values from the 'record' property instead */
350             var record = item.type === 'M.Model' ? item.record : item;
351 
352             /* Iterate through all views defined in the template view */
353             for(var i in childViewsArray) {
354                 /* Create a new object for the current view */
355                 obj[childViewsArray[i]] = obj[childViewsArray[i]].design({});
356 
357                 var regexResult = null;
358                 if(obj[childViewsArray[i]].computedValue) {
359                     /* This regex looks for a variable inside the template view (<%= ... %>) ... */
360                     regexResult = /^<%=\s+([.|_|-|$|§|a-zA-Z]+[0-9]*[.|_|-|$|§|a-zA-Z]*)\s*%>$/.exec(obj[childViewsArray[i]].computedValue.valuePattern);
361                 } else {
362                     regexResult = /^<%=\s+([.|_|-|$|§|a-zA-Z]+[0-9]*[.|_|-|$|§|a-zA-Z]*)\s*%>$/.exec(obj[childViewsArray[i]].valuePattern);
363                 }
364 
365                 /* ... if a match was found, the variable is replaced by the corresponding value inside the record */
366                 if(regexResult) {
367                     switch (obj[childViewsArray[i]].type) {
368                         case 'M.LabelView':
369                         case 'M.ButtonView':
370                         case 'M.ImageView':
371                         case 'M.TextFieldView':
372                             obj[childViewsArray[i]].value = record[regexResult[1]];
373                             break;
374                     }
375                 }
376             }
377 
378             /* If edit mode is on, render a delete button */
379             if(that.inEditMode) {
380                 obj.inEditMode = that.inEditMode;
381                 obj.deleteButton = obj.deleteButton.design({
382                     modelId: obj.modelId,
383                     events: {
384                         tap: {
385                             target: that.editOptions.target,
386                             action: that.editOptions.action
387                         }
388                     },
389                     internalEvents: {
390                         tap: {
391                             target: that,
392                             action: 'removeListItem'
393                         }
394                     }
395                 });
396             }
397 
398             /* set the list view as 'parent' for the current list item view */
399             obj.parentView = that;
400 
401             /* Add the current list view item to the list view ... */
402             that.addItem(obj.render());
403 
404             /* register events */
405             obj.registerEvents();
406             if(obj.deleteButton) {
407                 obj.deleteButton.registerEvents();
408             }
409 
410             /* ... once it is in the DOM, make it look nice */
411             for(var i in childViewsArray) {
412                 obj[childViewsArray[i]].theme();
413             }
414         });
415     },
416 
417     /**
418      * Triggers the rendering engine, jQuery mobile, to style the list view.
419      *
420      * @private
421      */
422     theme: function() {
423         if(this.searchBar) {
424             /* JQM-hack: remove multiple search bars */
425             if($('#' + this.id) && $('#' + this.id).parent()) {
426                 var searchBarsFound = 0;
427                 $('#' + this.id).parent().find('form.ui-listview-filter').each(function() {
428                     searchBarsFound += 1;
429                     if(searchBarsFound == 1) {
430                         return;
431                     }
432                     $(this).remove();
433                 });
434             }
435             this.searchBar.theme();
436         }
437     },
438 
439     /**
440      * Triggers the rendering engine, jQuery mobile, to re-style the list view.
441      *
442      * @private
443      */
444     themeUpdate: function() {
445         $('#' + this.id).listview('refresh');
446     },
447 
448     /**
449      * This method activates the edit mode and forces the list view to re-render itself
450      * and to display a remove button for every list view item.
451      *
452      * @param {Object} options The options for the remove button.
453      */
454     toggleRemove: function(options) {
455         if(this.contentBinding && typeof(this.contentBinding.target) === 'object' && typeof(this.contentBinding.property) === 'string' && this.contentBinding.target[this.contentBinding.property]) {
456             this.inEditMode = !this.inEditMode;
457             this.editOptions = options;
458             this.renderUpdate();
459         }
460     },
461 
462     /**
463      * This method activates a list item by applying the default 'isActive' css style to its
464      * DOM representation.
465      *
466      * @param {String} listItemId The id of the list item to be set active.
467      */
468     setActiveListItem: function(listItemId, event, nextEvent) {
469         if(this.selectedItem) {
470             this.selectedItem.removeCssClass('ui-btn-active');
471         }
472         this.selectedItem = M.ViewManager.getViewById(listItemId);
473 
474         /* is the selection list items are selectable, activate the right one */
475         if(this.listItemTemplateView && this.listItemTemplateView.isSelectable) {
476             this.selectedItem.addCssClass('ui-btn-active');
477         }
478 
479         /* delegate event to external handler, if specified */
480         if(nextEvent) {
481             M.EventDispatcher.callHandler(nextEvent, event, NO, [listItemId, this.selectedItem.modelId]);
482         }
483     },
484 
485     /**
486      * This method resets the list by applying the default css style to its currently activated
487      * list item.
488      */
489     resetActiveListItem: function() {
490         if(this.selectedItem) {
491             this.selectedItem.removeCssClass('ui-btn-active');
492         }
493     },
494 
495     /**
496      * Applies some style-attributes to the list view.
497      *
498      * @private
499      * @returns {String} The list's styling as html representation.
500      */
501     style: function() {
502         var html = '';
503         if(this.cssClass) {
504             html += ' class="' + this.cssClass + '"';
505         }
506         if(this.isDividedList && this.cssClassForDivider) {
507             html += ' data-dividertheme="' + this.cssClassForDivider + '"';
508         }
509         if(this.isInset) {
510             html += ' data-inset="true"';
511         }
512         if(this.isCountedList && this.cssClassForCounter) {
513             html += ' data-counttheme="' + this.cssClassForCounter + '"';
514         }
515         if(this.cssClassForSplitView) {
516             html += ' data-splittheme="' + this.cssClassForSplitView + '"';
517         }
518         if(this.hasSearchBar && this.usesDefaultSearchBehaviour) {
519             html += ' data-filter="true" data-filter-placeholder="' + this.searchBarInitialText + '"';
520         }
521         return html;
522     },
523 
524     removeListItem: function(id, event, nextEvent) {
525         var modelId = M.ViewManager.getViewById(id).modelId;
526 
527         /* delegate event to external handler, if specified */
528         if(nextEvent) {
529             M.EventDispatcher.callHandler(nextEvent, event, NO, [id, modelId]);
530         }
531     }
532 
533 });