import { Component , OnInit , Input , OnDestroy } from '@angular/core' ; import { Subscription } from 'rxjs' ; import { ScssHelper } from '../../scss/scss-helper' ; import { BreakpointHelperService } from './breakpoint-helper.service' ; import { GridCardConfiguration } from './grid-card-configuration' ; class GridCard { configuration : GridCardConfiguration ; row : number ; col : number ; colSpan : number ; constructor ( configuration , row , col , colSpan ) { this . configuration = configuration ; this . row = row ; this . col = col ; this . colSpan = colSpan ; } } @ Component ( { selector : 'kirby-grid' , templateUrl : './grid.component.html' , styleUrls : [ './grid.component.scss' ] , host : { '[attr.max-columns]' : 'maxColumns' } , } ) export class GridComponent implements OnInit , OnDestroy { cardConfigs : GridCardConfiguration [ ] ; cards : GridCard [ ] = [ ] ; private breakpointSubscription : Subscription ; @ Input ( ) maxColumns : number ; @ Input ( ) set cardConfigurations ( cardConfigurations ) { this . cardConfigs = cardConfigurations ; this . configureGrid ( ) ; } constructor ( private breakpointHelper ) { } configureGrid ( ) { let calculatedMaxColumns = 0 ; if ( this . maxColumns === undefined ) { calculatedMaxColumns = this . breakpointHelper . currentScreenWidth >= ScssHelper . BREAKPOINT_SCREEN_L ? 2 : 1 ; } else { calculatedMaxColumns = this . maxColumns ; } this . cards = [ ] ; let columnCounter = 0 ; let currentRow = 0 ; let currentColumn = 0 ; this . cardConfigs . forEach ( ( card , index ) => { columnCounter += card . preferredSize ; if ( calculatedMaxColumns === 1 ) { this . cards . push ( new GridCard ( card , currentRow , currentColumn , 1 ) ) ; currentRow += 1 ; return ; } if ( columnCounter <= calculatedMaxColumns ) { this . cards . push ( new GridCard ( card , currentRow , currentColumn , card . preferredSize ) ) ; currentColumn += card . preferredSize ; } else { const restColumns = calculatedMaxColumns - ( columnCounter - card . preferredSize ) ; const prevCard = this . cards [ index - 1 ] ; prevCard . colSpan = restColumns + prevCard . colSpan ; currentRow += 1 ; currentColumn = 0 ; this . cards . push ( new GridCard ( card , currentRow , currentColumn , card . preferredSize ) ) ; currentColumn = card . preferredSize ; columnCounter = card . preferredSize ; } if ( this . cardConfigs . length - 1 === index ) { const restColumns = calculatedMaxColumns - columnCounter ; const currentCard = this . cards [ index ] ; currentCard . colSpan += restColumns ; } } ) ; } ngOnInit ( ) { } ngOnDestroy ( ) { if ( this . breakpointSubscription ) { this . breakpointSubscription . unsubscribe ( ) ; } } }