initial import
[roojs1] / Roo / tree / TreeSorter.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12
13 /**
14  * @class Roo.tree.TreeSorter
15  * Provides sorting of nodes in a TreePanel
16  * 
17  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
18  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
19  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
20  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
21  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
22  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
23  * @constructor
24  * @param {TreePanel} tree
25  * @param {Object} config
26  */
27 Roo.tree.TreeSorter = function(tree, config){
28     Roo.apply(this, config);
29     tree.on("beforechildrenrendered", this.doSort, this);
30     tree.on("append", this.updateSort, this);
31     tree.on("insert", this.updateSort, this);
32     
33     var dsc = this.dir && this.dir.toLowerCase() == "desc";
34     var p = this.property || "text";
35     var sortType = this.sortType;
36     var fs = this.folderSort;
37     var cs = this.caseSensitive === true;
38     var leafAttr = this.leafAttr || 'leaf';
39
40     this.sortFn = function(n1, n2){
41         if(fs){
42             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
43                 return 1;
44             }
45             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
46                 return -1;
47             }
48         }
49         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
50         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
51         if(v1 < v2){
52                         return dsc ? +1 : -1;
53                 }else if(v1 > v2){
54                         return dsc ? -1 : +1;
55         }else{
56                 return 0;
57         }
58     };
59 };
60
61 Roo.tree.TreeSorter.prototype = {
62     doSort : function(node){
63         node.sort(this.sortFn);
64     },
65     
66     compareNodes : function(n1, n2){
67         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
68     },
69     
70     updateSort : function(tree, node){
71         if(node.childrenRendered){
72             this.doSort.defer(1, this, [node]);
73         }
74     }
75 };