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

atinc / ngx-tethys / 9a18585c-25d4-4f12-a1fc-7cfb9af32690

09 Oct 2024 03:21AM UTC coverage: 90.433% (+0.002%) from 90.431%
9a18585c-25d4-4f12-a1fc-7cfb9af32690

push

circleci

why520crazy
refactor: refactor all control-flow directives to new control-flow #TINFR-381

5511 of 6738 branches covered (81.79%)

Branch coverage included in aggregate %.

97 of 104 new or added lines in 58 files covered. (93.27%)

113 existing lines in 17 files now uncovered.

13252 of 14010 relevant lines covered (94.59%)

991.71 hits per line

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

88.1
/src/table/table.component.ts
1
import { InputCssPixel, UpdateHostClassService } from 'ngx-tethys/core';
2
import { Dictionary, SafeAny } from 'ngx-tethys/types';
3
import { coerceBooleanProperty, get, helpers, isString, keyBy, set } from 'ngx-tethys/util';
4
import { EMPTY, fromEvent, merge, Observable, of } from 'rxjs';
5
import { delay, startWith, switchMap } from 'rxjs/operators';
6
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
7

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

45
import { IThyTableColumnParentComponent, THY_TABLE_COLUMN_PARENT_COMPONENT, ThyTableColumnComponent } from './table-column.component';
46
import {
47
    PageChangedEvent,
48
    ThyMultiSelectEvent,
1✔
49
    ThyPage,
50
    ThyRadioSelectEvent,
51
    ThySwitchEvent,
52
    ThyTableSkeletonColumn,
53
    ThyTableDraggableEvent,
54
    ThyTableEmptyOptions,
1✔
55
    ThyTableEvent,
56
    ThyTableRowEvent,
148✔
57
    ThyTableSortDirection,
58
    ThyTableSortEvent
59
} from './table.interface';
66!
60
import { TableRowDragDisabledPipe } from './pipes/drag.pipe';
61
import { TableIsValidModelValuePipe } from './pipes/table.pipe';
62
import { ThyPagination } from 'ngx-tethys/pagination';
60!
63
import { ThyTableSkeleton } from './table-skeleton.component';
64
import { ThyEmpty } from 'ngx-tethys/empty';
65
import { ThySwitch } from 'ngx-tethys/switch';
57✔
66
import { FormsModule } from '@angular/forms';
67
import { ThyDragDropDirective, ThyContextMenuDirective } from 'ngx-tethys/shared';
68
import { ThyIcon } from 'ngx-tethys/icon';
70!
69
import { CdkScrollable } from '@angular/cdk/scrolling';
70
import { ThyTableColumnSkeletonType } from './enums';
71

56✔
72
export type ThyTableTheme = 'default' | 'bordered' | 'boxed';
3✔
73

74
export type ThyTableMode = 'list' | 'group' | 'tree';
75

76
export type ThyTableSize = 'md' | 'sm' | 'xs' | 'lg' | 'xlg' | 'default';
67✔
77

67✔
78
export enum ThyFixedDirection {
67✔
79
    left = 'left',
67✔
80
    right = 'right'
1✔
81
}
82

83
interface ThyTableGroup<T = unknown> {
84
    id?: string;
45!
85
    expand?: boolean;
45✔
86
    children?: object[];
87
    origin?: T;
88
}
50✔
89

50✔
90
const tableThemeMap = {
91
    default: 'table-default',
92
    bordered: 'table-bordered',
48✔
93
    boxed: 'table-boxed'
45✔
94
};
45!
95

×
96
const customType = {
97
    index: 'index',
98
    checkbox: 'checkbox',
45✔
99
    radio: 'radio',
100
    switch: 'switch'
45✔
101
};
45✔
102

103
const css = {
104
    tableBody: 'thy-table-body',
45✔
105
    tableScrollLeft: 'thy-table-scroll-left',
106
    tableScrollRight: 'thy-table-scroll-right',
107
    tableScrollMiddle: 'thy-table-scroll-middle'
45✔
108
};
109

110
const passiveEventListenerOptions = normalizePassiveListenerOptions({ passive: true });
45✔
111

112
/**
113
 * 表格组件
44✔
114
 * @name thy-table
115
 * @order 10
116
 */
