Debian Codegraph @

dojox/mobile/app/List.js

raw symbols SCIP
1 dojo.provide("dojox.mobile.app.List");
2 dojo.experimental("dojox.mobile.app.List");
3
4 dojo.require("dojo.string");
5 dojo.require("dijit._WidgetBase");
6
7 (function(){
8
9 var templateCache = {};
10
11 dojo.declare("dojox.mobile.app.List", dijit._WidgetBase, {
12 // summary:
13 // A templated list widget. Given a simple array of data objects
14 // and a HTML template, it renders a list of elements, with
15 // support for a swipe delete action. An optional template
16 // can be provided for when the list is empty.
17
18 // items: Array
19 // The array of data items that will be rendered.
20 items: null,
21
22 // itemTemplate: String
23 // The URL to the HTML file containing the markup for each individual
24 // data item.
25 itemTemplate: "",
26
27 // emptyTemplate: String
28 // The URL to the HTML file containing the HTML to display if there
29 // are no data items. This is optional.
30 emptyTemplate: "",
31
32 // dividerTemplate: String
33 // The URL to the HTML file containing the markup for the dividers
34 // between groups of list items
35 dividerTemplate: "",
36
37 // dividerFunction: Function
38 // Function to create divider elements. This should return a divider
39 // value for each item in the list
40 dividerFunction: null,
41
42 // labelDelete: String
43 // The label to display for the Delete button
44 labelDelete: "Delete",
45
46 // labelCancel: String
47 // The label to display for the Cancel button
48 labelCancel: "Cancel",
49
50 // controller: Object
51 controller: null,
52
53 // autoDelete: Boolean
54 autoDelete: true,
55
56 // enableDelete: Boolean
57 enableDelete: true,
58
59 // enableHold: Boolean
60 enableHold: true,
61
62 // formatters: Object
63 // A name/value map of functions used to format data for display
64 formatters: null,
65
66 // _templateLoadCount: Number
67 // The number of templates remaining to load before the list renders.
68 _templateLoadCount: 0,
69
70 // _mouseDownPos: Object
71 // The coordinates of where a mouseDown event was detected
72 _mouseDownPos: null,
73
74 baseClass: "list",
75
76 constructor: function(){
77 this._checkLoadComplete = dojo.hitch(this, this._checkLoadComplete);
78 this._replaceToken = dojo.hitch(this, this._replaceToken);
79 this._postDeleteAnim = dojo.hitch(this, this._postDeleteAnim);
80 },
81
82 postCreate: function(){
83
84 var _this = this;
85
86 if(this.emptyTemplate){
87 this._templateLoadCount++;
88 }
89 if(this.itemTemplate){
90 this._templateLoadCount++;
91 }
92 if(this.dividerTemplate){
93 this._templateLoadCount++;
94 }
95
96 this.connect(this.domNode, "onmousedown", function(event){
97 var touch = event;
98 if(event.targetTouches && event.targetTouches.length > 0){
99 touch = event.targetTouches[0];
100 }
101
102 // Find the node that was tapped/clicked
103 var rowNode = _this._getRowNode(event.target);
104
105 if(rowNode){
106 // Add the rows data to the event so it can be picked up
107 // by any listeners
108 _this._setDataInfo(rowNode, event);
109
110 // Select and highlight the row
111 _this._selectRow(rowNode);
112
113 // Record the position that was tapped
114 _this._mouseDownPos = {
115 x: touch.pageX,
116 y: touch.pageY
117 };
118 _this._dragThreshold = null;
119 }
120 });
121
122 this.connect(this.domNode, "onmouseup", function(event){
123 // When the mouse/finger comes off the list,
124 // call the onSelect function and deselect the row.
125 if(event.targetTouches && event.targetTouches.length > 0){
126 event = event.targetTouches[0];
127 }
128 var rowNode = _this._getRowNode(event.target);
129
130 if(rowNode){
131
132 _this._setDataInfo(rowNode, event);
133
134 if(_this._selectedRow){
135 _this.onSelect(rowNode._data, rowNode._idx, rowNode);
136 }
137
138 this._deselectRow();
139 }
140 });
141
142 // If swipe-to-delete is enabled, listen for the mouse moving
143 if(this.enableDelete){
144 this.connect(this.domNode, "mousemove", function(event){
145 dojo.stopEvent(event);
146 if(!_this._selectedRow){
147 return;
148 }
149 var rowNode = _this._getRowNode(event.target);
150
151 // Still check for enableDelete in case it's changed after
152 // this listener is added.
153 if(_this.enableDelete && rowNode && !_this._deleting){
154 _this.handleDrag(event);
155 }
156 });
157 }
158
159 // Put the data and index onto each onclick event.
160 this.connect(this.domNode, "onclick", function(event){
161 if(event.touches && event.touches.length > 0){
162 event = event.touches[0];
163 }
164 var rowNode = _this._getRowNode(event.target, true);
165
166 if(rowNode){
167 _this._setDataInfo(rowNode, event);
168 }
169 });
170
171 // If the mouse or finger moves off the selected row,
172 // deselect it.
173 this.connect(this.domNode, "mouseout", function(event){
174 if(event.touches && event.touches.length > 0){
175 event = event.touches[0];
176 }
177 if(event.target == _this._selectedRow){
178 _this._deselectRow();
179 }
180 });
181
182 // If no item template has been provided, it is an error.
183 if(!this.itemTemplate){
184 throw Error("An item template must be provided to " + this.declaredClass);
185 }
186
187 // Load the item template
188 this._loadTemplate(this.itemTemplate, "itemTemplate", this._checkLoadComplete);
189
190 if(this.emptyTemplate){
191 // If the optional empty template has been provided, load it.
192 this._loadTemplate(this.emptyTemplate, "emptyTemplate", this._checkLoadComplete);
193 }
194
195 if(this.dividerTemplate){
196 this._loadTemplate(this.dividerTemplate, "dividerTemplate", this._checkLoadComplete);
197 }
198 },
199
200 handleDrag: function(event){
201 // summary:
202 // Handles rows being swiped for deletion.
203 var touch = event;
204 if(event.targetTouches && event.targetTouches.length > 0){
205 touch = event.targetTouches[0];
206 }
207
208 // Get the distance that the mouse or finger has moved since
209 // beginning the swipe action.
210 var diff = touch.pageX - this._mouseDownPos.x;
211
212 var absDiff = Math.abs(diff);
213 if(absDiff > 10 && !this._dragThreshold){
214 // Make the user drag the row 60% of the width to remove it
215 this._dragThreshold = dojo.marginBox(this._selectedRow).w * 0.6;
216 if(!this.autoDelete){
217 this.createDeleteButtons(this._selectedRow);
218 }
219 }
220
221 this._selectedRow.style.left = (absDiff > 10 ? diff : 0) + "px";
222
223 // If the user has dragged the row more than the threshold, slide
224 // it off the screen in preparation for deletion.
225 if(this._dragThreshold && this._dragThreshold < absDiff){
226 this.preDelete(diff);
227 }
228 },
229
230 handleDragCancel: function(){
231 // summary:
232 // Handle a drag action being cancelled, for whatever reason.
233 // Reset handles, remove CSS classes etc.
234 if(this._deleting){
235 return;
236 }
237 dojo.removeClass(this._selectedRow, "hold");
238 this._selectedRow.style.left = 0;
239 this._mouseDownPos = null;
240 this._dragThreshold = null;
241
242 this._deleteBtns && dojo.style(this._deleteBtns, "display", "none");
243 },
244
245 preDelete: function(currentLeftPos){
246 // summary:
247 // Slides the row offscreen before it is deleted
248
249 // TODO: do this with CSS3!
250 var self = this;
251
252 this._deleting = true;
253
254 dojo.animateProperty({
255 node: this._selectedRow,
256 duration: 400,
257 properties: {
258 left: {
259 end: currentLeftPos +
260 ((currentLeftPos > 0 ? 1 : -1) * this._dragThreshold * 0.8)
261 }
262 },
263 onEnd: dojo.hitch(this, function(){
264 if(this.autoDelete){
265 this.deleteRow(this._selectedRow);
266 }
267 })
268 }).play();
269 },
270
271 deleteRow: function(row){
272
273 // First make the row invisible
274 // Put it back where it came from
275 dojo.style(row, {
276 visibility: "hidden",
277 minHeight: "0px"
278 });
279 dojo.removeClass(row, "hold");
280
281 this._deleteAnimConn =
282 this.connect(row, "webkitAnimationEnd", this._postDeleteAnim);
283
284 dojo.addClass(row, "collapsed");
285 },
286
287 _postDeleteAnim: function(event){
288 // summary:
289 // Completes the deletion of a row.
290
291 if(this._deleteAnimConn){
292 this.disconnect(this._deleteAnimConn);
293 this._deleteAnimConn = null;
294 }
295
296 var row = this._selectedRow;
297 var sibling = row.nextSibling;
298 var prevSibling = row.previousSibling;
299
300 // If the previous node is a divider and either this is
301 // the last element in the list, or the next node is
302 // also a divider, remove the divider for the deleted section.
303 if(prevSibling && prevSibling._isDivider){
304 if(!sibling || sibling._isDivider){
305 prevSibling.parentNode.removeChild(prevSibling);
306 }
307 }
308
309 row.parentNode.removeChild(row);
310 this.onDelete(row._data, row._idx, this.items);
311
312 // Decrement the index of each following row
313 while(sibling){
314 if(sibling._idx){
315 sibling._idx--;
316 }
317 sibling = sibling.nextSibling;
318 }
319
320 dojo.destroy(row);
321
322 // Fix up the 'first' and 'last' CSS classes on the rows
323 dojo.query("> *:not(.buttons)", this.domNode).forEach(this.applyClass);
324
325 this._deleting = false;
326 this._deselectRow();
327 },
328
329 createDeleteButtons: function(aroundNode){
330 // summary:
331 // Creates the two buttons displayed when confirmation is
332 // required before deletion of a row.
333 // aroundNode:
334 // The DOM node of the row about to be deleted.
335 var mb = dojo.marginBox(aroundNode);
336 var pos = dojo._abs(aroundNode, true);
337
338 if(!this._deleteBtns){
339 // Create the delete buttons.
340 this._deleteBtns = dojo.create("div",{
341 "class": "buttons"
342 }, this.domNode);
343
344 this.buttons = [];
345
346 this.buttons.push(new dojox.mobile.Button({
347 btnClass: "mblRedButton",
348 label: this.labelDelete
349 }));
350 this.buttons.push(new dojox.mobile.Button({
351 btnClass: "mblBlueButton",
352 label: this.labelCancel
353 }));
354
355 dojo.place(this.buttons[0].domNode, this._deleteBtns);
356 dojo.place(this.buttons[1].domNode, this._deleteBtns);
357
358 dojo.addClass(this.buttons[0].domNode, "deleteBtn");
359 dojo.addClass(this.buttons[1].domNode, "cancelBtn");
360
361 this._handleButtonClick = dojo.hitch(this._handleButtonClick);
362 this.connect(this._deleteBtns, "onclick", this._handleButtonClick);
363 }
364 dojo.removeClass(this._deleteBtns, "fade out fast");
365 dojo.style(this._deleteBtns, {
366 display: "",
367 width: mb.w + "px",
368 height: mb.h + "px",
369 top: (aroundNode.offsetTop) + "px",
370 left: "0px"
371 });
372 },
373
374 onDelete: function(data, index, array){
375 // summary:
376 // Called when a row is deleted
377 // data:
378 // The data related to the row being deleted
379 // index:
380 // The index of the data in the total array
381 // array:
382 // The array of data used.
383
384 array.splice(index, 1);
385
386 // If the data is empty, rerender in case an emptyTemplate has
387 // been provided
388 if(array.length < 1){
389 this.render();
390 }
391 },
392
393 cancelDelete: function(){
394 // summary:
395 // Cancels the deletion of a row.
396 this._deleting = false;
397 this.handleDragCancel();
398 },
399
400 _handleButtonClick: function(event){
401 // summary:
402 // Handles the click of one of the deletion buttons, either to
403 // delete the row or to cancel the deletion.
404 if(event.touches && event.touches.length > 0){
405 event = event.touches[0];
406 }
407 var node = event.target;
408 if(dojo.hasClass(node, "deleteBtn")){
409 this.deleteRow(this._selectedRow);
410 }else if(dojo.hasClass(node, "cancelBtn")){
411 this.cancelDelete();
412 }else{
413 return;
414 }
415 dojo.addClass(this._deleteBtns, "fade out");
416 },
417
418 applyClass: function(node, idx, array){
419 // summary:
420 // Applies the 'first' and 'last' CSS classes to the relevant
421 // rows.
422
423 dojo.removeClass(node, "first last");
424 if(idx == 0){
425 dojo.addClass(node, "first");
426 }
427 if(idx == array.length - 1){
428 dojo.addClass(node, "last");
429 }
430 },
431
432 _setDataInfo: function(rowNode, event){
433 // summary:
434 // Attaches the data item and index for each row to any event
435 // that occurs on that row.
436 event.item = rowNode._data;
437 event.index = rowNode._idx;
438 },
439
440 onSelect: function(data, index, rowNode){
441 // summary:
442 // Dummy function that is called when a row is tapped
443 },
444
445 _selectRow: function(row){
446 // summary:
447 // Selects a row, applies the relevant CSS classes.
448 if(this._deleting && this._selectedRow && row != this._selectedRow){
449 this.cancelDelete();
450 }
451
452 if(!dojo.hasClass(row, "row")){
453 return;
454 }
455 if(this.enableHold || this.enableDelete){
456 dojo.addClass(row, "hold");
457 }
458 this._selectedRow = row;
459 },
460
461 _deselectRow: function(){
462 // summary:
463 // Deselects a row, and cancels any drag actions that were
464 // occurring.
465 if(!this._selectedRow || this._deleting){
466 return;
467 }
468 this.handleDragCancel();
469 dojo.removeClass(this._selectedRow, "hold");
470 this._selectedRow = null;
471 },
472
473 _getRowNode: function(fromNode, ignoreNoClick){
474 // summary:
475 // Gets the DOM node of the row that is equal to or the parent
476 // of the node passed to this function.
477 while(fromNode && !fromNode._data && fromNode != this.domNode){
478 if(!ignoreNoClick && dojo.hasClass(fromNode, "noclick")){
479 return null;
480 }
481 fromNode = fromNode.parentNode;
482 }
483 return fromNode == this.domNode ? null : fromNode;
484 },
485
486 applyTemplate: function(template, data){
487 return dojo._toDom(dojo.string.substitute(
488 template, data, this._replaceToken, this.formatters || this));
489 },
490
491 render: function(){
492 // summary:
493 // Renders the list.
494
495 // Delete all existing nodes, except the deletion buttons.
496 dojo.query("> *:not(.buttons)", this.domNode).forEach(dojo.destroy);
497
498 // If there is no data, and an empty template has been provided,
499 // render it.
500 if(this.items.length < 1 && this.emptyTemplate){
501 dojo.place(dojo._toDom(this.emptyTemplate), this.domNode, "first");
502 }else{
503 this.domNode.appendChild(this._renderRange(0, this.items.length));
504 }
505 if(dojo.hasClass(this.domNode.parentNode, "mblRoundRect")){
506 dojo.addClass(this.domNode.parentNode, "mblRoundRectList")
507 }
508
509 var divs = dojo.query("> .row", this.domNode);
510 if(divs.length > 0){
511 dojo.addClass(divs[0], "first");
512 dojo.addClass(divs[divs.length - 1], "last");
513 }
514 },
515
516 _renderRange: function(startIdx, endIdx){
517
518 var rows = [];
519 var row, i;
520 var frag = document.createDocumentFragment();
521 startIdx = Math.max(0, startIdx);
522 endIdx = Math.min(endIdx, this.items.length);
523
524 for(i = startIdx; i < endIdx; i++){
525 // Create a document fragment containing the templated row
526 row = this.applyTemplate(this.itemTemplate, this.items[i]);
527 dojo.addClass(row, 'row');
528 row._data = this.items[i];
529 row._idx = i;
530 rows.push(row);
531 }
532 if(!this.dividerFunction || !this.dividerTemplate){
533 for(i = startIdx; i < endIdx; i++){
534 rows[i]._data = this.items[i];
535 rows[i]._idx = i;
536 frag.appendChild(rows[i]);
537 }
538 }else{
539 var prevDividerValue = null;
540 var dividerValue;
541 var divider;
542 for(i = startIdx; i < endIdx; i++){
543 rows[i]._data = this.items[i];
544 rows[i]._idx = i;
545
546 dividerValue = this.dividerFunction(this.items[i]);
547 if(dividerValue && dividerValue != prevDividerValue){
548 divider = this.applyTemplate(this.dividerTemplate, {
549 label: dividerValue,
550 item: this.items[i]
551 });
552 divider._isDivider = true;
553 frag.appendChild(divider);
554 prevDividerValue = dividerValue;
555 }
556 frag.appendChild(rows[i]);
557 }
558 }
559 return frag;
560 },
561
562 _replaceToken: function(value, key){
563 if(key.charAt(0) == '!'){ value = dojo.getObject(key.substr(1), false, _this); }
564 if(typeof value == "undefined"){ return ""; } // a debugging aide
565 if(value == null){ return ""; }
566
567 // Substitution keys beginning with ! will skip the transform step,
568 // in case a user wishes to insert unescaped markup, e.g. ${!foo}
569 return key.charAt(0) == "!" ? value :
570 // Safer substitution, see heading "Attribute values" in
571 // http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2
572 value.toString().replace(/"/g,"&quot;"); //TODO: add &amp? use encodeXML method?
573
574 },
575
576 _checkLoadComplete: function(){
577 // summary:
578 // Checks if all templates have loaded
579 this._templateLoadCount--;
580
581 if(this._templateLoadCount < 1 && this.get("items")){
582 this.render();
583 }
584 },
585
586 _loadTemplate: function(url, thisAttr, callback){
587 // summary:
588 // Loads a template
589 if(!url){
590 callback();
591 return;
592 }
593
594 if(templateCache[url]){
595 this.set(thisAttr, templateCache[url]);
596 callback();
597 }else{
598 var _this = this;
599
600 dojo.xhrGet({
601 url: url,
602 sync: false,
603 handleAs: "text",
604 load: function(text){
605 templateCache[url] = dojo.trim(text);
606 _this.set(thisAttr, templateCache[url]);
607 callback();
608 }
609 });
610 }
611 },
612
613
614 _setFormattersAttr: function(formatters){
615 // summary:
616 // Sets the data items, and causes a rerender of the list
617 this.formatters = formatters;
618 },
619
620 _setItemsAttr: function(items){
621 // summary:
622 // Sets the data items, and causes a rerender of the list
623
624 this.items = items || [];
625
626 if(this._templateLoadCount < 1 && items){
627 this.render();
628 }
629 },
630
631 destroy: function(){
632 if(this.buttons){
633 dojo.forEach(this.buttons, function(button){
634 button.destroy();
635 });
636 this.buttons = null;
637 }
638
639 this.inherited(arguments);
640 }
641
642 });
643
644 })();