• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

atinc / ngx-tethys / 17e94a41-8b9f-4dec-b3e2-d358f8184f00

24 Aug 2023 11:23AM UTC coverage: 90.132% (+0.08%) from 90.055%
17e94a41-8b9f-4dec-b3e2-d358f8184f00

push

circleci

web-flow
feat(table): replace loading with skeleton and make skeleton stronger #INFR-9201 (#2799)

5121 of 6335 branches covered (80.84%)

Branch coverage included in aggregate %.

33 of 33 new or added lines in 4 files covered. (100.0%)

12936 of 13699 relevant lines covered (94.43%)

976.04 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.27
/src/table/table.component.ts
1
import {
2
    Constructor,
3
    InputBoolean,
4
    InputCssPixel,
5
    InputNumber,
6
    MixinBase,
7
    mixinUnsubscribe,
8
    ThyUnsubscribe,
9
    UpdateHostClassService
10
} from 'ngx-tethys/core';
11
import { Dictionary, SafeAny } from 'ngx-tethys/types';
12
import { coerceBooleanProperty, get, helpers, isString, keyBy, set } from 'ngx-tethys/util';
13
import { EMPTY, fromEvent, merge, Observable, of } from 'rxjs';
14
import { delay, startWith, switchMap, takeUntil } from 'rxjs/operators';
15

16
import { CdkDrag, CdkDragDrop, CdkDragEnd, CdkDragStart, CdkDropList, moveItemInArray } from '@angular/cdk/drag-drop';
17
import { ViewportRuler } from '@angular/cdk/overlay';
18
import { normalizePassiveListenerOptions } from '@angular/cdk/platform';
19
import { DOCUMENT, isPlatformServer, NgClass, NgFor, NgIf, NgTemplateOutlet, NgStyle } from '@angular/common';
20
import {
21
    AfterViewInit,
22
    ChangeDetectorRef,
23
    Component,
24
    ContentChild,
25
    ContentChildren,
26
    ElementRef,
27
    EventEmitter,
1✔
28
    HostBinding,
1✔
29
    Inject,
1✔
30
    Input,
2✔
31
    IterableChangeRecord,
1✔
32
    IterableChanges,
33
    IterableDiffer,
34
    IterableDiffers,
35
    NgZone,
36
    OnChanges,
1✔
37
    OnDestroy,
38
    OnInit,
39
    Output,
40
    PLATFORM_ID,
41
    QueryList,
42
    Renderer2,
1✔
43
    SimpleChanges,
44
    TemplateRef,
45
    ViewChild,
46
    ViewChildren,
47
    ViewEncapsulation
48
} from '@angular/core';
1✔
49

1✔
50
import { IThyTableColumnParentComponent, THY_TABLE_COLUMN_PARENT_COMPONENT, ThyTableColumnComponent } from './table-column.component';
51
import {
52
    PageChangedEvent,
53
    ThyMultiSelectEvent,
54
    ThyPage,
55
    ThyRadioSelectEvent,
1✔
56
    ThySwitchEvent,
57
    ThyTableSkeletonColumn,
148✔
58
    ThyTableDraggableEvent,
59
    ThyTableEmptyOptions,
60
    ThyTableEvent,
66!
61
    ThyTableRowEvent,
62
    ThyTableSortDirection,
63
    ThyTableSortEvent
60!
64
} from './table.interface';
65
import { TableRowDragDisabledPipe } from './pipes/drag.pipe';
66
import { TableIsValidModelValuePipe } from './pipes/table.pipe';
57✔
67
import { ThyPaginationComponent } from 'ngx-tethys/pagination';
68
import { ThyTableSkeletonComponent } from './table-skeleton.component';
69
import { ThyEmptyComponent } from 'ngx-tethys/empty';
70!
70
import { ThySwitchComponent } from 'ngx-tethys/switch';
71
import { FormsModule } from '@angular/forms';
72
import { ThyDragDropDirective, ThyContextMenuDirective } from 'ngx-tethys/shared';
56✔
73
import { ThyIconComponent } from 'ngx-tethys/icon';
3✔
74
import { CdkScrollable } from '@angular/cdk/scrolling';
75
import { ThyTableColumnSkeletonType } from './enums';
76

77
export type ThyTableTheme = 'default' | 'bordered' | 'boxed';
67✔
78

67✔
79
export type ThyTableMode = 'list' | 'group' | 'tree';
67✔
80

67✔
81
export type ThyTableSize = 'md' | 'sm' | 'xs' | 'lg' | 'xlg' | 'default';
1✔
82

83
export enum ThyFixedDirection {
84
    left = 'left',
85
    right = 'right'
45!
86
}
45✔
87

88
interface ThyTableGroup<T = unknown> {
89
    id?: string;
50✔
90
    expand?: boolean;
50✔
91
    children?: object[];
92
    origin?: T;
93
}
48✔
94

45✔
95
const tableThemeMap = {
45!
96
    default: 'table-default',
×
97
    bordered: 'table-bordered',
98
    boxed: 'table-boxed'
99
};
45✔
100

101
const customType = {
45✔
102
    index: 'index',
45✔
103
    checkbox: 'checkbox',
104
    radio: 'radio',
105
    switch: 'switch'
45✔
106
};
107

108
const css = {
45✔
109
    tableBody: 'thy-table-body',
110
    tableScrollLeft: 'thy-table-scroll-left',
111
    tableScrollRight: 'thy-table-scroll-right',
45✔
112
    tableScrollMiddle: 'thy-table-scroll-middle'
113
};
114

