730306beee3c860a7872e4223b4cfcd7c4929542
[Pman.Builder] / Pman.Builder.Tree.js
1 /**
2  * The code that manages the tree...
3  *
4  * used to be inside the Interface, but has proved to be to difficult to manage.
5  *
6  * In principle, simple event handling code is put in the interface, and any hard
7  * lifting is done in nice files...
8  *
9  * It might be better to just extend 'tree', and use the extended class..
10  * 
11  */
12
13 Pman.Builder.Tree = {
14     
15     currentNode: false,
16     dragProp: '',
17     
18     appendNode : function(parent, inConfig, point) {
19                                 
20                                     
21         var tree = Pman.Tab.BuilderTree.tree;
22         
23         if (typeof(inConfig) == 'undefined') {
24             return;
25         }
26         var items = [];
27         if (typeof(inConfig) !== 'undefined' && inConfig.items) { // loading!
28             items = inConfig.items;
29             delete inConfig.items;
30         }
31         
32         var config = this.cloneConfig(inConfig);
33         
34         var hidden =  config['builder.hidden'] || false;
35          
36         if (!parent) {
37             parent = tree.root;
38         }
39               
40         var newNode = new Roo.tree.TreeNode({
41             text: this.configToText(config)
42         });
43               
44         newNode.elConfig = config;
45         
46         //if (markUndo === true) {
47         //Pman.Tab.Builder.markUndo("Add " + newNode.text);
48         //
49             // appends to our tree...
50         console.log("APPEND NODE: " + point);    
51         switch(point) {
52             case 'above':
53                 parent.parentNode.insertBefore(newNode, parent);
54                 parent.parentNode.expand(true);
55                 break;
56             case 'below':
57                 // if it's the last node.. then we append..
58                 var ix = parent.parentNode.indexOf(parent) + 1;
59                 if (parent.parentNode.childNodes.length == ix) {
60                      parent.parentNode.appendChild(newNode);
61                      break;
62                 }
63                 var bef = parent.parentNode.childNodes[ix];
64                 parent.parentNode.insertBefore(newNode, bef);
65                 parent.parentNode.expand(true);
66                 break;
67             
68             case 'append':
69             default:    
70                 parent.appendChild(newNode);
71                 parent.expand(true);
72                 break;
73         }
74         
75         newNode.ui.ctNode.style.display = hidden ? 'none' : '';
76         
77         if (items.length) {
78             Roo.each(items, function(i) {
79                 this.appendNode(newNode, i);
80             },this);
81             
82         }
83             
84             
85             /*
86             -- panels with panes...
87                 if (items && items.length) {
88                         for (var i = 0; i < items.length; i++) {
89                                         this.appendConfig(items[i], newNode, false);
90                         }
91                 }
92                 if (opts.doUpdate !== false) {
93                         this.updateForm(false, newNode);
94                 }
95             */
96         return newNode;
97         
98          
99     },
100     clearAll : function() {
101         var tree = Pman.Tab.BuilderTree.tree;
102         
103         var rt = tree.root;
104          if (rt.childNodes.length) {
105             rt.removeChild(rt.childNodes[0]);
106         }
107         
108         tree.root.elConfig  = Roo.apply({ }, this.defaultElConfig());  
109         //var btop = Pman.Tab.BuilderTop;
110         //if (btop.modsel && btop.modsel.lastData) {
111         //    this.tree.root.elConfig.app = btop.modsel.lastData.app;
112         //}
113         
114         this.setCurrentNode(tree.root,true);
115         
116     },
117     cloneConfig : function(config) {
118         if (!config) { return null; }
119         var newConfig = {};
120         
121         for (var i in config) {
122             if (i.match(/^builder\./)) {
123                 continue;
124             }
125             if (typeof config[i] == 'object') {
126                  newConfig[i] = this.cloneConfig(config[i]);
127             } else if (typeof config[i] != 'function') { // should this happen?
128                  newConfig[i] = config[i];
129             }
130         }
131         return newConfig;
132     },
133     configToText : function(c) {
134          
135         var txt = [];
136         c = c || {};
137               var sr = (typeof(c['+buildershow']) != 'undefined') &&  !c['+buildershow'] ? true : false;
138             if (sr) txt.push('<s>');
139             if (typeof(c['*prop']) != 'undefined')   { txt.push(c['*prop']+ ':'); }
140         if (c.xtype)      { txt.push(c.xtype); }
141         if (c.fieldLabel) { txt.push('[' + c.fieldLabel + ']'); }
142         if (c.boxLabel)   { txt.push('[' + c.boxLabel + ']'); }
143         
144         
145         if (c.layout)     { txt.push('<i>' + c.layout + '</i>'); }
146         if (c.title)      { txt.push('<b>' + c.title + '</b>'); }
147             if (c.header)    { txt.push('<b>' + c.header + '</b>'); }
148             if (c.legend)      { txt.push('<b>' + c.legend + '</b>'); }
149         if (c.text)       { txt.push('<b>' + c.text + '</b>'); }
150             if (c.name)       { txt.push('<b>' + c.name+ '</b>'); }
151         if (c.region)     { txt.push('<i>(' + c.region + ')</i>'); }
152             if (c.dataIndex) { txt.push('[' + c.dataIndex+ ']'); }
153             if (sr) txt.push('</s>');
154         return (txt.length == 0 ? "Element" : txt.join(" "));
155         
156         
157     },
158     currentNodeType : function() {
159         return this.nodeXtype(this.currentNode);
160         
161     },
162     defaultElConfig : function() {
163         return {
164            xtype : '*top',
165             
166             module : 'TestApp',
167             part:   'Partname',
168             modkey : 0,
169             region : 'center',
170             parent : 'Pman',
171             name : 'Module Name',
172             items: [] 
173         };
174     },
175     
176     replaceCurrentNode : function(cfg)
177     {
178         var tree = Pman.Tab.BuilderTree.tree;
179
180         if (this.currentNode == tree.root) {
181             return false;
182         }
183         var pn = this.currentNode.parentNode;
184         
185         var ix = pn.indexOf(this.currentNode);
186         pn.removeChild(this.currentNode);
187           
188         if (!pn.childNodes.length) {
189             this.appendNode(pn, cfg, 'append')
190             return true;
191         }
192         if (!ix) {
193             // first..
194             this.appendNode(pn.childNodes[0], cfg, 'above');
195             return true;
196         
197         }
198         
199         this.appendNode(pn.childNodes[ix-1], cfg, 'below');
200         
201         
202         return true;
203     },
204     
205     collapseToggle : function()
206     {
207         var tree = Pman.Tab.BuilderTree.tree;
208         
209         if (this.currentNode == tree.root) {
210             return false;
211         }
212         var cfg = this.currentNode.elConfig;
213         // things that can not be deleted...
214         var hidden = cfg['builder.hidden'] || 0;
215         if (hidden) {
216             delete cfg['builder.hidden'];
217         } else {
218             cfg['builder.hidden'] = 1;
219         }
220          
221         
222         this.currentNode.ui.ctNode.style.display = !hidden ? 'none' : '';
223          
224          
225         //this.setCurrentNode(pn.childNodes.length ? pn.childNodes[ix] : pn  ,true);
226         return true;
227     },
228     
229     
230     
231     
232     deleteCurrent : function()
233     {
234         
235         var tree = Pman.Tab.BuilderTree.tree;
236         
237         if (this.currentNode == tree.root) {
238             return false;
239         }
240         var cfg = this.currentNode.elConfig;
241         // things that can not be deleted...
242         
243         
244         var pn = this.currentNode.parentNode;
245         
246         // work out if we make the next or parent the 'current node'
247         var ix = pn.indexOf(this.currentNode);
248         //  console.log(ix);
249         pn.removeChild(this.currentNode);
250         if (pn.childNodes.length) {
251             ix = Math.min(pn.childNodes.length-1, ix);
252         }
253         this.setCurrentNode(pn.childNodes.length ? pn.childNodes[ix] : pn  ,true);
254         return true;
255     },
256     dupeNode : function(node)
257     {
258             var cfg = this.cloneConfig(node.elConfig);
259             
260             var newNode = new Roo.tree.TreeNode(
261             {
262                     id: Roo.id(),
263                     text: this.configToText(cfg)
264             });
265             
266             newNode.elConfig = cfg;
267             node.eachChild(function(n) {
268                 newNode.appendChild(this.dupeNode(n));
269             },this);
270             
271             return newNode;
272                 
273     },
274     loadBJS : function(module, part)
275     {
276         var _t = this;
277         new Pman.Request({
278             url : baseURL + '/Roo/Builder_part.php',
279             method : 'GET',
280             params : {
281                _id : part
282             },
283             success : function(res)         
284             {
285                 // data is in.. 
286                 Roo.log(res);
287                 
288                 if (!res.data.json.length) {
289                     var cfg = _t.defaultElConfig();
290                     cfg.name = Pman.Tab.BuilderTop.filesel.lastData.name;
291                     cfg.part = Pman.Tab.BuilderTop.filesel.lastData.name;
292                     cfg.module = '';
293                     _t.loadTree(cfg);
294                     return;
295                 
296                 }
297                 
298                 _t.loadTree(JSON.parse(res.data.json));
299                 
300              
301             }
302         
303          })  
304             
305         
306         
307     },
308     loadTree : function(o)
309     {
310         var tree = Pman.Tab.BuilderTree.tree;
311         this.clearAll();
312         tree.root.elConfig = o;
313         if (typeof(o.xtype) == 'undefined') {
314             o.xtype = '*top';
315         }
316         tree.root.setText(this.configToText(tree.root.elConfig));
317         this.appendNode(tree.root, o.items[0]);
318         tree.root.expand(true);
319         Pman.Tab.BuilderView.panel.redraw();
320         this.setCurrentNode(tree.root,true);
321     },
322     nodeXtype : function(n)
323     {
324         var tree = Pman.Tab.BuilderTree.tree;
325         if (!n || !n.elConfig) {return ''; }
326         var xt = n.elConfig.xtype ||  '';
327         var xns= n.elConfig['|xns'] ||   '';
328         xns += xns.length ? '.' : '';
329         return xns + xt;
330     },
331     setCurrentNode : function(node,select)
332     {
333         var tree = Pman.Tab.BuilderTree.tree;
334         
335         this.currentNode = node || tree.root;
336             
337         //Pman.Tab.BuilderView.highlightElement(this.currentNode);
338     
339         var p = Pman.Tab.BuilderProps.grid;
340         if (p) { //may not be ready yet..
341             p.setCurrrentNode(this.currentNode);
342         }
343         
344       
345         this.currentNode.setText(this.configToText(this.currentNode.elConfig));
346         
347         if (select) { //&& node !== this.tree.root) {
348             if (this.currentNode !== tree.root)  {
349                      this.currentNode.ensureVisible();
350               }   
351              this.currentNode.expand(false,false);
352             this.currentNode.select();
353         }
354         // update palete..
355         Pman.Tab.BuilderPalette.grid.getSelectionModel().clearSelections();
356         Pman.Tab.BuilderPalette.grid.view.refresh();
357         
358     },
359     toJS : function(n)
360     {
361         if (!n) {
362             var tree = Pman.Tab.BuilderTree.tree;
363             return this.toJS(tree.root);
364         }
365         var _this = this;
366         var ret = this.cloneConfig(n.elConfig);
367         if (n.childNodes.length) {
368             ret.items = [];
369             n.eachChild(function(cn) {
370                 ret.items.push(_this.toJS(cn));
371             });
372                 
373         }
374         return ret;
375           
376          
377     },
378     
379     /**
380      * handle dropNode
381      */
382     
383     handleDropNode : function (e)
384     {
385         // nodedragover handles the allow/disallow..
386         
387         /*
388         tree - The TreePanel
389         target - The node being targeted for the drop
390         data - The drag data from the drag source
391         point - The point of the drop - append, above or below
392         source - The drag source
393         rawEvent - Raw mouse event
394         dropNode - Drop node(s) provided by the source OR you can supply node(s) to be inserted by setting them on this object.
395         cancel - Set this to true to cancel the drop.
396         */
397         
398         var _t = this;
399         var np = e.point == 'append' ? e.target : e.target.parentNode ; // new parent
400           
401         if (!e.tree || !e.dropNode) {
402         
403             // form palete...
404             var data  = e.source.dragData.selections[0].data;
405     
406             var xar = data.name.split('.');
407     
408             var cfg = {
409                 'xtype' : xar.pop(),
410                 '|xns' : xar.join('.')
411                 
412             };
413             if (this.dragProp.length > 1) {
414                 cfg['*prop'] = this.dragProp;
415             }
416             // at this point it should of a set of options...
417              var cls = cfg['|xns'] + '.' + cfg['xtype'];
418                 
419     
420             if (typeof(Pman.Builder.Wizard[cls]) != 'undefined') {
421                 Pman.Dialog.BuilderAdd.show( cfg , function(fdata ) {
422      
423                     _t.appendNode(e.target, fdata , e.point);
424                      Pman.Tab.BuilderView.panel.redraw();
425              
426                  });
427                  return false;
428              }
429              this.appendNode(e.target, cfg, e.point);
430               Pman.Tab.BuilderView.panel.redraw();
431              
432             return false; // fixme drop of elements from palete..
433         }
434     
435         // always drop onto own parent
436         if (np == e.dropNode.parentNode) {
437             if (e.rawEvent.ctrlKey) {
438                 e.dropNode = this.dupeNode(e.dropNode);
439             }
440             return true;
441         }
442         // can append has to use palete...
443         // this code should be in nodedragover.
444         if (e.dropNode) {
445             var cfg = this.toJS(e.dropNode);
446             this.appendNode(e.target, cfg, e.point);
447         }
448         Roo.log('no e.dropNode?');
449         return false; // do not allow movement..
450         
451         if (_this.canAppend(np, e.dropNode.elConfig)) {
452             if (e.rawEvent.ctrlKey) {
453                 e.dropNode = _this.dupeNode(e.dropNode);
454                   
455                 if (np.elConfig.xtype == 'GridEditor') {
456                     e.dropNode.elConfig['*prop'] = 'field';
457                 }
458                 
459             }
460             return true;
461         }  
462         Roo.log('can not drop ' + e.dropNode.elConfig.xtype + ' ontop of ' + np.elConfig.xtype);
463         
464         
465         
466         return false;
467                             
468     
469     },
470     handleDragOver : function(e)
471     {
472         Roo.log('nodedragover');
473         Roo.log(e);
474         // e.cancel..
475         // if we have within the same tree:
476           // dropNode (the node being dragged !!important!!) 
477           // point: below, append
478           // target - node 
479        // for palete
480            // dropNode = false;
481            // grid = the grid...
482            // source.dragData.selections[..] 
483       
484        
485        // we can only check parents... (we in theory can check dupe properties.. but let's ignore that for the time being.)
486        
487        // ok off we go.
488        
489        if (!e.dropNode) {
490            // drag from palete..
491            if (!e.source.dragData.selections.length) {
492                e.cancel = true;
493                return;
494            }
495            var drop_rec = e.source.dragData.selections[0];
496            var drop_xtype = drop_rec.data.name;
497            var ok_parents = drop_rec.json.parents;
498            
499            Roo.log("TEST PARENTS: " + ok_parents.join(', '));
500            var new_parent = this.nodeXtype((e.point == 'append') ? e.target :  e.target.parentNode);
501            Roo.log("NEW PARENT: " + e.point + " = " + new_parent);
502            
503            // see if the new_parent is actually in the list of ok_parents
504            e.cancel = true;
505            this.dragProp = '';
506            var _t = this;
507            Roo.each(ok_parents, function(n) {
508                 Roo.log("compare "+n+" ? " + new_parent);
509                 if (n == new_parent || n.split(':').shift() == new_parent) {
510                    Roo.log("got match!");
511                    e.cancel = false;
512                    _t.dragProp = (n == new_parent) ?  '' : n.split(':').pop();
513                    return true;
514                 }
515                return null;
516             });
517    
518            // done all the checks...
519            return;
520            
521         }
522         
523         
524         // have a drop node - hence comming from the same object..
525         var drop_xtype = this.nodeXtype(e.dropNode);
526         // currently we can not determine validity..
527         e.cancel = false;
528         return ;
529         
530         
531         
532     },
533     save : function() 
534     {
535        // first see if first element has a name.. - we can not save otherwise..
536         var t = Pman.Tab.BuilderTree.tree;
537         if (!t.root.elConfig.name.length) {
538             Roo.MessageBox.alert("Error", "No name set for form");
539             return;
540         }
541      
542         var  sid = (typeof(sid) == 'undefined') ? 
543              (Pman.Tab.BuilderTop.filesel.lastData ? Pman.Tab.BuilderTop.filesel.lastData.id : 0) : sid;
544         
545
546         var js = this.toJS();
547         var render = new Pman.Builder.JsRender(js); 
548          
549         // console.log(js);
550         // console.log(json);
551         
552         // check the select box to see if that has been set... - save it with that id..
553         
554         //var _this = this;
555         
556         Pman.request({
557             url: baseURL + '/Roo/Builder_part.php',
558             method : 'POST',
559             params : {
560                 json : Roo.encode(js, null, 4),
561                 jsource : render.toSource(),
562                 name :   js.name,
563                 module_id : Pman.Tab.BuilderTop.modsel.getValue(),
564                 id : sid
565             }, 
566             success : function(data) {
567                 // set the fileSel!!
568                 console.log(data);
569                 //if (data) {
570                 //    _this.filesel.setFromData(data);
571 //                    if (cb) {
572 //                        cb.call(_this,data);
573   //                  }
574 //                    _this.postCode(data);
575 //                }
576             }
577         });
578 }
579
580     
581     
582 }