64✔
117
@Component({
64✔
118
    selector: 'thy-table',
1✔
119
    templateUrl: './table.component.html',
120
    providers: [
121
        {
122
            provide: THY_TABLE_COLUMN_PARENT_COMPONENT,
55✔
123
            useExisting: ThyTable
124
        },
125
        UpdateHostClassService
55✔
126
    ],
127
    encapsulation: ViewEncapsulation.None,
128
    host: {
55✔
129
        class: 'thy-table',
130
        '[class.thy-table-bordered]': `theme === 'bordered'`,
131
        '[class.thy-table-boxed]': `theme === 'boxed'`,
45✔
132
        '[class.thy-table-fixed-header]': 'thyHeaderFixed'
3✔
133
    },
134
    standalone: true,
45✔
135
    imports: [
136
        CdkScrollable,
137
        NgClass,
1✔
138
        NgTemplateOutlet,
139
        ThyIcon,
140
        ThyDragDropDirective,
44✔
141
        CdkDropList,
142
        CdkDrag,
143
        ThyContextMenuDirective,
66!
144
        NgStyle,
66✔
145
        FormsModule,
66✔
146
        ThySwitch,
367✔
147
        ThyEmpty,
148
        ThyTableSkeleton,
66✔
149
        ThyPagination,
66✔
150
        TableIsValidModelValuePipe,
66✔
151
        TableRowDragDisabledPipe
152
    ]
153
})
154
export class ThyTable implements OnInit, OnChanges, AfterViewInit, OnDestroy, IThyTableColumnParentComponent {
70✔
155
    private readonly destroyRef = inject(DestroyRef);
70✔
156

70✔
157
    public customType = customType;
70✔
158

70✔
159
    public model: object[] = [];
70✔
160

70✔
161
    public groups: ThyTableGroup[] = [];
70✔
162

70✔
163
    public rowKey = '_id';
70✔
164

70✔
165
    public groupBy: string;
70✔
166

70✔
167
    public mode: ThyTableMode = 'list';
70✔
168

70✔
169
    public theme: ThyTableTheme = 'default';
70✔
170

70✔
171
    public className = '';
70✔
172

70✔
173
    public size: ThyTableSize = 'md';
70✔
174

70✔
175
    public rowClassName: string | Function;
70✔
176

70✔
177
    public loadingDone = true;
70✔
178

70✔
179
    public loadingText: string;
70✔
180

70✔
181
    public emptyOptions: ThyTableEmptyOptions = {};
70✔
182

70✔
183
    public draggable = false;
70✔
184

70✔
185
    public selectedRadioRow: SafeAny = null;
70✔
186

70✔
187
    public pagination: ThyPage = { index: 1, size: 20, total: 0, sizeOptions: [20, 50, 100] };
70✔
188

70✔
189
    public trackByFn: SafeAny;
384✔
190

70✔
191
    public wholeRowSelect = false;
192

193
    public fixedDirection = ThyFixedDirection;
194

195
    public hasFixed = false;
70✔
196

70✔
197
    public columns: ThyTableColumnComponent[] = [];
70✔
198

70✔
199
    private _diff: IterableDiffer<SafeAny>;
70✔
200

70✔
201
    private initialized = false;
70✔
202

70✔
203
    private _oldThyClassName = '';
70✔
204

70✔
205
    private scrollClassName = css.tableScrollLeft;
206

70✔
207
    private get tableScrollElement(): HTMLElement {
70✔
208
        return this.elementRef.nativeElement.getElementsByClassName(css.tableBody)[0] as HTMLElement;
70✔
209
    }
70✔
210

70✔
211
    private get scroll$() {
70✔
UNCOV
212
        return merge(this.tableScrollElement ? fromEvent<MouseEvent>(this.tableScrollElement, 'scroll') : EMPTY);
×
213
    }
214

70✔
215
    /**
216
     * 设置数据为空时展示的模板
217
     * @type TemplateRef
374✔
218
     */
65✔
219
    @ContentChild('empty') emptyTemplate: TemplateRef<SafeAny>;
220

66✔
221
    @ViewChild('table', { static: true }) tableElementRef: ElementRef<SafeAny>;
222

223
    @ViewChildren('rows', { read: ElementRef }) rows: QueryList<ElementRef<HTMLElement>>;
377✔
224

66✔
225
    /**
4✔
226
     * 表格展示方式,列表/分组/树
4✔
227
     * @type list | group | tree
228
     * @default list
377✔
229
     */
66✔
230
    @Input()
1✔
231
    set thyMode(value: ThyTableMode) {
1!
232
        this.mode = value || this.mode;
233
    }
234

235
    /**
133✔
236
     * thyMode的值为 `group` 时分组的 Key
731✔
237
     */
2,097✔
238
    @Input()
2,097✔
239
    set thyGroupBy(value: string) {
240
        this.groupBy = value;
241
    }
242

243
    /**
2,097✔
244
     * 设置每行数据的唯一标识属性名
504✔
245
     * @default _id
246✔
246
     */
246✔
247
    @Input()
248
    set thyRowKey(value: SafeAny) {
504✔
249
        this.rowKey = value || this.rowKey;
6!
UNCOV
250
    }
×
251

252
    /**
253
     * 分组数据源
254
     */
255
    @Input()
256
    set thyGroups(value: SafeAny) {
2,132✔
257
        if (this.mode === 'group') {
356✔
258
            this.buildGroups(value);
259
        }
260
    }
261

369✔
262
    /**
35✔
263
     * 数据源
264
     */
265
    @Input()
266
    set thyModel(value: SafeAny) {
78✔
267
        this.model = value || [];
62✔
268
        this._diff = this._differs.find(this.model).create();
369✔
269
        this._initializeDataModel();
270

271
        if (this.mode === 'group') {
272
            this.buildModel();
273
        }
70✔
274
    }
180!
275

276
    /**
277
     * 表格的显示风格,`bordered` 时头部有背景色且分割线区别明显
278
     * @type default | bordered | boxed
70✔
279
     * @default default
363✔
280
     */
2,911✔
281
    @Input()
589✔
282
    set thyTheme(value: ThyTableTheme) {
283
        this.theme = value || this.theme;
284
        this._setClass();
285
    }
286

95✔
287
    /**
161✔
288
     * 表格的大小
90✔
289
     * @type xs | sm | md | lg | xlg | default
290
     * @default md
71✔
291
     */
71!
292
    @Input()
71✔
293
    set thySize(value: ThyTableSize) {
294
        this.size = value || this.size;
71!
295
        this._setClass();
71✔
296
    }
297

71✔
298
    /**
299
     * 设置表格最小宽度,一般是适用于设置列宽为百分之或auto时限制表格最小宽度'
300
     */
×
UNCOV
301
    @Input()
×
UNCOV
302
    @InputCssPixel()
×
303
    thyMinWidth: string | number;
304

305
    /**
306
     * 设置为 fixed 布局表格,设置 fixed 后,列宽将严格按照设置宽度展示,列宽将不会根据表格内容自动调整
13,820✔
307
     * @default false
308
     */
309
    @Input({ transform: coerceBooleanProperty }) thyLayoutFixed: boolean;
6,957✔
310

311
    /**
312
     * 是否表头固定,若设置为 true, 需要同步设置 thyHeight
1,220✔
313
     * @default false
410✔
314
     */
315
    @Input({ transform: coerceBooleanProperty }) thyHeaderFixed: boolean;
810!
316

810✔
317
    /**
318
     * 表格的高度
UNCOV
319
     */
×
320
    @HostBinding('style.height')
321
    @Input()
322
    @InputCssPixel()
323
    thyHeight: string;
249!
324

249✔
325
    /**
326
     * 设置表格的样式
327
     */
328
    @Input()
1!
UNCOV
329
    set thyClassName(value: string) {
×
330
        const list = this.className.split(' ').filter(a => a.trim());
331
        const index: number = list.findIndex(item => item === this._oldThyClassName);
332
        if (index !== -1) {
333
            list.splice(index, 1, value);
1✔
334
        } else {
335
            list.push(value);
336
        }
1✔
337
        this._oldThyClassName = value;
338
        this.className = list.join(' ');
339
    }
1✔
340

341
    /**
342
     * 设置表格行的样式,传入函数,支持 row、index
1✔
343
     * @type string | (row, index) => string
1✔
344
     */
345
    @Input()
346
    set thyRowClassName(value: string | Function) {
2✔
347
        this.rowClassName = value;
12✔
348
    }
349

2✔
350
    /**
351
     * 设置加载状态
352
     * @default true
353
     */
354
    @Input({ transform: coerceBooleanProperty })
2✔
355
    set thyLoadingDone(value: boolean) {
356
        this.loadingDone = value;
357
    }
1✔
358

359
    /**
360
     * 设置加载时显示的文本,已废弃
361
     * @deprecated
1✔
362
     */
363
    @Input()
364
    set thyLoadingText(value: string) {
1✔
365
        this.loadingText = value;
366
    }
367

368
    /**
×
UNCOV
369
     * 配置空状态组件
×
UNCOV
370
     */
×
371
    @Input()
372
    set thyEmptyOptions(value: ThyTableEmptyOptions) {
373
        this.emptyOptions = value;
374
    }
1✔
375

376
    /**
377
     * 是否开启行拖拽
180✔
378
     * @default false
379
     */
380
    @Input({ transform: coerceBooleanProperty })
367✔
381
    set thyDraggable(value: boolean) {
382
        this.draggable = value;
383
        if ((typeof ngDevMode === 'undefined' || ngDevMode) && this.draggable && this.mode === 'tree') {
180!
384
            throw new Error('Tree mode sorting is not supported');
180✔
385
        }
386
    }
387

388
    /**
180✔
389
     * 设置当前页码
390
     * @default 1
391
     */
392
    @Input({ transform: numberAttribute })
393
    set thyPageIndex(value: number) {
394
        this.pagination.index = value;
395
    }
396

7✔
397
    /**
3✔
398
     * 设置每页显示数量
399
     * @default 20
400
     */
4✔
401
    @Input({ transform: numberAttribute })
402
    set thyPageSize(value: number) {
403
        this.pagination.size = value;
404
    }
1✔
405

2✔
406
    /**
1✔
407
     * 设置总页数
1✔
408
     */
1✔
409
    @Input({ transform: numberAttribute })
410
    set thyPageTotal(value: number) {
411
        this.pagination.total = value;
2✔
412
    }
1✔
413

1✔
414
    /**
415
     * 选中当前行是否自动选中 Checkbox,不开启时只有点击 Checkbox 列时才会触发选中
416
     * @default false
2✔
417
     */
3✔
418
    @Input({ transform: coerceBooleanProperty })
419
    set thyWholeRowSelect(value: boolean) {
2✔
420
        if (value) {
421
            this.className += ' table-hover';
1✔
422
        }
423
        this.wholeRowSelect = value;
424
    }
425

426
    /**
427
     * 是否显示表格头
1✔
428
     * @default false
1✔
429
     */
430
    @Input({ transform: coerceBooleanProperty }) thyHeadless = false;
431

432
    /**
1✔
433
     * 是否显示表格头,已废弃,请使用 thyHeadless
2✔
434
     * @deprecated please use thyHeadless
435
     */
1✔
436
    @Input({ transform: coerceBooleanProperty })
2✔
437
    set thyShowHeader(value: boolean) {
438
        this.thyHeadless = !value;
1✔
439
    }
440

441
    /**
442
     * 是否显示左侧 Total
443
     */
444
    @Input({ alias: 'thyShowTotal', transform: coerceBooleanProperty }) showTotal = false;
1✔
445

1✔
446
    /**
447
     * 是否显示调整每页显示条数下拉框
448
     */
449
    @Input({ alias: 'thyShowSizeChanger', transform: coerceBooleanProperty }) showSizeChanger = false;
3✔
450

3✔
451
    /**
3✔
452
     * 每页显示条数下拉框可选项
3!
453
     * @type number[]
3✔
454
     */
12✔
455
    @Input('thyPageSizeOptions')
456
    set pageSizeOptions(value: number[]) {
457
        this.pagination.sizeOptions = value;
458
    }
459

460
    /**
1✔
461
     * thyMode 为 tree 时,设置 Tree 树状数据展示时的缩进
462
     */
463
    @Input({ transform: numberAttribute }) thyIndent = 20;
464

465
    /**
466
     * thyMode 为 tree 时,设置 Tree 树状数据对象中的子节点 Key
1✔
467
     * @type string
1✔
468
     */
469
    @Input() thyChildrenKey = 'children';
470

3✔
471
    /**
2✔
472
     * 开启 Hover 后显示操作,默认不显示操作区内容,鼠标 Hover 时展示
473
     * @default false
1!
474
     */
1✔
475
    @HostBinding('class.thy-table-hover-display-operation')
476
    @Input({ transform: coerceBooleanProperty })
477
    thyHoverDisplayOperation: boolean;
478

3!
479
    @Input() thyDragDisabledPredicate: (item: SafeAny) => boolean = () => false;
3✔
480

481
    /**
3✔
482
     * 表格列的骨架类型
1✔
483
     * @type ThyTableColumnSkeletonType[]
484
     */
2✔
485
    @Input() thyColumnSkeletonTypes: ThyTableColumnSkeletonType[] = [
1✔
486
        ThyTableColumnSkeletonType.title,
487
        ThyTableColumnSkeletonType.member,
488
        ThyTableColumnSkeletonType.default
1✔
489
    ];
490

3✔
491
    /**
3✔
492
     * 切换组件回调事件
3✔
493
     */
3✔
494
    @Output() thyOnSwitchChange: EventEmitter<ThySwitchEvent> = new EventEmitter<ThySwitchEvent>();
495

496
    /**
497
     * 表格分页回调事件
11✔
498
     */
11✔
499
    @Output() thyOnPageChange: EventEmitter<PageChangedEvent> = new EventEmitter<PageChangedEvent>();
4✔
500

2✔
501
    /**
2✔
502
     * 表格分页当前页改变回调事件
503
     */
2!
504
    @Output() thyOnPageIndexChange: EventEmitter<number> = new EventEmitter<number>();
2✔
505

1✔
506
    @Output() thyOnPageSizeChange: EventEmitter<number> = new EventEmitter<number>();
1✔
507

1✔
508
    /**
509
     * 多选回调事件
2✔
510
     */
1✔
511
    @Output() thyOnMultiSelectChange: EventEmitter<ThyMultiSelectEvent> = new EventEmitter<ThyMultiSelectEvent>();
1✔
512

513
    /**
514
     * 单选回调事件
515
     */
4✔
516
    @Output() thyOnRadioSelectChange: EventEmitter<ThyRadioSelectEvent> = new EventEmitter<ThyRadioSelectEvent>();
517

518
    /**
519
     * 拖动修改事件
4✔
520
     */
521
    @Output() thyOnDraggableChange: EventEmitter<ThyTableDraggableEvent> = new EventEmitter<ThyTableDraggableEvent>();
522

523
    /**
11✔
524
     * 表格行点击触发事件
7✔
525
     */
7✔
526
    @Output() thyOnRowClick: EventEmitter<ThyTableRowEvent> = new EventEmitter<ThyTableRowEvent>();
527

4✔
528
    /**
529
     * 列排序修改事件
530
     */
1✔
531
    @Output() thySortChange: EventEmitter<ThyTableSortEvent> = new EventEmitter<ThyTableSortEvent>();
532

533
    @Output() thyOnRowContextMenu: EventEmitter<ThyTableEvent> = new EventEmitter<ThyTableEvent>();
534

1✔
535
    @ContentChild('group', { static: true }) groupTemplate: TemplateRef<SafeAny>;
536

537
    @ContentChildren(ThyTableColumnComponent)
8!
538
    set listOfColumnComponents(components: QueryList<ThyTableColumnComponent>) {
8✔
539
        if (components) {
47✔
540
            this.columns = components.toArray();
541
            this.hasFixed = !!this.columns.find(item => {
542
                return item.fixed === this.fixedDirection.left || item.fixed === this.fixedDirection.right;
543
            });
544
            this.buildSkeletonColumns();
8✔
545
            this._initializeColumns();
47✔
546
            this._initializeDataModel();
547
        }
548
    }
549

14✔
550
    // 数据的折叠展开状态
14✔
551
    public expandStatusMap: Dictionary<boolean> = {};
14✔
552

28✔
553
    public expandStatusMapOfGroup: Dictionary<boolean> = {};
28!
UNCOV
554

×
555
    private expandStatusMapOfGroupBeforeDrag: Dictionary<boolean> = {};
556

557
    dragPreviewClass = 'thy-table-drag-preview';
28✔
558

559
    public skeletonColumns: ThyTableSkeletonColumn[] = [];
28✔
560

561
    constructor(
562
        public elementRef: ElementRef,
563
        private _differs: IterableDiffers,
13✔
564
        private viewportRuler: ViewportRuler,
13✔
565
        private updateHostClassService: UpdateHostClassService,
79✔
566
        @Inject(DOCUMENT) private document: SafeAny,
79✔
567
        @Inject(PLATFORM_ID) private platformId: string,
78✔
568
        private ngZone: NgZone,
569
        private renderer: Renderer2,
570
        private cdr: ChangeDetectorRef
571
    ) {
572
        this._bindTrackFn();
4✔
573
    }
4✔
574

575
    private _initializeColumns() {
576
        if (!this.columns.some(item => item.expand === true) && this.columns.length > 0) {
1✔
UNCOV
577
            this.columns[0].expand = true;
×
578
        }
579
        this._initializeColumnFixedPositions();
580
    }
581

1✔
582
    private _initializeColumnFixedPositions() {
1✔
583
        const leftFixedColumns = this.columns.filter(item => item.fixed === ThyFixedDirection.left);
584
        leftFixedColumns.forEach((item, index) => {
585
            const previous = leftFixedColumns[index - 1];
586
            item.left = previous ? previous.left + parseInt(previous.width.toString(), 10) : 0;
8✔
587
        });
8✔
588
        const rightFixedColumns = this.columns.filter(item => item.fixed === ThyFixedDirection.right).reverse();
8✔
589
        rightFixedColumns.forEach((item, index) => {
8✔
590
            const previous = rightFixedColumns[index - 1];
8✔
591
            item.right = previous ? previous.right + parseInt(previous.width.toString(), 10) : 0;
8!
UNCOV
592
        });
×
593
    }
×
594

UNCOV
595
    private _initializeDataModel() {
×
UNCOV
596
        this.model.forEach(row => {
×
597
            this.columns.forEach(column => {
598
                this._initialSelections(row, column);
UNCOV
599
                this._initialCustomModelValue(row, column);
×
600
            });
601
        });
602
    }
8!
603

8✔
604
    private _initialSelections(row: object, column: ThyTableColumnComponent) {
605
        if (column.selections) {
8!
UNCOV
606
            if (column.type === 'checkbox') {
×
607
                row[column.key] = column.selections.includes(row[this.rowKey]);
608
                this.onModelChange(row, column);
609
            }
610
            if (column.type === 'radio') {
66✔
611
                if (column.selections.includes(row[this.rowKey])) {
66✔
612
                    this.selectedRadioRow = row;
66✔
613
                }
66✔
614
            }
615
        }
616
    }
8✔
617

8✔
618
    private _initialCustomModelValue(row: object, column: ThyTableColumnComponent) {
8✔
619
        if (column.type === customType.switch) {
620
            row[column.key] = get(row, column.model);
66✔
621
        }
66✔
UNCOV
622
    }
×
623

624
    private _refreshCustomModelValue(row: SafeAny) {
625
        this.columns.forEach(column => {
626
            this._initialCustomModelValue(row, column);
627
        });
66✔
628
    }
66✔
629

377✔
630
    private _applyDiffChanges(changes: IterableChanges<SafeAny>) {
556✔
631
        if (changes) {
682✔
632
            changes.forEachAddedItem((record: IterableChangeRecord<SafeAny>) => {
633
                this._refreshCustomModelValue(record.item);
377✔
634
            });
635
        }
636
    }
637

66!
UNCOV
638
    private _bindTrackFn() {
×
639
        this.trackByFn = function (this: SafeAny, index: number, row: SafeAny): SafeAny {
640
            return row && this.rowKey ? row[this.rowKey] : index;
66✔
641
        }.bind(this);
392✔
642
    }
643

644
    private _destroyInvalidAttribute() {
645
        this.model.forEach(row => {
646
            for (const key in row) {
647
                if (key.includes('[$$column]')) {
648
                    delete row[key];
649
                }
392!
650
            }
651
        });
×
652
    }
653

654
    private _setClass(first = false) {
655
        if (!first && !this.initialized) {
656
            return;
657
        }
658
        const classNames: string[] = [];
659
        if (this.size) {
1!
660
            classNames.push(`table-${this.size}`);
1✔
661
        }
662
        if (tableThemeMap[this.theme]) {
663
            classNames.push(tableThemeMap[this.theme]);
664
        }
665

78✔
666
        this.updateHostClassService.updateClass(classNames);
78✔
667
    }
78✔
668

78✔
669
    public updateColumnSelections(key: string, selections: SafeAny): void {
12✔
670
        const column = this.columns.find(item => item.key === key);
12✔
671
        this.model.forEach(row => {
672
            this._initialSelections(row, column);
78!
673
        });
78✔
674
    }
78✔
675

676
    public isTemplateRef(ref: SafeAny) {
677
        return ref instanceof TemplateRef;
678
    }
70✔
679

680
    public getModelValue(row: SafeAny, path: string) {
1✔
681
        return get(row, path);
682
    }
683

684
    public renderRowClassName(row: SafeAny, index: number) {
685
        if (!this.rowClassName) {
686
            return null;
687
        }
688
        if (isString(this.rowClassName)) {
689
            return this.rowClassName;
690
        } else {
691
            return (this.rowClassName as Function)(row, index);
1✔
692
        }
693
    }
694

695
    public onModelChange(row: SafeAny, column: ThyTableColumnComponent) {
696
        if (column.model) {
697
            set(row, column.model, row[column.key]);
698
        }
699
    }
700

701
    public onStopPropagation(event: Event) {
702
        if (this.wholeRowSelect) {
703
            event.stopPropagation();
704
        }
705
    }
706

707
    public onPageChange(event: PageChangedEvent) {
708
        this.thyOnPageChange.emit(event);
709
    }
710

711
    public onPageIndexChange(event: number) {
712
        this.thyOnPageIndexChange.emit(event);
713
    }
714

715
    public onPageSizeChange(event: number) {
716
        this.thyOnPageSizeChange.emit(event);
717
    }
718

719
    public onCheckboxChange(row: SafeAny, column: ThyTableColumnComponent) {
720
        this.onModelChange(row, column);
721
        this.onMultiSelectChange(null, row, column);
722
    }
723

724
    public onMultiSelectChange(event: Event, row: SafeAny, column: ThyTableColumnComponent) {
725
        const rows = this.model.filter(item => {
726
            return item[column.key];
727
        });
728
        const multiSelectEvent: ThyMultiSelectEvent = {
729
            event: event,
730
            row: row,
731
            rows: rows
732
        };
733
        this.thyOnMultiSelectChange.emit(multiSelectEvent);
734
    }
735

736
    public onRadioSelectChange(event: Event, row: SafeAny) {
737
        const radioSelectEvent: ThyRadioSelectEvent = {
738
            event: event,
739
            row: row
740
        };
1✔
741
        this.thyOnRadioSelectChange.emit(radioSelectEvent);
742
    }
743

744
    public onSwitchChange(event: Event, row: SafeAny, column: SafeAny) {
1✔
745
        const switchEvent: ThySwitchEvent = {
746
            event: event,
747
            row: row,
748
            refresh: (value: SafeAny) => {
1✔
749
                value = value || row;
750
                setTimeout(() => {
751
                    value[column.key] = get(value, column.model);
752
                });
753
            }
754
        };
755
        this.thyOnSwitchChange.emit(switchEvent);
756
    }
757

758
    showExpand(row: SafeAny) {
759
        return row[this.thyChildrenKey] && row[this.thyChildrenKey].length > 0;
760
    }
761

762
    isExpanded(row: SafeAny) {
763
        return this.expandStatusMap[row[this.rowKey]];
764
    }
765

766
    iconIndentComputed(level: number) {
767
        if (this.mode === 'tree') {
768
            return level * this.thyIndent - 5;
769
        }
770
    }
771

772
    tdIndentComputed(level: number, column: SafeAny) {
773
        return {
774
            left: `${column.left}px`,
775
            right: `${column.right}px`,
776
            position: 'relative',
777
            paddingLeft: `${(level + 1) * this.thyIndent - 5}px`
778
        };
779
    }
780

781
    expandChildren(row: SafeAny) {
782
        if (this.isExpanded(row)) {
783
            this.expandStatusMap[row[this.rowKey]] = false;
784
        } else {
785
            this.expandStatusMap[row[this.rowKey]] = true;
786
        }
787
    }
788

789
    onDragGroupStarted(event: CdkDragStart<unknown>) {
790
        this.expandStatusMapOfGroupBeforeDrag = { ...this.expandStatusMapOfGroup };
791
        const groups = this.groups.filter(group => group.expand);
792
        this.foldGroups(groups);
793
        this.onDragStarted(event);
794
        this.cdr.detectChanges();
795
    }
796

797
    onDragGroupEnd(event: CdkDragEnd<unknown>) {
798
        const groups = this.groups.filter(group => this.expandStatusMapOfGroupBeforeDrag[group.id]);
799
        this.expandGroups(groups);
800
        this.cdr.detectChanges();
801
    }
802

803
    private onDragGroupDropped(event: CdkDragDrop<unknown>) {
804
        const group = this.groups.find(group => {
805
            return event.item.data.id === group.id;
806
        });
807
        if (group) {
808
            // drag group
809
            const dragEvent: ThyTableDraggableEvent = {
810
                model: event.item,
811
                models: this.groups,
812
                oldIndex: event.previousIndex,
813
                newIndex: event.currentIndex
814
            };
815
            moveItemInArray(this.groups, event.previousIndex, event.currentIndex);
816
            this.thyOnDraggableChange.emit(dragEvent);
817
        } else {
818
            // drag group children
819
            const group = this.groups.find(group => {
820
                return event.item.data[this.groupBy] === group.id;
821
            });
822
            const groupIndex =
823
                event.container.getSortedItems().findIndex(item => {
824
                    return item.data.id === event.item.data[this.groupBy];
825
                }) + 1;
826
            const dragEvent: ThyTableDraggableEvent = {
827
                model: event.item,
828
                models: group.children,
829
                oldIndex: event.previousIndex - groupIndex,
830
                newIndex: event.currentIndex - groupIndex
831
            };
832
            moveItemInArray(group.children, dragEvent.oldIndex, dragEvent.newIndex);
833
            this.thyOnDraggableChange.emit(dragEvent);
834
        }
835
    }
836

837
    onDragStarted(event: CdkDragStart<unknown>) {
838
        this.ngZone.runOutsideAngular(() =>
839
            setTimeout(() => {
840
                const preview = this.document.getElementsByClassName(this.dragPreviewClass)[0];
841
                const originalTds: HTMLCollection = event.source._dragRef.getPlaceholderElement()?.children;
842
                if (preview) {
843
                    Array.from(preview?.children).forEach((element: HTMLElement, index: number) => {
844
                        element.style.width = `${originalTds[index]?.clientWidth}px`;
845
                    });
846
                }
847
            })
848
        );
849
    }
850

851
    dropListEnterPredicate = (index: number, drag: CdkDrag, drop: CdkDropList) => {
852
        return drop.getSortedItems()[index].data.group_id === drag.data.group_id;
853
    };
854

855
    private onDragModelDropped(event: CdkDragDrop<unknown>) {
856
        const dragEvent: ThyTableDraggableEvent = {
857
            model: event.item,
858
            models: this.model,
859
            oldIndex: event.previousIndex,
860
            newIndex: event.currentIndex
861
        };
862
        moveItemInArray(this.model, event.previousIndex, event.currentIndex);
863
        this.thyOnDraggableChange.emit(dragEvent);
864
    }
865

866
    onDragDropped(event: CdkDragDrop<unknown>) {
867
        if (this.mode === 'group') {
868
            this.onDragGroupDropped(event);
869
        } else if (this.mode === 'list') {
870
            this.onDragModelDropped(event);
871
        }
872
    }
873

874
    onColumnHeaderClick(event: Event, column: ThyTableColumnComponent) {
875
        if (column.sortable) {
876
            const { sortDirection, model, sortChange } = column;
877
            let direction;
878
            if (sortDirection === ThyTableSortDirection.default) {
879
                direction = ThyTableSortDirection.desc;
880
            } else if (sortDirection === ThyTableSortDirection.desc) {
881
                direction = ThyTableSortDirection.asc;
882
            } else {
883
                direction = ThyTableSortDirection.default;
884
            }
885
            column.sortDirection = direction;
886
            const sortEvent = { event, key: model, direction };
887
            sortChange.emit(sortEvent);
888
            this.thySortChange.emit(sortEvent);
889
        }
890
    }
891

892
    public onRowClick(event: Event, row: SafeAny) {
893
        const next = this.onRowClickPropagationEventHandler(event, row);
894
        if (next) {
895
            if (this.wholeRowSelect) {
896
                const column = this.columns.find(item => {
897
                    return item.type === customType.checkbox || item.type === customType.radio;
898
                });
899
                if (column && !column.disabled) {
900
                    if (column.type === customType.checkbox) {
901
                        row[column.key] = !row[column.key];
902
                        this.onModelChange(row, column);
903
                        this.onMultiSelectChange(event, row, column);
904
                    }
905
                    if (column.type === customType.radio) {
906
                        this.selectedRadioRow = row;
907
                        this.onRadioSelectChange(event, row);
908
                    }
909
                }
910
            }
911
            const rowEvent = {
912
                event: event,
913
                row: row
914
            };
915
            this.thyOnRowClick.emit(rowEvent);
916
        }
917
    }
918

919
    private onRowClickPropagationEventHandler(event: Event, row: SafeAny): boolean {
920
        if ((event.target as Element).closest('.tree-expand-icon')) {
921
            this.expandChildren(row);
922
            return false;
923
        }
924
        return true;
925
    }
926

927
    public onRowContextMenu(event: Event, row: SafeAny) {
928
        const contextMenuEvent: ThyTableEvent = {
929
            event: event,
930
            row: row
931
        };
932
        this.thyOnRowContextMenu.emit(contextMenuEvent);
933
    }
934

935
    private _refreshColumns() {
936
        const components = this.columns || [];
937
        const _columns = components.map(component => {
938
            return {
939
                width: component.width,
940
                className: component.className
941
            };
942
        });
943

944
        this.columns.forEach((n, i) => {
945
            Object.assign(n, _columns[i]);
946
        });
947
    }
948

949
    private buildGroups(originGroups: SafeAny) {
950
        const originGroupsMap = helpers.keyBy(originGroups, 'id');
951
        this.groups = [];
952
        originGroups.forEach((origin: SafeAny) => {
953
            const group: ThyTableGroup = { id: origin[this.rowKey], children: [], origin };
954

955
            if (this.expandStatusMapOfGroup.hasOwnProperty(group.id)) {
956
                group.expand = this.expandStatusMapOfGroup[group.id];
957
            } else {
958
                group.expand = !!(originGroupsMap[group.id] as SafeAny).expand;
959
            }
960

961
            this.groups.push(group);
962
        });
963
    }
964

965
    private buildModel() {
966
        const groupsMap = keyBy(this.groups, 'id');
967
        this.model.forEach(row => {
968
            const group = groupsMap[row[this.groupBy]];
969
            if (group) {
970
                group.children.push(row);
971
            }
972
        });
973
    }
974

975
    public expandGroup(group: ThyTableGroup) {
976
        group.expand = !group.expand;
977
        this.expandStatusMapOfGroup[group.id] = group.expand;
978
    }
979

980
    private expandGroups(groups: ThyTableGroup[]) {
981
        groups.forEach(group => {
982
            this.expandGroup(group);
983
        });
984
    }
985

986
    private foldGroups(groups: ThyTableGroup[]) {
987
        groups.forEach(group => {
988
            this.expandGroup(group);
989
        });
990
    }
991

992
    private updateScrollClass() {
993
        const scrollElement = this.tableScrollElement;
994
        const maxScrollLeft = scrollElement.scrollWidth - scrollElement.offsetWidth;
995
        const scrollX = scrollElement.scrollLeft;
996
        const lastScrollClassName = this.scrollClassName;
997
        this.scrollClassName = '';
998
        if (scrollElement.scrollWidth > scrollElement.clientWidth) {
999
            if (scrollX >= maxScrollLeft) {
1000
                this.scrollClassName = css.tableScrollRight;
1001
            } else if (scrollX === 0) {
1002
                this.scrollClassName = css.tableScrollLeft;
1003
            } else {
1004
                this.scrollClassName = css.tableScrollMiddle;
1005
            }
1006
        }
1007
        if (lastScrollClassName) {
1008
            this.renderer.removeClass(this.tableScrollElement, lastScrollClassName);
1009
        }
1010
        if (this.scrollClassName) {
1011
            this.renderer.addClass(this.tableScrollElement, this.scrollClassName);
1012
        }
1013
    }
1014

1015
    ngOnInit() {
1016
        this.updateHostClassService.initializeElement(this.tableElementRef.nativeElement);
1017
        this._setClass(true);
1018
        this.initialized = true;
1019

1020
        merge(this.viewportRuler.change(200), of(null).pipe(delay(200)))
1021
            .pipe(takeUntilDestroyed(this.destroyRef))
1022
            .subscribe(() => {
1023
                this._refreshColumns();
1024
                this.updateScrollClass();
1025
                this.cdr.detectChanges();
1026
            });
1027

1028
        this.ngZone.runOutsideAngular(() => {
1029
            this.scroll$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
1030
                this.updateScrollClass();
1031
            });
1032
        });
