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

atinc / ngx-tethys / cd64db52-e563-41a3-85f3-a0adb87ce135

30 Oct 2024 08:03AM UTC coverage: 90.402% (-0.04%) from 90.438%
cd64db52-e563-41a3-85f3-a0adb87ce135

push

circleci

web-flow
refactor: refactor constructor to the inject function (#3222)

5503 of 6730 branches covered (81.77%)

Branch coverage included in aggregate %.

422 of 429 new or added lines in 170 files covered. (98.37%)

344 existing lines in 81 files now uncovered.

13184 of 13941 relevant lines covered (94.57%)

997.19 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
    Input,
24
    IterableChangeRecord,
25
    IterableChanges,
26
    IterableDiffer,
27
    IterableDiffers,
1✔
28
    NgZone,
1✔
29
    numberAttribute,
1✔
30
    OnChanges,
2✔
31
    OnDestroy,
1✔
32
    OnInit,
33
    Output,
34
    PLATFORM_ID,
35
    QueryList,
36
    Renderer2,
1✔
37
    SimpleChanges,
38
    TemplateRef,
39
    ViewChild,
40
    ViewChildren,
41
    ViewEncapsulation
42
} from '@angular/core';
1✔
43

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

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

3✔
73
export type ThyTableMode = 'list' | 'group' | 'tree';
74

75
export type ThyTableSize = 'md' | 'sm' | 'xs' | 'lg' | 'xlg' | 'default';
76

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

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

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

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

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

109
const passiveEventListenerOptions = normalizePassiveListenerOptions({ passive: true });
110

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

70✔
164
    private readonly destroyRef = inject(DestroyRef);
70✔
165

70✔
166
    public customType = customType;
70✔
167

70✔
168
    public model: object[] = [];
70✔
169

70✔
170
    public groups: ThyTableGroup[] = [];
70✔
171

70✔
172
    public rowKey = '_id';
70✔
173

70✔
174
    public groupBy: string;
70✔
175

70✔
176
    public mode: ThyTableMode = 'list';
70✔
177

70✔
178
    public theme: ThyTableTheme = 'default';
70✔
179

70✔
180
    public className = '';
70✔
181

70✔
182
    public size: ThyTableSize = 'md';
70✔
183

70✔
184
    public rowClassName: string | Function;
70✔
185

70✔
186
    public loadingDone = true;
70✔
187

70✔
188
    public loadingText: string;
70✔
189

384✔
190
    public emptyOptions: ThyTableEmptyOptions = {};
70✔
191

192
    public draggable = false;
193

194
    public selectedRadioRow: SafeAny = null;
195

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

70✔
198
    public trackByFn: SafeAny;
70✔
199

70✔
200
    public wholeRowSelect = false;
70✔
201

70✔
202
    public fixedDirection = ThyFixedDirection;
70✔
203

70✔
204
    public hasFixed = false;
70✔
205

206
    public columns: ThyTableColumnComponent[] = [];
70✔
207

70✔
208
    private _diff: IterableDiffer<SafeAny>;
70✔
209

70✔
210
    private initialized = false;
70✔
211

70✔
UNCOV
212
    private _oldThyClassName = '';
×
213

214
    private scrollClassName = css.tableScrollLeft;
70✔
215

216
    private get tableScrollElement(): HTMLElement {
217
        return this.elementRef.nativeElement.getElementsByClassName(css.tableBody)[0] as HTMLElement;
374✔
218
    }
65✔
219

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

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

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

1!
232
    @ViewChildren('rows', { read: ElementRef }) rows: QueryList<ElementRef<HTMLElement>>;
233

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

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

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

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

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

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

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

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

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

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

×
320
    /**
321
     * 是否表头固定,若设置为 true, 需要同步设置 thyHeight
322
     * @default false
323
     */
249!
324
    @Input({ transform: coerceBooleanProperty }) thyHeaderFixed: boolean;
249✔
325

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

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

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

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

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

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

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

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

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

415
    /**
416
     * 设置总页数
2✔
417
     */
3✔
418
    @Input({ transform: numberAttribute })
419
    set thyPageTotal(value: number) {
2✔
420
        this.pagination.total = value;
421
    }
1✔
422

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

435
    /**
1✔
436
     * 是否显示表格头
2✔
437
     * @default false
438
     */
1✔
439
    @Input({ transform: coerceBooleanProperty }) thyHeadless = false;
440

441
    /**
442
     * 是否显示表格头,已废弃,请使用 thyHeadless
443
     * @deprecated please use thyHeadless
444
     */
1✔
445
    @Input({ transform: coerceBooleanProperty })
1✔
446
    set thyShowHeader(value: boolean) {
447
        this.thyHeadless = !value;
448
    }
449

3✔
450
    /**
3✔
451
     * 是否显示左侧 Total
3✔
452
     */
3!
453
    @Input({ alias: 'thyShowTotal', transform: coerceBooleanProperty }) showTotal = false;
3✔
454

12✔
455
    /**
456
     * 是否显示调整每页显示条数下拉框
457
     */
458
    @Input({ alias: 'thyShowSizeChanger', transform: coerceBooleanProperty }) showSizeChanger = false;