44✔
115
const passiveEventListenerOptions = normalizePassiveListenerOptions({ passive: true });
116

117
const _MixinBase: Constructor<ThyUnsubscribe> & typeof MixinBase = mixinUnsubscribe(MixinBase);
64✔
118

64✔
119
/**
1✔
120
 * 表格组件
121
 * @name thy-table
122
 * @order 10
123
 */
55✔
124
@Component({
125
    selector: 'thy-table',
126
    templateUrl: './table.component.html',
55✔
127
    providers: [
128
        {
129
            provide: THY_TABLE_COLUMN_PARENT_COMPONENT,
55✔
130
            useExisting: ThyTableComponent
131
        },
132
        UpdateHostClassService
45✔
133
    ],
3✔
134
    encapsulation: ViewEncapsulation.None,
135
    host: {
45✔
136
        class: 'thy-table',
137
        '[class.thy-table-bordered]': `theme === 'bordered'`,
138
        '[class.thy-table-boxed]': `theme === 'boxed'`,
1✔
139
        '[class.thy-table-fixed-header]': 'thyHeaderFixed'
140
    },
141
    standalone: true,
44✔
142
    imports: [
143
        CdkScrollable,
144
        NgClass,
66!
145
        NgFor,
66✔
146
        NgIf,
66✔
147
        NgTemplateOutlet,
367✔
148
        ThyIconComponent,
149
        ThyDragDropDirective,
66✔
150
        CdkDropList,
66✔
151
        CdkDrag,
152
        ThyContextMenuDirective,
153
        NgStyle,
154
        FormsModule,
70✔
155
        ThySwitchComponent,
70✔
156
        ThyEmptyComponent,
70✔
157
        ThyTableSkeletonComponent,
70✔
158
        ThyPaginationComponent,
70✔
159
        TableIsValidModelValuePipe,
70✔
160
        TableRowDragDisabledPipe
70✔
161
    ]
70✔
162
})
70✔
163
export class ThyTableComponent extends _MixinBase implements OnInit, OnChanges, AfterViewInit, OnDestroy, IThyTableColumnParentComponent {
70✔
164
    public customType = customType;
70✔
165

70✔
166
    public model: object[] = [];
70✔
167

70✔
168
    public groups: ThyTableGroup[] = [];
70✔
169

70✔
170
    public rowKey = '_id';
70✔
171

70✔
172
    public groupBy: string;
70✔
173

70✔
174
    public mode: ThyTableMode = 'list';
70✔
175

70✔
176
    public theme: ThyTableTheme = 'default';
70✔
177

70✔
178
    public className = '';
70✔
179

70✔
180
    public size: ThyTableSize = 'md';
70✔
181

70✔
182
    public rowClassName: string | Function;
70✔
183

70✔
184
    public loadingDone = true;
70✔
185

70✔
186
    public loadingText: string;
70✔
187

70✔
188
    public emptyOptions: ThyTableEmptyOptions = {};
70✔
189

384✔
190
    public draggable = false;
70✔
191

192
    public selectedRadioRow: SafeAny = null;
193

194
    public pagination: ThyPage = { index: 1, size: 20, total: 0, sizeOptions: [20, 50, 100] };
195

70✔
196
    public trackByFn: SafeAny;
70✔
197

70✔
198
    public wholeRowSelect = false;
70✔
199

70✔
200
    public fixedDirection = ThyFixedDirection;
70✔
201

70✔
202
    public hasFixed = false;
70✔
203

70✔
204
    public columns: ThyTableColumnComponent[] = [];
70✔
205

206
    private _diff: IterableDiffer<SafeAny>;
70✔
207

70✔
208
    private initialized = false;
70✔
209

70✔
210
    private _oldThyClassName = '';
70✔
211

70✔
212
    private scrollClassName = css.tableScrollLeft;
×
213

214
    private get tableScrollElement(): HTMLElement {
70✔
215
        return this.elementRef.nativeElement.getElementsByClassName(css.tableBody)[0] as HTMLElement;
216
    }
217

374✔
218
    private get scroll$() {
65✔
219
        return merge(this.tableScrollElement ? fromEvent<MouseEvent>(this.tableScrollElement, 'scroll') : EMPTY);
220
    }
66✔
221

222
    /**
223
     * 设置数据为空时展示的模板
377✔
224
     * @type TemplateRef
66✔
225
     */
4✔
226
    @ContentChild('empty') emptyTemplate: TemplateRef<SafeAny>;
4✔
227

228
    @ViewChild('table', { static: true }) tableElementRef: ElementRef<SafeAny>;
377✔
229

66✔
230
    @ViewChildren('rows', { read: ElementRef }) rows: QueryList<ElementRef<HTMLElement>>;
1✔
231

1!
232
    /**
233
     * 表格展示方式,列表/分组/树
234
     * @type list | group | tree
235
     * @default list
133✔
236
     */
731✔
237
    @Input()
2,097✔
238
    set thyMode(value: ThyTableMode) {
2,097✔
239
        this.mode = value || this.mode;
240
    }
241

242
    /**
243
     * thyMode的值为 `group` 时分组的 Key
2,097✔
244
     */
504✔
245
    @Input()
246✔
246
    set thyGroupBy(value: string) {
246✔
247
        this.groupBy = value;
248
    }
504✔
249

6!
250
    /**
×
251
     * 设置每行数据的唯一标识属性名
252
     * @default _id
253
     */
254
    @Input()
255
    set thyRowKey(value: SafeAny) {
256
        this.rowKey = value || this.rowKey;
2,132✔
257
    }
356✔
258

259
    /**
260
     * 分组数据源
261
     */
369✔
262
    @Input()
35✔
263
    set thyGroups(value: SafeAny) {
264
        if (this.mode === 'group') {
265
            this.buildGroups(value);
266
        }
78✔
267
    }
62✔
268

369✔
269
    /**
270
     * 数据源
271
     */
272
    @Input()
273
    set thyModel(value: SafeAny) {
70✔
274
        this.model = value || [];
634!
275
        this._diff = this._differs.find(this.model).create();
276
        this._initializeDataModel();
277

278
        if (this.mode === 'group') {
70✔
279
            this.buildModel();
363✔
280
        }
2,911✔
281
    }
589✔
282

283
    /**
284
     * 表格的显示风格,`bordered` 时头部有背景色且分割线区别明显
285
     * @type default | bordered | boxed
286
     * @default default
95✔
287
     */
161✔
288
    @Input()
90✔
289
    set thyTheme(value: ThyTableTheme) {
290
        this.theme = value || this.theme;
71✔
291
        this._setClass();
71!
292
    }
71✔
293

294
    /**
71!
295
     * 表格的大小
71✔
296
     * @type xs | sm | md | lg | xlg | default
297
     * @default md
71✔
298
     */
299
    @Input()
300
    set thySize(value: ThyTableSize) {
×
301
        this.size = value || this.size;
×
302
        this._setClass();
×
303
    }
304

305
    /**
306
     * 设置表格最小宽度,一般是适用于设置列宽为百分之或auto时限制表格最小宽度'
13,820✔
307
     */
308
    @Input()
309
    @InputCssPixel()
6,957✔
310
    thyMinWidth: string | number;
311

312
    /**
1,220✔
313
     * 设置为 fixed 布局表格,设置 fixed 后,列宽将严格按照设置宽度展示,列宽将不会根据表格内容自动调整
410✔
314
     * @default false
315
     */
810!
316
    @Input() @InputBoolean() thyLayoutFixed: boolean;
810✔
317

318
    /**
319
     * 是否表头固定,若设置为 true, 需要同步设置 thyHeight
×
320
     * @default false
321
     */
322
    @Input() @InputBoolean() thyHeaderFixed: boolean;
323

249!
324
    /**
249✔
325
     * 表格的高度
326
     */
327
    @HostBinding('style.height')
328
    @Input()
1!
329
    @InputCssPixel()
×
330
    thyHeight: string;
331

332
    /**
333
     * 设置表格的样式
1✔
334
     */
335
    @Input()
336
    set thyClassName(value: string) {
1✔
337
        const list = this.className.split(' ').filter(a => a.trim());
338
        const index: number = list.findIndex(item => item === this._oldThyClassName);
339
        if (index !== -1) {
1✔
340
            list.splice(index, 1, value);
341
        } else {
342
            list.push(value);
1✔
343
        }
1✔
344
        this._oldThyClassName = value;
345
        this.className = list.join(' ');
346
    }
2✔
347

12✔
348
    /**
349
     * 设置表格行的样式,传入函数,支持 row、index
2✔
350
     * @type string | (row, index) => string
351
     */
352
    @Input()
353
    set thyRowClassName(value: string | Function) {
354
        this.rowClassName = value;
2✔
355
    }
356

357
    /**
1✔
358
     * 设置加载状态
359
     * @default true
360
     */
361
    @Input()
1✔
362
    @InputBoolean()
363
    set thyLoadingDone(value: boolean) {
364
        this.loadingDone = value;
1✔
365
    }
366

367
    /**
368
     * 设置加载时显示的文本,已废弃
×
369
     * @deprecated
×
370
     */
×
371
    @Input()
372
    set thyLoadingText(value: string) {
373
        this.loadingText = value;
374
    }
1✔
375

376
    /**
377
     * 配置空状态组件
180✔
378
     */
379
    @Input()
380
    set thyEmptyOptions(value: ThyTableEmptyOptions) {
367✔
381
        this.emptyOptions = value;
382
    }
383

180!
384
    /**
180✔
385
     * 是否开启行拖拽
386
     * @default false
387
     */
388
    @Input()
180✔
389
    @InputBoolean()
390
    set thyDraggable(value: boolean) {
391
        this.draggable = coerceBooleanProperty(value);
392
        if ((typeof ngDevMode === 'undefined' || ngDevMode) && this.draggable && this.mode === 'tree') {
393
            throw new Error('Tree mode sorting is not supported');
394
        }
7✔
395
    }
3✔
396

397
    /**
398
     * 设置当前页码
4✔
399
     * @default 1
400
     */
401
    @Input()
402
    @InputNumber()
1✔
403
    set thyPageIndex(value: number) {
2✔
404
        this.pagination.index = value;
1✔
405
    }
1✔
406

1✔
407
    /**
408
     * 设置每页显示数量
409
     * @default 20
2✔
410
     */
1✔
411
    @Input()
1✔
412
    @InputNumber()
413
    set thyPageSize(value: number) {
414
        this.pagination.size = value;
2✔
415
    }
3✔
416

417
    /**
2✔
418
     * 设置总页数
419
     */
1✔
420
    @Input()
421
    @InputNumber()
422
    set thyPageTotal(value: number) {
423
        this.pagination.total = value;
424
    }
425

1✔
426
    /**
1✔
427
     * 选中当前行是否自动选中 Checkbox,不开启时只有点击 Checkbox 列时才会触发选中
428
     * @default false
429
     */
430
    @Input()
1✔
431
    @InputBoolean()
2✔
432
    set thyWholeRowSelect(value: boolean) {
433
        if (value) {
1✔
434
            this.className += ' table-hover';
2✔
435
        }
436
        this.wholeRowSelect = value;
1✔
437
    }
438

439
    /**
440
     * 是否显示表格头
441
     * @default false
442
     */
1✔
443
    @Input() @InputBoolean() thyHeadless = false;
1✔
444

445
    /**
446
     * 是否显示表格头,已废弃,请使用 thyHeadless
447
     * @deprecated please use thyHeadless
3✔
448
     */
3✔
449
    @Input()
3✔
450
    @InputBoolean()
3!
451
    set thyShowHeader(value: boolean) {
3✔
452
        this.thyHeadless = !value;
12✔
453
    }
454

455
    /**
456
     * 是否显示左侧 Total
457
     */
458
    @Input('thyShowTotal') @InputBoolean() showTotal = false;
1✔
459

460
    /**
461
     * 是否显示调整每页显示条数下拉框
462
     */
463
    @Input('thyShowSizeChanger') @InputBoolean() showSizeChanger = false;
464

1✔
465
    /**
1✔
466
     * 每页显示条数下拉框可选项
467
     * @type number[]
468
     */
3✔
469
    @Input('thyPageSizeOptions')
2✔
470
    set pageSizeOptions(value: number[]) {
471
        this.pagination.sizeOptions = value;
1!
472
    }
1✔
473

474
    /**
475
     * thyMode 为 tree 时,设置 Tree 树状数据展示时的缩进
476
     */
1!
477
    @Input() @InputNumber() thyIndent = 20;
1✔
478

479
    /**
1!
480
     * thyMode 为 tree 时,设置 Tree 树状数据对象中的子节点 Key
1✔
481
     * @type string
482
     */
×
483
    @Input() thyChildrenKey = 'children';
×
484

485
    /**
486
     * 开启 Hover 后显示操作,默认不显示操作区内容,鼠标 Hover 时展示
×
487
     * @default false
488
     */
1✔
489
    @HostBinding('class.thy-table-hover-display-operation')
1✔
490
    @Input()
1✔
491
    @InputBoolean()
1✔
492
    thyHoverDisplayOperation: boolean;
493

494
    @Input() thyDragDisabledPredicate: (item: SafeAny) => boolean = () => false;
495

11✔
496
    /**
11✔
497
     * 表格列的骨架类型
4✔
498
     * @type ThyTableColumnSkeletonType[]
2✔
499
     */
2✔
500
    @Input() thyColumnSkeletonTypes: ThyTableColumnSkeletonType[] = [
501
        ThyTableColumnSkeletonType.title,
2!
502
        ThyTableColumnSkeletonType.member,
2✔
503
        ThyTableColumnSkeletonType.default
1✔
504
    ];
1✔
505

1✔
506
    /**
507
     * 切换组件回调事件
2✔
508
     */
1✔
509
    @Output() thyOnSwitchChange: EventEmitter<ThySwitchEvent> = new EventEmitter<ThySwitchEvent>();
1✔
510

511
    /**
512
     * 表格分页回调事件
513
     */
4✔
514
    @Output() thyOnPageChange: EventEmitter<PageChangedEvent> = new EventEmitter<PageChangedEvent>();
515

516
    /**
517
     * 表格分页当前页改变回调事件
4✔
518
     */
519
    @Output() thyOnPageIndexChange: EventEmitter<number> = new EventEmitter<number>();
520

521
    @Output() thyOnPageSizeChange: EventEmitter<number> = new EventEmitter<number>();
11✔
522

7✔
523
    /**
7✔
524
     * 多选回调事件
525
     */
4✔
526
    @Output() thyOnMultiSelectChange: EventEmitter<ThyMultiSelectEvent> = new EventEmitter<ThyMultiSelectEvent>();
527

528
    /**
1✔
529
     * 单选回调事件
530
     */
531
    @Output() thyOnRadioSelectChange: EventEmitter<ThyRadioSelectEvent> = new EventEmitter<ThyRadioSelectEvent>();
532

1✔
533
    /**
534
     * 拖动修改事件
535
     */
8!
536
    @Output() thyOnDraggableChange: EventEmitter<ThyTableDraggableEvent> = new EventEmitter<ThyTableDraggableEvent>();
8✔
537

47✔
538
    /**
539
     * 表格行点击触发事件
540
     */
541
    @Output() thyOnRowClick: EventEmitter<ThyTableRowEvent> = new EventEmitter<ThyTableRowEvent>();
542

8✔
543
    /**
47✔
544
     * 列排序修改事件
545
     */
546
    @Output() thySortChange: EventEmitter<ThyTableSortEvent> = new EventEmitter<ThyTableSortEvent>();
547

14✔
548
    @Output() thyOnRowContextMenu: EventEmitter<ThyTableEvent> = new EventEmitter<ThyTableEvent>();
14✔
549

14✔
550
    @ContentChild('group', { static: true }) groupTemplate: TemplateRef<SafeAny>;
28✔
551

28!
552
    @ContentChildren(ThyTableColumnComponent)
×
553
    set listOfColumnComponents(components: QueryList<ThyTableColumnComponent>) {
554
        if (components) {
555
            this.columns = components.toArray();
28✔
556
            this.hasFixed = !!this.columns.find(item => {
557
                return item.fixed === this.fixedDirection.left || item.fixed === this.fixedDirection.right;
28✔
558
            });
559
            this._initializeColumns();
560
            this._initializeDataModel();
561
        }
13✔
562
    }
13✔
563

79✔
564
    // 数据的折叠展开状态
79✔
565
    public expandStatusMap: Dictionary<boolean> = {};
78✔
566

567
    public expandStatusMapOfGroup: Dictionary<boolean> = {};
568

569
    private expandStatusMapOfGroupBeforeDrag: Dictionary<boolean> = {};
570

4✔
571
    dragPreviewClass = 'thy-table-drag-preview';
4✔
572

573
    public skeletonColumns: ThyTableSkeletonColumn[] = [];
574

1✔
575
    constructor(
×
576
        public elementRef: ElementRef,
577
        private _differs: IterableDiffers,
578
        private viewportRuler: ViewportRuler,
579
        private updateHostClassService: UpdateHostClassService,
1✔
580
        @Inject(DOCUMENT) private document: SafeAny,
1✔
581
        @Inject(PLATFORM_ID) private platformId: string,
582
        private ngZone: NgZone,
583
        private renderer: Renderer2,
584
        private cdr: ChangeDetectorRef
8✔
585
    ) {
8✔
586
        super();
8✔
587
        this._bindTrackFn();
8✔
588
    }
8✔
589

8!
590
    private _initializeColumns() {
×
591
        if (!this.columns.some(item => item.expand === true) && this.columns.length > 0) {
×
592
            this.columns[0].expand = true;
593
        }
×
594
        this._initializeColumnFixedPositions();
×
595
    }
596

597
    private _initializeColumnFixedPositions() {
×
598
        const leftFixedColumns = this.columns.filter(item => item.fixed === ThyFixedDirection.left);
599
        leftFixedColumns.forEach((item, index) => {
600
            const previous = leftFixedColumns[index - 1];
8!
601
            item.left = previous ? previous.left + parseInt(previous.width.toString(), 10) : 0;
8✔
602
        });
603
        const rightFixedColumns = this.columns.filter(item => item.fixed === ThyFixedDirection.right).reverse();
8!
604
        rightFixedColumns.forEach((item, index) => {
×
605
            const previous = rightFixedColumns[index - 1];
606
            item.right = previous ? previous.right + parseInt(previous.width.toString(), 10) : 0;
607
        });
608
    }
66✔
609

66✔
610
    private _initializeDataModel() {
66✔
611
        this.model.forEach(row => {
66✔
612
            this.columns.forEach(column => {
613
                this._initialSelections(row, column);
614
                this._initialCustomModelValue(row, column);
8✔
615
            });
8✔
616
        });
8✔
617
    }
8✔
618

619
    private _initialSelections(row: object, column: ThyTableColumnComponent) {
66✔
620
        if (column.selections) {
66✔
621
            if (column.type === 'checkbox') {
×
622
                row[column.key] = column.selections.includes(row[this.rowKey]);
623
                this.onModelChange(row, column);
624
            }
625
            if (column.type === 'radio') {
626
                if (column.selections.includes(row[this.rowKey])) {
8✔
627
                    this.selectedRadioRow = row;
8✔
628
                }
47✔
629
            }
70✔
630
        }
86✔
631
    }
632

47✔
633
    private _initialCustomModelValue(row: object, column: ThyTableColumnComponent) {
634
        if (column.type === customType.switch) {
635
            row[column.key] = get(row, column.model);
636
        }
66!
637
    }
×
638

639
    private _refreshCustomModelValue(row: SafeAny) {
66✔
640
        this.columns.forEach(column => {
392✔
641
            this._initialCustomModelValue(row, column);
642
        });
643
    }
644

645
    private _applyDiffChanges(changes: IterableChanges<SafeAny>) {
646
        if (changes) {
647
            changes.forEachAddedItem((record: IterableChangeRecord<SafeAny>) => {
648
                this._refreshCustomModelValue(record.item);
392!
649
            });
650
        }
×
651
    }
652

653
    private _bindTrackFn() {
654
        this.trackByFn = function (this: SafeAny, index: number, row: SafeAny): SafeAny {
655
            return row && this.rowKey ? row[this.rowKey] : index;
656
        }.bind(this);
657
    }
658

1!
659
    private _destroyInvalidAttribute() {
1✔
660
        this.model.forEach(row => {
661
            for (const key in row) {
662
                if (key.includes('[$$column]')) {
663
                    delete row[key];
664
                }
78✔
665
            }
78✔
666
        });
78✔
667
    }
78✔
668

12✔
669
    private _setClass(first = false) {
12✔
670
        if (!first && !this.initialized) {
671
            return;
78!
672
        }
78✔
673
        const classNames: string[] = [];
78✔
674
        if (this.size) {
675
            classNames.push(`table-${this.size}`);
676
        }
677
        if (tableThemeMap[this.theme]) {
70✔
678
            classNames.push(tableThemeMap[this.theme]);
70✔
679
        }
680

1✔
681
        this.updateHostClassService.updateClass(classNames);
682
    }
683

684
    public updateColumnSelections(key: string, selections: SafeAny): void {
685
        const column = this.columns.find(item => item.key === key);
686
        this.model.forEach(row => {
687
            this._initialSelections(row, column);
688
        });
689
    }
690

691
    public isTemplateRef(ref: SafeAny) {
1✔
692
        return ref instanceof TemplateRef;
693
    }
694

695
    public getModelValue(row: SafeAny, path: string) {
696
        return get(row, path);
697
    }
698

699
    public renderRowClassName(row: SafeAny, index: number) {
700
        if (!this.rowClassName) {
701
            return null;
702
        }
703
        if (isString(this.rowClassName)) {
704
            return this.rowClassName;
705
        } else {
706
            return (this.rowClassName as Function)(row, index);
707
        }
708
    }
709

710
    public onModelChange(row: SafeAny, column: ThyTableColumnComponent) {
711
        if (column.model) {
712
            set(row, column.model, row[column.key]);
713
        }
714
    }
715

716
    public onStopPropagation(event: Event) {
717
        if (this.wholeRowSelect) {
718
            event.stopPropagation();
719
        }
720
    }
721

722
    public onPageChange(event: PageChangedEvent) {
723
        this.thyOnPageChange.emit(event);
724
    }
725

726
    public onPageIndexChange(event: number) {
727
        this.thyOnPageIndexChange.emit(event);
728
    }
729

730
    public onPageSizeChange(event: number) {
731
        this.thyOnPageSizeChange.emit(event);
732
    }
733

734
    public onCheckboxChange(row: SafeAny, column: ThyTableColumnComponent) {
735
        this.onModelChange(row, column);
736
        this.onMultiSelectChange(null, row, column);
737
    }
738

739
    public onMultiSelectChange(event: Event, row: SafeAny, column: ThyTableColumnComponent) {
740
        const rows = this.model.filter(item => {
1✔
741
            return item[column.key];
742
        });
743
        const multiSelectEvent: ThyMultiSelectEvent = {
744
            event: event,
1✔
745
            row: row,
746
            rows: rows
747
        };
748
        this.thyOnMultiSelectChange.emit(multiSelectEvent);
1✔
749
    }
750

751
    public onRadioSelectChange(event: Event, row: SafeAny) {
752
        const radioSelectEvent: ThyRadioSelectEvent = {
1✔
753
            event: event,
754
            row: row
755
        };
756
        this.thyOnRadioSelectChange.emit(radioSelectEvent);
1✔
757
    }
758

759
    public onSwitchChange(event: Event, row: SafeAny, column: SafeAny) {
760
        const switchEvent: ThySwitchEvent = {
761
            event: event,
1✔
762
            row: row,
763
            refresh: (value: SafeAny) => {
764
                value = value || row;
765
                setTimeout(() => {
766
                    value[column.key] = get(value, column.model);
1✔
767
                });
768
            }
769
        };
770
        this.thyOnSwitchChange.emit(switchEvent);
771
    }
1✔
772

773
    showExpand(row: SafeAny) {
774
        return row[this.thyChildrenKey] && row[this.thyChildrenKey].length > 0;
775
    }
776

1✔
777
    isExpanded(row: SafeAny) {
778
        return this.expandStatusMap[row[this.rowKey]];
779
    }
780

781
    iconIndentComputed(level: number) {
1✔
782
        if (this.mode === 'tree') {
783
            return level * this.thyIndent - 5;
784
        }
785
    }
786

1✔
787
    tdIndentComputed(level: number) {
788
        return {
789
            position: 'relative',
790
            paddingLeft: `${(level + 1) * this.thyIndent - 5}px`
1✔
791
        };
792
    }
793

794
    expandChildren(row: SafeAny) {
795
        if (this.isExpanded(row)) {
1✔
796
            this.expandStatusMap[row[this.rowKey]] = false;
797
        } else {
798
            this.expandStatusMap[row[this.rowKey]] = true;
799
        }
1✔
800
    }
801

802
    onDragGroupStarted(event: CdkDragStart<unknown>) {
803
        this.expandStatusMapOfGroupBeforeDrag = { ...this.expandStatusMapOfGroup };
1✔
804
        const groups = this.groups.filter(group => group.expand);
805
        this.foldGroups(groups);
806
        this.onDragStarted(event);
807
        this.cdr.detectChanges();
1✔
808
    }
809

810
    onDragGroupEnd(event: CdkDragEnd<unknown>) {
811
        const groups = this.groups.filter(group => this.expandStatusMapOfGroupBeforeDrag[group.id]);
1✔
812
        this.expandGroups(groups);
813
        this.cdr.detectChanges();
814
    }
815

816
    private onDragGroupDropped(event: CdkDragDrop<unknown>) {
817
        const group = this.groups.find(group => {
818
            return event.item.data.id === group.id;
819
        });
820
        if (group) {
821
            // drag group
822
            const dragEvent: ThyTableDraggableEvent = {
823
                model: event.item,
824
                models: this.groups,
825
                oldIndex: event.previousIndex,
826
                newIndex: event.currentIndex
827
            };
828
            moveItemInArray(this.groups, event.previousIndex, event.currentIndex);
829
            this.thyOnDraggableChange.emit(dragEvent);
830
        } else {
831
            // drag group children
832
            const group = this.groups.find(group => {
833
                return event.item.data[this.groupBy] === group.id;
834
            });
835
            const groupIndex =
836
                event.container.getSortedItems().findIndex(item => {
837
                    return item.data.id === event.item.data[this.groupBy];
838
                }) + 1;
839
            const dragEvent: ThyTableDraggableEvent = {
840
                model: event.item,
841
                models: group.children,
842
                oldIndex: event.previousIndex - groupIndex,
843
                newIndex: event.currentIndex - groupIndex
844
            };
845
            moveItemInArray(group.children, dragEvent.oldIndex, dragEvent.newIndex);
846
            this.thyOnDraggableChange.emit(dragEvent);
847
        }
848
    }
849

850
    onDragStarted(event: CdkDragStart<unknown>) {
851
        this.ngZone.runOutsideAngular(() =>
852
            setTimeout(() => {
853
                const preview = this.document.getElementsByClassName(this.dragPreviewClass)[0];
854
                const originalTds: HTMLCollection = event.source._dragRef.getPlaceholderElement()?.children;
855
                if (preview) {
856
                    Array.from(preview?.children).forEach((element: HTMLElement, index: number) => {
857
                        element.style.width = `${originalTds[index]?.clientWidth}px`;
858
                    });
859
                }
860
            })
861
        );
862
    }
863

864
    dropListEnterPredicate = (index: number, drag: CdkDrag, drop: CdkDropList) => {
865
        return drop.getSortedItems()[index].data.group_id === drag.data.group_id;
866
    };
867

868
    private onDragModelDropped(event: CdkDragDrop<unknown>) {
869
        const dragEvent: ThyTableDraggableEvent = {
870
            model: event.item,
871
            models: this.model,
872
            oldIndex: event.previousIndex,
873
            newIndex: event.currentIndex
874
        };
875
        moveItemInArray(this.model, event.previousIndex, event.currentIndex);
876
        this.thyOnDraggableChange.emit(dragEvent);
877
    }
878

879
    onDragDropped(event: CdkDragDrop<unknown>) {
880
        if (this.mode === 'group') {
881
            this.onDragGroupDropped(event);
882
        } else if (this.mode === 'list') {
883
            this.onDragModelDropped(event);
884
        }
885
    }
886

887
    onColumnHeaderClick(event: Event, column: ThyTableColumnComponent) {
888
        if (column.sortable) {
889
            const { sortDirection, model, sortChange } = column;
890
            let direction;
891
            if (sortDirection === ThyTableSortDirection.default) {
892
                direction = ThyTableSortDirection.asc;
893
            } else if (sortDirection === ThyTableSortDirection.asc) {
894
                direction = ThyTableSortDirection.desc;
895
            } else {
896
                direction = ThyTableSortDirection.default;
897
            }
898
            column.sortDirection = direction;
899
            const sortEvent = { event, key: model, direction };
900
            sortChange.emit(sortEvent);
901
            this.thySortChange.emit(sortEvent);
902
        }
903
    }
904

905
    public onRowClick(event: Event, row: SafeAny) {
906
        const next = this.onRowClickPropagationEventHandler(event, row);
907
        if (next) {
908
            if (this.wholeRowSelect) {
909
                const column = this.columns.find(item => {
910
                    return item.type === customType.checkbox || item.type === customType.radio;
911
                });
912
                if (column && !column.disabled) {
913
                    if (column.type === customType.checkbox) {
914
                        row[column.key] = !row[column.key];
915
                        this.onModelChange(row, column);
916
                        this.onMultiSelectChange(event, row, column);
917
                    }
918
                    if (column.type === customType.radio) {
919
                        this.selectedRadioRow = row;
920
                        this.onRadioSelectChange(event, row);
921
                    }
922
                }
923
            }
924
            const rowEvent = {
925
                event: event,
926
                row: row
927
            };
928
            this.thyOnRowClick.emit(rowEvent);
929
        }
930
    }
931

932
    private onRowClickPropagationEventHandler(event: Event, row: SafeAny): boolean {
933
        if ((event.target as Element).closest('.tree-expand-icon')) {
934
            this.expandChildren(row);
935
            return false;
936
        }
937
        return true;
938
    }
939

940
    public onRowContextMenu(event: Event, row: SafeAny) {
941
        const contextMenuEvent: ThyTableEvent = {
942
            event: event,
943
            row: row
944
        };
945
        this.thyOnRowContextMenu.emit(contextMenuEvent);
946
    }
947

948
    private _refreshColumns() {
949
        const components = this.columns || [];
950
        const _columns = components.map(component => {
951
            return {
952
                width: component.width,
953
                className: component.className
954
            };
955
        });
956

957
        this.columns.forEach((n, i) => {
958
            Object.assign(n, _columns[i]);
959
        });
960
    }
961

962
    private buildGroups(originGroups: SafeAny) {
963
        const originGroupsMap = helpers.keyBy(originGroups, 'id');
964
        this.groups = [];
965
        originGroups.forEach((origin: SafeAny) => {
966
            const group: ThyTableGroup = { id: origin[this.rowKey], children: [], origin };
967

968
            if (this.expandStatusMapOfGroup.hasOwnProperty(group.id)) {
969
                group.expand = this.expandStatusMapOfGroup[group.id];
970
            } else {
971
                group.expand = !!(originGroupsMap[group.id] as SafeAny).expand;
972
            }
973

974
            this.groups.push(group);
975
        });
976
    }
977

978
    private buildModel() {
979
        const groupsMap = keyBy(this.groups, 'id');
980
        this.model.forEach(row => {
981
            const group = groupsMap[row[this.groupBy]];
982
            if (group) {
983
                group.children.push(row);
984
            }
985
        });
986
    }
987

988
    public expandGroup(group: ThyTableGroup) {
989
        group.expand = !group.expand;
990
        this.expandStatusMapOfGroup[group.id] = group.expand;
991
    }
992

993
    private expandGroups(groups: ThyTableGroup[]) {
994
        groups.forEach(group => {
995
            this.expandGroup(group);
996
        });
997
    }
998

999
    private foldGroups(groups: ThyTableGroup[]) {
1000
        groups.forEach(group => {
1001
            this.expandGroup(group);
1002
        });
1003
    }
1004

1005
    private updateScrollClass() {
1006
        const scrollElement = this.tableScrollElement;
1007
        const maxScrollLeft = scrollElement.scrollWidth - scrollElement.offsetWidth;
1008
        const scrollX = scrollElement.scrollLeft;
1009
        const lastScrollClassName = this.scrollClassName;
1010
        this.scrollClassName = '';
1011
        if (scrollElement.scrollWidth > scrollElement.clientWidth) {
1012
            if (scrollX >= maxScrollLeft) {
1013
                this.scrollClassName = css.tableScrollRight;
1014
            } else if (scrollX === 0) {
1015
                this.scrollClassName = css.tableScrollLeft;
1016
            } else {
1017
                this.scrollClassName = css.tableScrollMiddle;
1018
            }
1019
        }
1020
        if (lastScrollClassName) {
1021
            this.renderer.removeClass(this.tableScrollElement, lastScrollClassName);
1022
        }
1023
        if (this.scrollClassName) {
1024
            this.renderer.addClass(this.tableScrollElement, this.scrollClassName);
1025
        }
1026
    }
1027

1028
    ngOnInit() {
1029
        this.updateHostClassService.initializeElement(this.tableElementRef.nativeElement);
1030
        this._setClass(true);
1031
        this.initialized = true;
1032

1033
        merge(this.viewportRuler.change(200), of(null).pipe(delay(200)))
1034
            .pipe(takeUntil(this.ngUnsubscribe$))
1035
            .subscribe(() => {
1036
                this._refreshColumns();
1037
                this.updateScrollClass();
1038
                this.buildSkeletonColumns();
1039
                this.cdr.detectChanges();
1040
            });
1041

1042
        this.ngZone.runOutsideAngular(() => {
1043
            this.scroll$.pipe(takeUntil(this.ngUnsubscribe$)).subscribe(() => {
1044
                this.updateScrollClass();
1045
            });
1046
        });
1047
    }
1048

1049
    private buildSkeletonColumns() {
1050
        this.skeletonColumns = [];
1051

1052
        this.columns.forEach((column: ThyTableColumnComponent, index: number) => {
1053
            const item = {
1054
                type: this.thyColumnSkeletonTypes[index] || ThyTableColumnSkeletonType.default,
1055
                width: column.width || 'auto'
1056
            };
1057
            this.skeletonColumns = [...this.skeletonColumns, item];
1058
        });
1059
    }
1060

1061
    ngAfterViewInit(): void {
1062
        if (isPlatformServer(this.platformId)) {
1063
            return;
1064
        }
1065

1066
        this.rows.changes
1067
            .pipe(
1068
                startWith(this.rows),
1069
                switchMap(
1070
                    () =>
1071
                        new Observable<Event>(subscriber =>
1072
                            this.ngZone.runOutsideAngular(() =>
1073
                                merge(
1074
                                    ...this.rows.map(row =>
1075
                                        fromEvent(
1076
                                            row.nativeElement,
1077
                                            // Note: there's no need to add touch, pointer and mouse event listeners together.
1078
                                            // There can be any number of rows, which will lead to adding N * 3 event listeners.
1079
                                            // According to the spec (https://www.w3.org/TR/pointerevents/#examples), we can use feature detection
1080
                                            // to determine if pointer events are available. If pointer events are available, we have to listen only
1081
                                            // to the `pointerdown` event. Otherwise, we have to determine if we're on a touch device or not.
1082
                                            // Touch events are handled earlier than mouse events, tho not all user agents dispatch mouse events
1083
                                            // after touch events. See the spec: https://www.w3.org/TR/touch-events/#mouse-events.
1084
                                            window.PointerEvent
1085
                                                ? 'pointerdown'
1086
                                                : 'ontouchstart' in row.nativeElement
1087
                                                ? 'touchstart'
1088
                                                : 'mousedown',
1089
                                            // Note: since Chrome 56 defaults document level `touchstart` listener to passive.
1090
                                            // The element `touchstart` listener is not passive by default
1091
                                            // We never call `preventDefault()` on it, so we're safe making it passive too.
1092
                                            <AddEventListenerOptions>passiveEventListenerOptions
1093
                                        )
1094
                                    )
1095
                                ).subscribe(subscriber)
1096
                            )
1097
                        )
1098
                ),
1099
                takeUntil(this.ngUnsubscribe$)
1100
            )
1101
            .subscribe(event => {
1102
                if (!this.draggable) {
1103
                    event.stopPropagation();
1104
                }
1105
            });
1106
    }
1107

1108
    ngOnChanges(simpleChanges: SimpleChanges) {
1109
        const modeChange = simpleChanges.thyMode;
1110
        const thyGroupsChange = simpleChanges.thyGroups;
1111
        const isGroupMode = modeChange && modeChange.currentValue === 'group';
1112
        if (isGroupMode && thyGroupsChange && thyGroupsChange.firstChange) {
1113
            this.buildGroups(thyGroupsChange.currentValue);
1114
            this.buildModel();
1115
        }
1116

1117
        if (this._diff) {
1118
            const changes = this._diff.diff(this.model);
1119
            this._applyDiffChanges(changes);
1120
        }
1121
    }
1122

1123
    ngOnDestroy() {
1124
        super.ngOnDestroy();
1125
        this._destroyInvalidAttribute();
1126
    }
1127
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc