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

atinc / ngx-tethys / 755c8f67-68c9-45a3-92c8-c397f26c8338

24 May 2024 09:49AM UTC coverage: 90.398% (+0.005%) from 90.393%
755c8f67-68c9-45a3-92c8-c397f26c8338

push

circleci

why520crazy
fix(table): change bind style with ngStyle #INFR-12443

5439 of 6663 branches covered (81.63%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

9 existing lines in 1 file now uncovered.

13183 of 13937 relevant lines covered (94.59%)

983.66 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 { 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, NgFor, NgIf, NgTemplateOutlet, NgStyle } from '@angular/common';
12
import {
13
    AfterViewInit,
14
    booleanAttribute,
15
    ChangeDetectorRef,
16
    Component,
17
    ContentChild,
18
    ContentChildren,
19
    DestroyRef,
20
    ElementRef,
21
    EventEmitter,
22
    HostBinding,
23
    inject,
24
    Inject,
25
    Input,
26
    IterableChangeRecord,
27
    IterableChanges,
1✔
28
    IterableDiffer,
1✔
29
    IterableDiffers,
1✔
30
    NgZone,
2✔
31
    numberAttribute,
1✔
32
    OnChanges,
33
    OnDestroy,
34
    OnInit,
35
    Output,
36
    PLATFORM_ID,
1✔
37
    QueryList,
38
    Renderer2,
39
    SimpleChanges,
40
    TemplateRef,
41
    ViewChild,
42
    ViewChildren,
1✔
43
    ViewEncapsulation
44
} from '@angular/core';
45

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

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

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

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

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

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

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

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

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

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

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

70✔
160
    public customType = customType;
70✔
161

70✔
162
    public model: object[] = [];
70✔
163

70✔
164
    public groups: ThyTableGroup[] = [];
70✔
165

70✔
166
    public rowKey = '_id';
70✔
167

70✔
168
    public groupBy: string;
70✔
169

70✔
170
    public mode: ThyTableMode = 'list';
70✔
171

70✔
172
    public theme: ThyTableTheme = 'default';
70✔
173

70✔
174
    public className = '';
70✔
175

70✔
176
    public size: ThyTableSize = 'md';
70✔
177

70✔
178
    public rowClassName: string | Function;
70✔
179

70✔
180
    public loadingDone = true;
70✔
181

70✔
182
    public loadingText: string;
70✔
183

70✔
184
    public emptyOptions: ThyTableEmptyOptions = {};
70✔
185

70✔
186
    public draggable = false;
70✔
187

70✔
188
    public selectedRadioRow: SafeAny = null;
70✔
189

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

192
    public trackByFn: SafeAny;
193

194
    public wholeRowSelect = false;
195

70✔
196
    public fixedDirection = ThyFixedDirection;
70✔
197

70✔
198
    public hasFixed = false;
70✔
199

70✔
200
    public columns: ThyTableColumnComponent[] = [];
70✔
201

70✔
202
    private _diff: IterableDiffer<SafeAny>;
70✔
203

70✔
204
    private initialized = false;
70✔
205

206
    private _oldThyClassName = '';
70✔
207

70✔
208
    private scrollClassName = css.tableScrollLeft;
70✔
209

70✔
210
    private get tableScrollElement(): HTMLElement {
70✔
211
        return this.elementRef.nativeElement.getElementsByClassName(css.tableBody)[0] as HTMLElement;
70✔
212
    }
×
213

214
    private get scroll$() {
70✔
215
        return merge(this.tableScrollElement ? fromEvent<MouseEvent>(this.tableScrollElement, 'scroll') : EMPTY);
216
    }
217

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

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

4✔
226
    @ViewChildren('rows', { read: ElementRef }) rows: QueryList<ElementRef<HTMLElement>>;
4✔
227

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

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

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

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

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

70✔
274
        if (this.mode === 'group') {
634!
275
            this.buildModel();
276
        }
277
    }
278

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

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

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

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

410✔
314
    /**
315
     * 是否表头固定,若设置为 true, 需要同步设置 thyHeight
810!
316
     * @default false
810✔
317
     */
318
    @Input({ transform: booleanAttribute }) thyHeaderFixed: boolean;
319

×
320
    /**
321
     * 表格的高度
322
     */
323
    @HostBinding('style.height')
249!
324
    @Input()
249✔
325
    @InputCssPixel()
326
    thyHeight: string;
327

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

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

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

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

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

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

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

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

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

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

1✔
429
    /**
430
     * 是否显示表格头
431
     * @default false
432
     */
1✔
433
    @Input({ transform: booleanAttribute }) thyHeadless = false;
2✔
434

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

444
    /**
1✔
445
     * 是否显示左侧 Total
1✔
446
     */
447
    @Input({ alias: 'thyShowTotal', transform: booleanAttribute }) showTotal = false;
448

449
    /**
3✔
450
     * 是否显示调整每页显示条数下拉框
3✔
451
     */
3✔
452
    @Input({ alias: 'thyShowSizeChanger', transform: booleanAttribute }) showSizeChanger = false;
3!
453

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

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

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

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

3✔
482
    @Input() thyDragDisabledPredicate: (item: SafeAny) => boolean = () => false;
1✔
483

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

3✔
494
    /**
495
     * 切换组件回调事件
496
     */
497
    @Output() thyOnSwitchChange: EventEmitter<ThySwitchEvent> = new EventEmitter<ThySwitchEvent>();
11✔
498

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

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

509
    @Output() thyOnPageSizeChange: EventEmitter<number> = new EventEmitter<number>();
2✔
510