1033
    }
1034

1035
    private buildSkeletonColumns() {
1036
        this.skeletonColumns = [];
1037

1038
        this.columns.forEach((column: ThyTableColumnComponent, index: number) => {
1039
            const item = {
1040
                type: this.thyColumnSkeletonTypes[index] || ThyTableColumnSkeletonType.default,
1041
                width: column.width || 'auto'
1042
            };
1043
            this.skeletonColumns = [...this.skeletonColumns, item];
1044
        });
1045
    }
1046

1047
    ngAfterViewInit(): void {
1048
        if (isPlatformServer(this.platformId)) {
1049
            return;
1050
        }
1051

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

1094
    ngOnChanges(simpleChanges: SimpleChanges) {
1095
        const modeChange = simpleChanges.thyMode;
1096
        const thyGroupsChange = simpleChanges.thyGroups;
1097
        const isGroupMode = modeChange && modeChange.currentValue === 'group';
1098
        if (isGroupMode && thyGroupsChange && thyGroupsChange.firstChange) {
1099
            this.buildGroups(thyGroupsChange.currentValue);
1100
            this.buildModel();
1101
        }
1102

1103
        if (this._diff) {
1104
            const changes = this._diff.diff(this.model);
1105
            this._applyDiffChanges(changes);
1106
        }
1107
    }
1108

1109
    ngOnDestroy() {
1110
        this._destroyInvalidAttribute();
1111
    }
1112
}
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