Fix #6662 - support header image in square
[roojs1] / Roo / bootstrap / Card.js
1 /*
2  *  - LGPL
3  *
4  *  This is BS4's Card element.. - similar to our containers probably..
5  * 
6  */
7 /**
8  * @class Roo.bootstrap.Card
9  * @extends Roo.bootstrap.Component
10  * Bootstrap Card class
11  *
12  *
13  * possible... may not be implemented..
14  * @cfg {String} header_image  src url of image.
15  * @cfg {String|Object} header
16  * @cfg {Number} header_size (0|1|2|3|4|5) H1 or H2 etc.. 0 indicates default
17  * @cfg {Number} header_weight  (primary|secondary|success|info|warning|danger|light|dark)
18  * 
19  * @cfg {String} title
20  * @cfg {String} subtitle
21  * @cfg {String|Boolean} html -- html contents - or just use children.. use false to hide it..
22  * @cfg {String} footer
23  
24  * @cfg {String} weight (primary|warning|info|danger|secondary|success|light|dark)
25  * 
26  * @cfg {String} margin (0|1|2|3|4|5|auto)
27  * @cfg {String} margin_top (0|1|2|3|4|5|auto)
28  * @cfg {String} margin_bottom (0|1|2|3|4|5|auto)
29  * @cfg {String} margin_left (0|1|2|3|4|5|auto)
30  * @cfg {String} margin_right (0|1|2|3|4|5|auto)
31  * @cfg {String} margin_x (0|1|2|3|4|5|auto)
32  * @cfg {String} margin_y (0|1|2|3|4|5|auto)
33  *
34  * @cfg {String} padding (0|1|2|3|4|5)
35  * @cfg {String} padding_top (0|1|2|3|4|5)next_to_card
36  * @cfg {String} padding_bottom (0|1|2|3|4|5)
37  * @cfg {String} padding_left (0|1|2|3|4|5)
38  * @cfg {String} padding_right (0|1|2|3|4|5)
39  * @cfg {String} padding_x (0|1|2|3|4|5)
40  * @cfg {String} padding_y (0|1|2|3|4|5)
41  *
42  * @cfg {String} display (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
43  * @cfg {String} display_xs (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
44  * @cfg {String} display_sm (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
45  * @cfg {String} display_lg (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
46  * @cfg {String} display_xl (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
47  
48  * @config {Boolean} dragable  if this card can be dragged.
49  * @config {String} drag_group  group for drag
50  * @config {Boolean} dropable  if this card can recieve other cards being dropped onto it..
51  * @config {String} drop_group  group for drag
52  * 
53  * @config {Boolean} collapsable can the body be collapsed.
54  * @config {Boolean} collapsed is the body collapsed when rendered...
55  * @config {Boolean} rotateable can the body be rotated by clicking on it..
56  * @config {Boolean} rotated is the body rotated when rendered...
57  * 
58  * @constructor
59  * Create a new Container
60  * @param {Object} config The config object
61  */
62
63 Roo.bootstrap.Card = function(config){
64     Roo.bootstrap.Card.superclass.constructor.call(this, config);
65     
66     this.addEvents({
67          // raw events
68         /**
69          * @event drop
70          * When a element a card is dropped
71          * @param {Roo.bootstrap.Card} this
72          *
73          * 
74          * @param {Roo.bootstrap.Card} move_card the card being dropped?
75          * @param {String} position 'above' or 'below'
76          * @param {Roo.bootstrap.Card} next_to_card What card position is relative to of 'false' for empty list.
77         
78          */
79         'drop' : true,
80          /**
81          * @event rotate
82          * When a element a card is rotate
83          * @param {Roo.bootstrap.Element} this
84          * @param {Roo.Element} n the node being dropped?
85          * @param {Boolean} rotate status
86          */
87         'rotate' : true
88         
89     });
90 };
91
92
93 Roo.extend(Roo.bootstrap.Card, Roo.bootstrap.Component,  {
94     
95     
96     weight : '',
97     
98     margin: '', /// may be better in component?
99     margin_top: '', 
100     margin_bottom: '', 
101     margin_left: '',
102     margin_right: '',
103     margin_x: '',
104     margin_y: '',
105     
106     padding : '',
107     padding_top: '', 
108     padding_bottom: '', 
109     padding_left: '',
110     padding_right: '',
111     padding_x: '',
112     padding_y: '',
113     
114     display: '', 
115     display_xs: '', 
116     display_sm: '', 
117     display_lg: '',
118     display_xl: '',
119  
120     header_image  : '',
121     header : '',
122     header_size : 0,
123     title : '',
124     subtitle : '',
125     html : '',
126     footer: '',
127
128     collapsable : false,
129     collapsed : false,
130     rotateable : false,
131     rotated : false,
132     
133     dragable : false,
134     drag_group : false,
135     dropable : false,
136     drop_group : false,
137     childContainer : false,
138     dropEl : false, /// the dom placeholde element that indicates drop location.
139     containerEl: false, // body container
140     bodyEl: false, // card-body
141     headerContainerEl : false, //
142     headerEl : false,
143     header_imageEl : false,
144     
145     layoutCls : function()
146     {
147         var cls = '';
148         var t = this;
149         Roo.log(this.margin_bottom.length);
150         ['', 'top', 'bottom', 'left', 'right', 'x', 'y' ].forEach(function(v) {
151             // in theory these can do margin_top : ml-xs-3 ??? but we don't support that yet
152             
153             if (('' + t['margin' + (v.length ? '_' : '') + v]).length) {
154                 cls += ' m' +  (v.length ? v[0]  : '') + '-' +  t['margin' + (v.length ? '_' : '') + v];
155             }
156             if (('' + t['padding' + (v.length ? '_' : '') + v]).length) {
157                 cls += ' p' +  (v.length ? v[0]  : '') + '-' +  t['padding' + (v.length ? '_' : '') + v];
158             }
159         });
160         
161         ['', 'xs', 'sm', 'lg', 'xl'].forEach(function(v) {
162             if (('' + t['display' + (v.length ? '_' : '') + v]).length) {
163                 cls += ' d' +  (v.length ? '-' : '') + v + '-' + t['display' + (v.length ? '_' : '') + v]
164             }
165         });
166         
167         // more generic support?
168         if (this.hidden) {
169             cls += ' d-none';
170         }
171         
172         return cls;
173     },
174  
175        // Roo.log("Call onRender: " + this.xtype);
176         /*  We are looking at something like this.
177 <div class="card">
178     <img src="..." class="card-img-top" alt="...">
179     <div class="card-body">
180         <h5 class="card-title">Card title</h5>
181          <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
182
183         >> this bit is really the body...
184         <div> << we will ad dthis in hopefully it will not break shit.
185         
186         ** card text does not actually have any styling...
187         
188             <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
189         
190         </div> <<
191           <a href="#" class="card-link">Card link</a>
192           
193     </div>
194     <div class="card-footer">
195         <small class="text-muted">Last updated 3 mins ago</small>
196     </div>
197 </div>
198          */
199     getAutoCreate : function(){
200         
201         var cfg = {
202             tag : 'div',
203             cls : 'card',
204             cn : [ ]
205         };
206         
207         if (this.weight.length && this.weight != 'light') {
208             cfg.cls += ' text-white';
209         } else {
210             cfg.cls += ' text-dark'; // need as it's nested..
211         }
212         if (this.weight.length) {
213             cfg.cls += ' bg-' + this.weight;
214         }
215         
216         cfg.cls += ' ' + this.layoutCls(); 
217         
218         var hdr = false;
219         var hdr_ctr = false;
220         if (this.header.length) {
221             hdr = {
222                 tag : this.header_size > 0 ? 'h' + this.header_size : 'div',
223                 cls : 'card-header ' + (this.header_weight ? 'bg-' + this.header_weight : ''),
224                 cn : []
225             };
226             cfg.cn.push(hdr);
227             hdr_ctr = hdr;
228         } else {
229             hdr = {
230                 tag : 'div',
231                 cls : 'card-header d-none ' + (this.header_weight ? 'bg-' + this.header_weight : ''),
232                 cn : []
233             };
234             cfg.cn.push(hdr);
235             hdr_ctr = hdr;
236         }
237         if (this.collapsable) {
238             hdr_ctr = {
239             tag : 'a',
240             cls : 'd-block user-select-none',
241             cn: [
242                     {
243                         tag: 'i',
244                         cls : 'roo-collapse-toggle fa fa-chevron-down float-right ' + (this.collapsed ? 'collapsed' : '')
245                     }
246                    
247                 ]
248             };
249             hdr.cn.push(hdr_ctr);
250         }
251         
252         hdr_ctr.cn.push(        {
253             tag: 'span',
254             cls: 'roo-card-header-ctr' + ( this.header.length ? '' : ' d-none'),
255             html : this.header
256         });
257         
258         
259         if (this.header_image.length) {
260             cfg.cn.push({
261                 tag : 'img',
262                 cls : 'card-img-top',
263                 src: this.header_image // escape?
264             });
265         } else {
266             cfg.cn.push({
267                     tag : 'div',
268                     cls : 'card-img-top d-none' 
269                 });
270         }
271             
272         var body = {
273             tag : 'div',
274             cls : 'card-body' + (this.html === false  ? ' d-none' : ''),
275             cn : []
276         };
277         var obody = body;
278         if (this.collapsable || this.rotateable) {
279             obody = {
280                 tag: 'div',
281                 cls : 'roo-collapsable collapse ' + (this.collapsed || this.rotated ? '' : 'show'),
282                 cn : [  body ]
283             };
284         }
285         
286         cfg.cn.push(obody);
287         
288         if (this.title.length) {
289             body.cn.push({
290                 tag : 'div',
291                 cls : 'card-title',
292                 src: this.title // escape?
293             });
294         }  
295         
296         if (this.subtitle.length) {
297             body.cn.push({
298                 tag : 'div',
299                 cls : 'card-title',
300                 src: this.subtitle // escape?
301             });
302         }
303         
304         body.cn.push({
305             tag : 'div',
306             cls : 'roo-card-body-ctr'
307         });
308         
309         if (this.html.length) {
310             body.cn.push({
311                 tag: 'div',
312                 html : this.html
313             });
314         }
315         // fixme ? handle objects?
316         
317         if (this.footer.length) {
318            
319             cfg.cn.push({
320                 cls : 'card-footer ' + (this.rotated ? 'd-none' : ''),
321                 html : this.footer
322             });
323             
324         } else {
325             cfg.cn.push({cls : 'card-footer d-none'});
326         }
327         
328         // footer...
329         
330         return cfg;
331     },
332     
333     
334     getCardHeader : function()
335     {
336         var  ret = this.el.select('.card-header',true).first();
337         if (ret.hasClass('d-none')) {
338             ret.removeClass('d-none');
339         }
340         
341         return ret;
342     },
343     getCardFooter : function()
344     {
345         var  ret = this.el.select('.card-footer',true).first();
346         if (ret.hasClass('d-none')) {
347             ret.removeClass('d-none');
348         }
349         
350         return ret;
351     },
352     getCardImageTop : function()
353     {
354         var  ret = this.header_imageEl;
355         if (ret.hasClass('d-none')) {
356             ret.removeClass('d-none');
357         }
358             
359         return ret;
360     },
361     
362     getChildContainer : function()
363     {
364         
365         if(!this.el){
366             return false;
367         }
368         return this.el.select('.roo-card-body-ctr',true).first();    
369     },
370     
371     initEvents: function() 
372     {
373         this.bodyEl = this.el.select('.card-body',true).first(); 
374         this.containerEl = this.getChildContainer();
375         if(this.dragable){
376             this.dragZone = new Roo.dd.DragZone(this.getEl(), {
377                     containerScroll: true,
378                     ddGroup: this.drag_group || 'default_card_drag_group'
379             });
380             this.dragZone.getDragData = this.getDragData.createDelegate(this);
381         }
382         if (this.dropable) {
383             this.dropZone = new Roo.dd.DropZone(this.el.select('.card-body',true).first() , {
384                 containerScroll: true,
385                 ddGroup: this.drop_group || 'default_card_drag_group'
386             });
387             this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
388             this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
389             this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
390             this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
391             this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
392         }
393         
394         if (this.collapsable) {
395             this.el.select('.card-header',true).on('click', this.onToggleCollapse, this);
396         }
397         if (this.rotateable) {
398             this.el.select('.card-header',true).on('click', this.onToggleRotate, this);
399         }
400         this.collapsableEl = this.el.select('.roo-collapsable').first();
401          
402         this.footerEl = this.el.select('.card-footer').first();
403         this.collapsableToggleEl = this.el.select('.roo-collapse-toggle');
404         this.headerContainerEl = this.el.select('.roo-card-header-ctr').first();
405         this.headerEl = this.el.select('.card-header',true).first();
406         
407         if (this.rotated) {
408             this.el.addClass('roo-card-rotated');
409             this.fireEvent('rotate', this, true);
410         }
411         this.header_imageEl = this.el.select('.card-img-top',true).first(); 
412         this.header_imageEl.on('load', this.onHeaderImageLoad, this );
413         
414     },
415     getDragData : function(e)
416     {
417         var target = this.getEl();
418         if (target) {
419             //this.handleSelection(e);
420             
421             var dragData = {
422                 source: this,
423                 copy: false,
424                 nodes: this.getEl(),
425                 records: []
426             };
427             
428             
429             dragData.ddel = target.dom ;    // the div element
430             Roo.log(target.getWidth( ));
431             dragData.ddel.style.width = target.getWidth() + 'px';
432             
433             return dragData;
434         }
435         return false;
436     },
437     /**
438     *    Part of the Roo.dd.DropZone interface. If no target node is found, the
439     *    whole Element becomes the target, and this causes the drop gesture to append.
440     */
441     getTargetFromEvent : function(e, dragged_card_el)
442     {
443         var target = e.getTarget();
444         while ((target !== null) && (target.parentNode != this.containerEl.dom)) {
445             target = target.parentNode;
446         }
447         
448         var ret = {
449             position: '',
450             cards : [],
451             card_n : -1,
452             items_n : -1,
453             card : false 
454         };
455         
456         //Roo.log([ 'target' , target ? target.id : '--nothing--']);
457         // see if target is one of the 'cards'...
458         
459         
460         //Roo.log(this.items.length);
461         var pos = false;
462         
463         var last_card_n = 0;
464         var cards_len  = 0;
465         for (var i = 0;i< this.items.length;i++) {
466             
467             if (!this.items[i].el.hasClass('card')) {
468                  continue;
469             }
470             pos = this.getDropPoint(e, this.items[i].el.dom);
471             
472             cards_len = ret.cards.length;
473             //Roo.log(this.items[i].el.dom.id);
474             ret.cards.push(this.items[i]);
475             last_card_n  = i;
476             if (ret.card_n < 0 && pos == 'above') {
477                 ret.position = cards_len > 0 ? 'below' : pos;
478                 ret.items_n = i > 0 ? i - 1 : 0;
479                 ret.card_n  = cards_len  > 0 ? cards_len - 1 : 0;
480                 ret.card = ret.cards[ret.card_n];
481             }
482         }
483         if (!ret.cards.length) {
484             ret.card = true;
485             ret.position = 'below';
486             ret.items_n;
487             return ret;
488         }
489         // could not find a card.. stick it at the end..
490         if (ret.card_n < 0) {
491             ret.card_n = last_card_n;
492             ret.card = ret.cards[last_card_n];
493             ret.items_n = this.items.indexOf(ret.cards[last_card_n]);
494             ret.position = 'below';
495         }
496         
497         if (this.items[ret.items_n].el == dragged_card_el) {
498             return false;
499         }
500         
501         if (ret.position == 'below') {
502             var card_after = ret.card_n+1 == ret.cards.length ? false : ret.cards[ret.card_n+1];
503             
504             if (card_after  && card_after.el == dragged_card_el) {
505                 return false;
506             }
507             return ret;
508         }
509         
510         // its's after ..
511         var card_before = ret.card_n > 0 ? ret.cards[ret.card_n-1] : false;
512         
513         if (card_before  && card_before.el == dragged_card_el) {
514             return false;
515         }
516         
517         return ret;
518     },
519     
520     onNodeEnter : function(n, dd, e, data){
521         return false;
522     },
523     onNodeOver : function(n, dd, e, data)
524     {
525        
526         var target_info = this.getTargetFromEvent(e,data.source.el);
527         if (target_info === false) {
528             this.dropPlaceHolder('hide');
529             return false;
530         }
531         Roo.log(['getTargetFromEvent', target_info ]);
532         
533          
534         this.dropPlaceHolder('show', target_info,data);
535         
536         return false; 
537     },
538     onNodeOut : function(n, dd, e, data){
539         this.dropPlaceHolder('hide');
540      
541     },
542     onNodeDrop : function(n, dd, e, data)
543     {
544         
545         // call drop - return false if
546         
547         // this could actually fail - if the Network drops..
548         // we will ignore this at present..- client should probably reload
549         // the whole set of cards if stuff like that fails.
550         
551         
552         var info = this.getTargetFromEvent(e,data.source.el);
553         if (info === false) {
554             return false;
555         }
556         this.dropPlaceHolder('hide');
557   
558          
559     
560     
561     
562         this.acceptCard(data.source, info.position, info.card, info.items_n);
563         return true;
564          
565     },
566     firstChildCard : function()
567     {
568         for (var i = 0;i< this.items.length;i++) {
569             
570             if (!this.items[i].el.hasClass('card')) {
571                  continue;
572             }
573             return this.items[i];
574         }
575         return this.items.length ? this.items[this.items.length-1] : false; // don't try and put stuff after the cards...
576     },
577     /**
578      * accept card
579      *
580      * -        card.acceptCard(move_card, info.position, info.card, info.items_n);
581      */
582     acceptCard : function(move_card,  position, next_to_card )
583     {
584         if (this.fireEvent("drop", this, move_card, position, next_to_card) === false) {
585             return false;
586         }
587         
588         var to_items_n = next_to_card ? this.items.indexOf(next_to_card) : 0;
589         
590         move_card.parent().removeCard(move_card);
591         
592         
593         var dom = move_card.el.dom;
594         dom.style.width = ''; // clear with - which is set by drag.
595         
596         if (next_to_card !== false && next_to_card !== true && next_to_card.el.dom.parentNode) {
597             var cardel = next_to_card.el.dom;
598             
599             if (position == 'above' ) {
600                 cardel.parentNode.insertBefore(dom, cardel);
601             } else if (cardel.nextSibling) {
602                 cardel.parentNode.insertBefore(dom,cardel.nextSibling);
603             } else {
604                 cardel.parentNode.append(dom);
605             }
606         } else {
607             // card container???
608             this.containerEl.dom.append(dom);
609         }
610         
611         //FIXME HANDLE card = true 
612         
613         // add this to the correct place in items.
614         
615         // remove Card from items.
616         
617        
618         if (this.items.length) {
619             var nitems = [];
620             //Roo.log([info.items_n, info.position, this.items.length]);
621             for (var i =0; i < this.items.length; i++) {
622                 if (i == to_items_n && position == 'above') {
623                     nitems.push(move_card);
624                 }
625                 nitems.push(this.items[i]);
626                 if (i == to_items_n && position == 'below') {
627                     nitems.push(move_card);
628                 }
629             }
630             this.items = nitems;
631             Roo.log(this.items);
632         } else {
633             this.items.push(move_card);
634         }
635         
636         move_card.parentId = this.id;
637         
638         return true;
639         
640         
641     },
642     removeCard : function(c)
643     {
644         this.items = this.items.filter(function(e) { return e != c });
645  
646         var dom = c.el.dom;
647         dom.parentNode.removeChild(dom);
648         dom.style.width = ''; // clear with - which is set by drag.
649         c.parentId = false;
650         
651     },
652     
653     /**    Decide whether to drop above or below a View node. */
654     getDropPoint : function(e, n, dd)
655     {
656         if (dd) {
657              return false;
658         }
659         if (n == this.containerEl.dom) {
660             return "above";
661         }
662         var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
663         var c = t + (b - t) / 2;
664         var y = Roo.lib.Event.getPageY(e);
665         if(y <= c) {
666             return "above";
667         }else{
668             return "below";
669         }
670     },
671     onToggleCollapse : function(e)
672         {
673         if (this.collapsed) {
674             this.el.select('.roo-collapse-toggle').removeClass('collapsed');
675             this.collapsableEl.addClass('show');
676             this.collapsed = false;
677             return;
678         }
679         this.el.select('.roo-collapse-toggle').addClass('collapsed');
680         this.collapsableEl.removeClass('show');
681         this.collapsed = true;
682         
683     
684     },
685     
686     onToggleRotate : function(e)
687     {
688         this.collapsableEl.removeClass('show');
689         this.footerEl.removeClass('d-none');
690         this.el.removeClass('roo-card-rotated');
691         this.el.removeClass('d-none');
692         if (this.rotated) {
693             
694             this.collapsableEl.addClass('show');
695             this.rotated = false;
696             this.fireEvent('rotate', this, this.rotated);
697             return;
698         }
699         this.el.addClass('roo-card-rotated');
700         this.footerEl.addClass('d-none');
701         this.el.select('.roo-collapsable').removeClass('show');
702         
703         this.rotated = true;
704         this.fireEvent('rotate', this, this.rotated);
705     
706     },
707     
708     dropPlaceHolder: function (action, info, data)
709     {
710         if (this.dropEl === false) {
711             this.dropEl = Roo.DomHelper.append(this.containerEl, {
712             cls : 'd-none'
713             },true);
714         }
715         this.dropEl.removeClass(['d-none', 'd-block']);        
716         if (action == 'hide') {
717             
718             this.dropEl.addClass('d-none');
719             return;
720         }
721         // FIXME - info.card == true!!!
722         this.dropEl.dom.parentNode.removeChild(this.dropEl.dom);
723         
724         if (info.card !== true) {
725             var cardel = info.card.el.dom;
726             
727             if (info.position == 'above') {
728                 cardel.parentNode.insertBefore(this.dropEl.dom, cardel);
729             } else if (cardel.nextSibling) {
730                 cardel.parentNode.insertBefore(this.dropEl.dom,cardel.nextSibling);
731             } else {
732                 cardel.parentNode.append(this.dropEl.dom);
733             }
734         } else {
735             // card container???
736             this.containerEl.dom.append(this.dropEl.dom);
737         }
738         
739         this.dropEl.addClass('d-block roo-card-dropzone');
740         
741         this.dropEl.setHeight( Roo.get(data.ddel).getHeight() );
742         
743         
744     
745     
746     
747     },
748     setHeaderText: function(html)
749     {
750         this.header = html;
751         if (this.headerContainerEl) {
752             this.headerContainerEl.dom.innerHTML = html;
753         }
754     },
755     onHeaderImageLoad : function(ev, he)
756     {
757         if (!this.header_image_fit_square) {
758             return;
759         }
760         
761         var hw = he.naturalHeight / he.naturalWidth;
762         // wide image = < 0
763         // tall image = > 1
764         //var w = he.dom.naturalWidth;
765         var ww = he.width;
766         he.style.left =  0;
767         he.style.position =  'relative';
768         if (hw > 1) {
769             var nw = (ww * (1/hw));
770             Roo.get(he).setSize( ww * (1/hw),  ww);
771             he.style.left =  ((ww - nw)/ 2) + 'px';
772             he.style.position =  'relative';
773         }
774
775     }
776
777     
778 });
779