459

460
    /**
1✔
461
     * 每页显示条数下拉框可选项
462
     * @type number[]
463
     */
464
    @Input('thyPageSizeOptions')
465
    set pageSizeOptions(value: number[]) {
466
        this.pagination.sizeOptions = value;
1✔
467
    }
1✔
468

469
    /**
470
     * thyMode 为 tree 时,设置 Tree 树状数据展示时的缩进
3✔
471
     */
2✔
472
    @Input({ transform: numberAttribute }) thyIndent = 20;
473

1!
474
    /**
1✔
475
     * thyMode 为 tree 时,设置 Tree 树状数据对象中的子节点 Key
476
     * @type string
477
     */
478
    @Input() thyChildrenKey = 'children';
3!
479

3✔
480
    /**
481
     * 开启 Hover 后显示操作,默认不显示操作区内容,鼠标 Hover 时展示
3✔
482
     * @default false
1✔
483
     */
484
    @HostBinding('class.thy-table-hover-display-operation')
2✔
485
    @Input({ transform: coerceBooleanProperty })
1✔
486
    thyHoverDisplayOperation: boolean;
487

488
    @Input() thyDragDisabledPredicate: (item: SafeAny) => boolean = () => false;
1✔
489

490
    /**
3✔
491
     * 表格列的骨架类型
3✔
492
     * @type ThyTableColumnSkeletonType[]
3✔
493
     */
3✔
494
    @Input() thyColumnSkeletonTypes: ThyTableColumnSkeletonType[] = [
495
        ThyTableColumnSkeletonType.title,
496
        ThyTableColumnSkeletonType.member,
497
        ThyTableColumnSkeletonType.default
11✔
498
    ];
11✔
499

4✔
500
    /**
2✔
501
     * 切换组件回调事件
2✔
502
     */
503
    @Output() thyOnSwitchChange: EventEmitter<ThySwitchEvent> = new EventEmitter<ThySwitchEvent>();
2!
504

2✔
505
    /**
1✔
506
     * 表格分页回调事件
1✔
507
     */
1✔
508
    @Output() thyOnPageChange: EventEmitter<PageChangedEvent> = new EventEmitter<PageChangedEvent>();
509

2✔
510
    /**
1✔
511
     * 表格分页当前页改变回调事件
1✔
512
     */
513
    @Output() thyOnPageIndexChange: EventEmitter<number> = new EventEmitter<number>();
514

515
    @Output() thyOnPageSizeChange: EventEmitter<number> = new EventEmitter<number>();
4✔
516

517
    /**
518
     * 多选回调事件
519
     */
4✔
520
    @Output() thyOnMultiSelectChange: EventEmitter<ThyMultiSelectEvent> = new EventEmitter<ThyMultiSelectEvent>();
521

522
    /**
523
     * 单选回调事件
11✔
524
     */
7✔
525
    @Output() thyOnRadioSelectChange: EventEmitter<ThyRadioSelectEvent> = new EventEmitter<ThyRadioSelectEvent>();
7✔
526

527
    /**
4✔
528
     * 拖动修改事件
529
     */
530
    @Output() thyOnDraggableChange: EventEmitter<ThyTableDraggableEvent> = new EventEmitter<ThyTableDraggableEvent>();
1✔
531

532
    /**
533
     * 表格行点击触发事件
534
     */
1✔
535
    @Output() thyOnRowClick: EventEmitter<ThyTableRowEvent> = new EventEmitter<ThyTableRowEvent>();
536

537
    /**
8!
538
     * 列排序修改事件
8✔
539
     */
47✔
540
    @Output() thySortChange: EventEmitter<ThyTableSortEvent> = new EventEmitter<ThyTableSortEvent>();
541

542
    @Output() thyOnRowContextMenu: EventEmitter<ThyTableEvent> = new EventEmitter<ThyTableEvent>();
543

544
    @ContentChild('group', { static: true }) groupTemplate: TemplateRef<SafeAny>;
8✔
545

47✔
546
    @ContentChildren(ThyTableColumnComponent)
547
    set listOfColumnComponents(components: QueryList<ThyTableColumnComponent>) {
548
        if (components) {
549
            this.columns = components.toArray();
14✔
550
            this.hasFixed = !!this.columns.find(item => {
14✔
551
                return item.fixed === this.fixedDirection.left || item.fixed === this.fixedDirection.right;
14✔
552
            });
28✔
553
            this.buildSkeletonColumns();
28!
UNCOV
554
            this._initializeColumns();
×
555
            this._initializeDataModel();
556
        }
557
    }
28✔
558

559
    // 数据的折叠展开状态
28✔
560
    public expandStatusMap: Dictionary<boolean> = {};
561

562
    public expandStatusMapOfGroup: Dictionary<boolean> = {};
563

13✔
564
    private expandStatusMapOfGroupBeforeDrag: Dictionary<boolean> = {};
13✔
565

79✔
566
    dragPreviewClass = 'thy-table-drag-preview';
79✔
567

78✔
568
    public skeletonColumns: ThyTableSkeletonColumn[] = [];
569

570
    constructor() {
571
        this._bindTrackFn();
572
    }
4✔
573

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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