summaryrefslogtreecommitdiffstats
path: root/usecaseui-portal/src/app/shared/components/description/description.component.ts
blob: 6f3469d96688385cbf1bb1d6f3d98b17ea1eeef7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Component, ContentChildren, EventEmitter, Input, OnDestroy, OnInit, QueryList } from '@angular/core';
import { Subject } from 'rxjs';
import { DescriptionItemComponent } from './descriptions-item.component';
import { DescriptionItemRenderProps } from './description.type';
@Component({
  selector: 'app-descriptions',
  templateUrl: './description.component.html',
  styleUrls: ['./description.component.less'],
})
export class DescriptionComponent implements OnInit, OnDestroy {
  @ContentChildren(DescriptionItemComponent) items: QueryList<DescriptionItemComponent>;

  @Input() nzColumn: number = 3;
  @Input() nzTitle: string = '';
  @Input() nzColon: boolean = true;

  itemMatrix: DescriptionItemRenderProps[][] = [];
  private destroy$ = new Subject<void>();
  constructor() { }

  ngOnInit() {
  }

  ngAfterContentInit(): void {
    this.prepareMatrix();
  }


  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

   /**
   * Prepare the render matrix according to description items' spans.
   */
   private prepareMatrix(): void {
    if (!this.items) {
      return;
    }

    let currentRow: DescriptionItemRenderProps[] = [];
    let width = 0;

    const column = this.nzColumn;
    const items = this.items.toArray();
    const length = items.length;
    const matrix: DescriptionItemRenderProps[][] = [];
    const flushRow = (): void => {
      matrix.push(currentRow);
      currentRow = [];
      width = 0;
    };

    for (let i = 0; i < length; i++) {
      const item = items[i];
      const { nzTitle: title, content, nzSpan: span } = item;

      width += span;

      if (width >= column) {
        if (width > column) {
          console.warn(`"nzColumn" is ${column} but we have row length ${width}`);
          flushRow();
        }
        currentRow.push({ title, content, span });
        flushRow();
      } else if (i === length - 1) {
        currentRow.push({ title, content, span: column - (width - span) });
        flushRow();
      } else {
        currentRow.push({ title, content, span });
      }
    }

    this.itemMatrix = matrix;
  }

}