1✔
511
    /**
1✔
512
     * 多选回调事件
513
     */
514
    @Output() thyOnMultiSelectChange: EventEmitter<ThyMultiSelectEvent> = new EventEmitter<ThyMultiSelectEvent>();
515

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

521
    /**
522
     * 拖动修改事件
523
     */
11✔
524
    @Output() thyOnDraggableChange: EventEmitter<ThyTableDraggableEvent> = new EventEmitter<ThyTableDraggableEvent>();
7✔
525

7✔
526
    /**
527
     * 表格行点击触发事件
4✔
528
     */
529
    @Output() thyOnRowClick: EventEmitter<ThyTableRowEvent> = new EventEmitter<ThyTableRowEvent>();
530

1✔
531
    /**
532
     * 列排序修改事件
533
     */
534
    @Output() thySortChange: EventEmitter<ThyTableSortEvent> = new EventEmitter<ThyTableSortEvent>();
1✔
535

536
    @Output() thyOnRowContextMenu: EventEmitter<ThyTableEvent> = new EventEmitter<ThyTableEvent>();
537

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

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

28✔
553
    // 数据的折叠展开状态
28!
UNCOV
554
    public expandStatusMap: Dictionary<boolean> = {};
×
555

556
    public expandStatusMapOfGroup: Dictionary<boolean> = {};
557

28✔
558
    private expandStatusMapOfGroupBeforeDrag: Dictionary<boolean> = {};
559

28✔
560
    dragPreviewClass = 'thy-table-drag-preview';
561

562
    public skeletonColumns: ThyTableSkeletonColumn[] = [];
563

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

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

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

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

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

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

627
    private _refreshCustomModelValue(row: SafeAny) {
66✔
628
        this.columns.forEach(column => {
66✔
629
            this._initialCustomModelValue(row, column);
377✔
630
        });
556✔
631
    }
682✔
632

633
    private _applyDiffChanges(changes: IterableChanges<SafeAny>) {
377✔
634
        if (changes) {
635
            changes.forEachAddedItem((record: IterableChangeRecord<SafeAny>) => {
636
                this._refreshCustomModelValue(record.item);
637
            });
66!
UNCOV
638
        }
×
639
    }
640

66✔
641
    private _bindTrackFn() {
392✔
642
        this.trackByFn = function (this: SafeAny, index: number, row: SafeAny): SafeAny {
643
            return row && this.rowKey ? row[this.rowKey] : index;
644
        }.bind(this);
645
    }
646

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

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

78✔
669
        this.updateHostClassService.updateClass(classNames);
12✔
670
    }
12✔
671

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

70✔
679
    public isTemplateRef(ref: SafeAny) {
680
        return ref instanceof TemplateRef;
1✔
681
    }
682

683
    public getModelValue(row: SafeAny, path: string) {
684
        return get(row, path);
685
    }
686

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

698
    public onModelChange(row: SafeAny, column: ThyTableColumnComponent) {
699
        if (column.model) {
700
            set(row, column.model, row[column.key]);
701
        }
702
    }
703

704
    public onStopPropagation(event: Event) {
705
        if (this.wholeRowSelect) {
706
            event.stopPropagation();
707
        }
708
    }
709

710
    public onPageChange(event: PageChangedEvent) {
711
        this.thyOnPageChange.emit(event);
712
    }
713

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

718
    public onPageSizeChange(event: number) {
719
        this.thyOnPageSizeChange.emit(event);
720
    }
721

722
    public onCheckboxChange(row: SafeAny, column: ThyTableColumnComponent) {
723
        this.onModelChange(row, column);
724
        this.onMultiSelectChange(null, row, column);
725
    }
726

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

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

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

761
    showExpand(row: SafeAny) {
762
        return row[this.thyChildrenKey] && row[this.thyChildrenKey].length > 0;
763
    }
764

765
    isExpanded(row: SafeAny) {
766
        return this.expandStatusMap[row[this.rowKey]];
767
    }
768

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

947
        this.columns.forEach((n, i) => {
948
            Object.assign(n, _columns[i]);
949
        });
950
    }
951

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

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

964
            this.groups.push(group);
965
        });
966
    }
967

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

978
    public expandGroup(group: ThyTableGroup) {
979
        group.expand = !group.expand;
980
        this.expandStatusMapOfGroup[group.id] = group.expand;
981
    }
982

983
    private expandGroups(groups: ThyTableGroup[]) {
984
        groups.forEach(group => {
985
            this.expandGroup(group);
986
        });
987
    }
988

989
    private foldGroups(groups: ThyTableGroup[]) {
990
        groups.forEach(group => {
991
            this.expandGroup(group);
992
        });
993
    }
994

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

1018
    ngOnInit() {
1019
        this.updateHostClassService.initializeElement(this.tableElementRef.nativeElement);
1020
        this._setClass(true);
1021
        this.initialized = true;
1022

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

1031
        this.ngZone.runOutsideAngular(() => {
1032
            this.scroll$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
1033
                this.updateScrollClass();
1034
            });
1035
        });
1036
    }
1037

1038
    private buildSkeletonColumns() {
1039
        this.skeletonColumns = [];
1040

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

1050
    ngAfterViewInit(): void {
1051
        if (isPlatformServer(this.platformId)) {
1052
            return;
1053
        }
1054

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

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

1106
        if (this._diff) {
1107
            const changes = this._diff.diff(this.model);
1108
            this._applyDiffChanges(changes);
1109
        }
1110
    }
1111

1112
    ngOnDestroy() {
1113
        this._destroyInvalidAttribute();
1114
    }
1115
}
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