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

atinc / ngx-tethys / 351f9d2a-df18-4e41-82d3-a66582fb6ff5

17 Jul 2024 02:24AM UTC coverage: 90.465% (+0.01%) from 90.454%
351f9d2a-df18-4e41-82d3-a66582fb6ff5

Pull #3124

circleci

mengshuicmq
test(tree-select): add test
Pull Request #3124: fix(tree-select): #INFR-12947 change treeNodes when thyVirtualScroll…

5491 of 6714 branches covered (81.78%)

Branch coverage included in aggregate %.

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

10 existing lines in 1 file now uncovered.

13238 of 13989 relevant lines covered (94.63%)

997.55 hits per line

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

88.14
/src/tree-select/tree-select.component.ts
1
import {
2
    EXPANDED_DROPDOWN_POSITIONS,
3
    getFlexiblePositions,
4
    scaleYMotion,
5
    TabIndexDisabledControlValueAccessorMixin,
6
    ThyClickDispatcher
7
} from 'ngx-tethys/core';
8
import { ThyEmpty } from 'ngx-tethys/empty';
9
import { ThyFlexibleText } from 'ngx-tethys/flexible-text';
10
import { ThyIcon } from 'ngx-tethys/icon';
11
import { ThySelectControl, ThyStopPropagationDirective } from 'ngx-tethys/shared';
12
import { ThyTreeNode } from 'ngx-tethys/tree';
13
import { coerceBooleanProperty, elementMatchClosest, isArray, isObject, produce, warnDeprecation } from 'ngx-tethys/util';
14
import { Observable, of, Subject } from 'rxjs';
15
import { take, takeUntil } from 'rxjs/operators';
16

17
import { CdkConnectedOverlay, CdkOverlayOrigin, ConnectionPositionPair, ViewportRuler } from '@angular/cdk/overlay';
×
18
import { CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
2✔
19
import { isPlatformBrowser, NgClass, NgFor, NgIf, NgStyle, NgTemplateOutlet } from '@angular/common';
17✔
20
import {
2✔
21
    ChangeDetectorRef,
2✔
22
    Component,
23
    ContentChild,
15!
24
    ElementRef,
15✔
25
    EventEmitter,
15✔
26
    forwardRef,
2✔
27
    HostBinding,
2✔
28
    Inject,
29
    Input,
30
    NgZone,
15✔
31
    OnDestroy,
32
    OnInit,
4✔
33
    Output,
2✔
34
    PLATFORM_ID,
35
    TemplateRef,
36
    ViewChild
37
} from '@angular/core';
38
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
39

40
import { ThyTreeSelectNode, ThyTreeSelectType } from './tree-select.class';
1✔
41

42
type InputSize = 'xs' | 'sm' | 'md' | 'lg' | '';
40✔
43

40✔
44
export function filterTreeData(treeNodes: ThyTreeSelectNode[], searchText: string, searchKey: string = 'name') {
40✔
45
    const filterNodes = (node: ThyTreeSelectNode, result: ThyTreeSelectNode[]) => {
1✔
46
        if (node[searchKey] && node[searchKey].indexOf(searchText) !== -1) {
1✔
47
            result.push(node);
1!
48
            return result;
1✔
49
        }
50
        if (Array.isArray(node.children)) {
51
            const nodes = node.children.reduce((previous, current) => filterNodes(current, previous), [] as ThyTreeSelectNode[]);
52
            if (nodes.length) {
53
                const parentNode = { ...node, children: nodes, expand: true };
196✔
54
                result.push(parentNode);
55
            }
56
        }
196✔
57
        return result;
58
    };
UNCOV
59
    const treeData = treeNodes.reduce((previous, current) => filterNodes(current, previous), [] as ThyTreeSelectNode[]);
×
UNCOV
60
    return treeData;
×
61
}
62

63
/**
64
 * 树选择组件
65
 * @name thy-tree-select
66
 * @order 10
67
 */
68
@Component({
69
    selector: 'thy-tree-select',
4✔
70
    templateUrl: './tree-select.component.html',
2✔
71
    providers: [
72
        {
73
            provide: NG_VALUE_ACCESSOR,
2✔
74
            useExisting: forwardRef(() => ThyTreeSelect),
75
            multi: true
76
        }
77
    ],
4✔
78
    standalone: true,
79
    imports: [
×
80
        CdkOverlayOrigin,
4✔
81
        ThySelectControl,
3,724✔
82
        NgIf,
111,720✔
83
        NgTemplateOutlet,
111,720✔
84
        CdkConnectedOverlay,
3,720✔
85
        forwardRef(() => ThyTreeSelectNodes),
86
        ThyStopPropagationDirective
87
    ],
3,724✔
88
    host: {
89
        '[attr.tabindex]': 'tabIndex',
3,720✔
90
        '(focus)': 'onFocus($event)',
91
        '(blur)': 'onBlur($event)'
92
    },
22✔
93
    animations: [scaleYMotion]
22✔
94
})
4✔
95
export class ThyTreeSelect extends TabIndexDisabledControlValueAccessorMixin implements OnInit, OnDestroy, ControlValueAccessor {
96
    @HostBinding('class.thy-select-custom') treeSelectClass = true;
22✔
97

98
    @HostBinding('class.thy-select') isTreeSelect = true;
99

39✔
100
    // 菜单是否展开
39✔
101
    @HostBinding('class.menu-is-opened') expandTreeSelectOptions = false;
39✔
102

39✔
103
    @HostBinding('class.thy-select-custom--multiple') isMulti = false;
39✔
104

39✔
105
    public treeNodes: ThyTreeSelectNode[];
39✔
106

39✔
107
    public selectedValue: any;
39✔
108

39✔
109
    public selectedNode: ThyTreeSelectNode;
39✔
110

39✔
111
    public selectedNodes: ThyTreeSelectNode[] = [];
39✔
112

39✔
113
    public flattenTreeNodes: ThyTreeSelectNode[] = [];
39✔
114

39✔
115
    virtualTreeNodes: ThyTreeSelectNode[] = [];
39✔
116

117
    public cdkConnectOverlayWidth = 0;
118

119
    public positions: ConnectionPositionPair[];
120

39✔
121
    public expandedDropdownPositions = EXPANDED_DROPDOWN_POSITIONS;
39✔
122

39✔
123
    public icons: { expand: string; collapse: string; gap?: number } = {
39✔
124
        expand: 'angle-down',
39✔
125
        collapse: 'angle-right',
39✔
126
        gap: 15
39✔
127
    };
39✔
128

39✔
129
    private initialled = false;
39✔
130

39✔
131
    private destroy$ = new Subject<void>();
39✔
132

39✔
133
    public valueIsObject = false;
39✔
134

39✔
135
    originTreeNodes: ThyTreeSelectNode[];
39✔
136

39✔
137
    @ContentChild('thyTreeSelectTriggerDisplay')
39✔
138
    thyTreeSelectTriggerDisplayRef: TemplateRef<any>;
39✔
139

39✔
140
    @ContentChild('treeNodeTemplate')
141
    treeNodeTemplateRef: TemplateRef<any>;
142

39✔
143
    @ViewChild(CdkOverlayOrigin, { static: true }) cdkOverlayOrigin: CdkOverlayOrigin;
39✔
144

39✔
145
    @ViewChild(CdkConnectedOverlay, { static: true }) cdkConnectedOverlay: CdkConnectedOverlay;
39✔
146

39✔
147
    @ViewChild('customDisplayTemplate', { static: true }) customDisplayTemplate: TemplateRef<any>;
39✔
148

4✔
149
    /**
150
     * treeNodes 数据
39!
151
     * @type ThyTreeSelectNode[]
39✔
152
     */
153
    @Input()
154
    set thyTreeNodes(value: ThyTreeSelectNode[]) {
155
        this.treeNodes = value;
27✔
156
        this.originTreeNodes = value;
27✔
157
        if (this.initialled) {
2✔
158
            this.flattenTreeNodes = this.flattenNodes(this.treeNodes, this.flattenTreeNodes, []);
2✔
159
            this.setSelectedNodes();
2✔
160

161
            if (this.thyVirtualScroll) {
162
                this.buildFlattenTreeNodes();
163
            }
164
        }
39✔
165
    }
166

167
    /**
168
     * 开启虚拟滚动
1✔
169
     */
170
    @Input({ transform: coerceBooleanProperty }) thyVirtualScroll: boolean = false;
171

172
    /**
1✔
173
     * 树节点的唯一标识
1✔
174
     * @type string
175
     */
176
    @Input() thyPrimaryKey = '_id';
177

178
    /**
2✔
179
     * 树节点的显示的字段 key
1✔
180
     * @type string
181
     */
1✔
182
    @Input() thyShowKey = 'name';
183

184
    @Input() thyChildCountKey = 'childCount';
39✔
185

186
    /**
187
     * 单选时,是否显示清除按钮,当为 true 时,显示清除按钮
196✔
188
     * @default false
189
     */
190
    @Input({ transform: coerceBooleanProperty }) thyAllowClear: boolean;
1✔
191

192
    /**
193
     * 是否多选
1✔
194
     * @type boolean
195
     */
196
    @Input({ transform: coerceBooleanProperty }) thyMultiple = false;
197

1✔
198
    /**
199
     * 是否禁用树选择器,当为 true 禁用树选择器
200
     * @type boolean
201
     */
1✔
202
    @Input({ transform: coerceBooleanProperty }) thyDisable = false;
203

×
204
    get thyDisabled(): boolean {
4,083✔
205
        return this.thyDisable;
4,083✔
206
    }
4,083!
207

112,044✔
208
    /**
112,044✔
209
     * 树选择框默认文字
112,044✔
210
     * @type string
4,042✔
211
     */
4,042✔
212
    @Input() thyPlaceholder = '请选择节点';
213

214
    get placeholder() {
4,083✔
215
        return this.thyPlaceholder;
216
    }
217

28!
218
    /**
219
     * 控制树选择的输入框大小
220
     * @type xs | sm | md | default | lg
62✔
221
     */
222
    @Input() thySize: InputSize;
4✔
223

2!
224
    /**
2✔
225
     * 改变空选项的情况下的提示文本
1✔
226
     * @type string
2✔
227
     */
228
    @Input() thyEmptyOptionsText = '暂时没有数据可选';
229

230
    /**
1✔
231
     * 设置是否隐藏节点(不可进行任何操作),优先级高于 thyHiddenNodeFn
2✔
232
     * @type string
233
     */
234
    @Input() thyHiddenNodeKey = 'hidden';
235

236
    /**
237
     * 设置是否禁用节点(不可进行任何操作),优先级高于 thyDisableNodeFn
238
     * @type string
2✔
239
     */
1!
240
    @Input() thyDisableNodeKey = 'disabled';
1✔
241

242
    /**
243
     * 是否异步加载节点的子节点(显示加载状态),当为 true 时,异步获取
244
     * @type boolean
1✔
245
     */
246
    @Input({ transform: coerceBooleanProperty }) thyAsyncNode = false;
247

248
    /**
249
     * 是否展示全名
58✔
250
     * @type boolean
58✔
251
     */
252
    @Input({ transform: coerceBooleanProperty }) thyShowWholeName = false;
253

254
    /**
14✔
255
     * 是否展示搜索
1✔
256
     * @type boolean
257
     */
13✔
258
    @Input({ transform: coerceBooleanProperty }) thyShowSearch = false;
13✔
259

13✔
260
    /**
261
     * 图标类型,支持 default | especial,已废弃
262
     * @deprecated
7✔
263
     */
2✔
264
    @Input()
2✔
265
    set thyIconType(type: ThyTreeSelectType) {
2✔
266
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
267
            warnDeprecation('This parameter has been deprecation');
268
        }
269
        // if (type === 'especial') {
2✔
270
        //     this.icons = { expand: 'minus-square', collapse: 'plus-square', gap: 20 };
2✔
271
        // } else {
2✔
272
        //     this.icons = { expand: 'caret-right-down', collapse: 'caret-right', gap: 15 };
2✔
273
        // }
2✔
274
    }
275

276
    /**
13!
UNCOV
277
     * 设置是否隐藏节点(不可进行任何操作),优先级低于 thyHiddenNodeKey。
×
278
     * @default (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.hidden
279
     */
280
    @Input() thyHiddenNodeFn: (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.hidden;
13✔
281

7✔
282
    /**
283
     * 设置是否禁用节点(不可进行任何操作),优先级低于 thyDisableNodeKey。
284
     * @default (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.disabled
13✔
285
     */
13✔
286
    @Input() thyDisableNodeFn: (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.disabled;
3✔
287

288
    /**
289
     * 获取节点的子节点,返回 Observable<ThyTreeSelectNode>。
290
     * @default (node: ThyTreeSelectNode) => Observable<ThyTreeSelectNode> = (node: ThyTreeSelectNode) => of([])
1✔
291
     */
292
    @Input() thyGetNodeChildren: (node: ThyTreeSelectNode) => Observable<ThyTreeSelectNode> = (node: ThyTreeSelectNode) => of([]);
293

294
    /**
3✔
295
     * 树选择组件展开和折叠状态事件
1✔
296
     */
297
    @Output() thyExpandStatusChange: EventEmitter<boolean> = new EventEmitter<boolean>();
3!
UNCOV
298

×
299
    private _getNgModelType() {
300
        if (this.thyMultiple) {
3!
301
            this.valueIsObject = !this.selectedValue[0] || isObject(this.selectedValue[0]);
3✔
302
        } else {
3✔
303
            this.valueIsObject = isObject(this.selectedValue);
304
        }
3✔
305
    }
306

307
    public buildFlattenTreeNodes() {
308
        this.virtualTreeNodes = this.getFlattenTreeNodes(this.treeNodes);
12✔
309
    }
3✔
310

3✔
311
    private getFlattenTreeNodes(rootTrees: ThyTreeSelectNode[] = this.treeNodes) {
3✔
312
        const forEachTree = (tree: ThyTreeSelectNode[], fn: any, result: ThyTreeSelectNode[] = []) => {
3✔
313
            tree.forEach(item => {
314
                result.push(item);
315
                if (item.children && fn(item)) {
9✔
316
                    forEachTree(item.children, fn, result);
2✔
317
                }
318
            });
2✔
319
            return result;
320
        };
321
        return forEachTree(rootTrees, (node: ThyTreeSelectNode) => !!node.expand);
7✔
322
    }
7✔
323

324
    writeValue(value: any): void {
325
        this.selectedValue = value;
326

327
        if (value) {
1✔
328
            this._getNgModelType();
1!
329
        }
1✔
330
        this.setSelectedNodes();
1✔
331
    }
1✔
332

2✔
333
    constructor(
18✔
334
        public elementRef: ElementRef,
335
        private ngZone: NgZone,
336
        private ref: ChangeDetectorRef,
1✔
337
        @Inject(PLATFORM_ID) private platformId: string,
1✔
338
        private thyClickDispatcher: ThyClickDispatcher,
339
        private viewportRuler: ViewportRuler
1✔
340
    ) {
341
        super();
342
    }
1✔
343

344
    ngOnInit() {
345
        this.positions = getFlexiblePositions('bottom', 4);
346
        this.isMulti = this.thyMultiple;
347
        this.flattenTreeNodes = this.flattenNodes(this.treeNodes, this.flattenTreeNodes, []);
348
        this.setSelectedNodes();
349
        this.initialled = true;
350

1✔
351
        if (this.thyVirtualScroll) {
352
            this.buildFlattenTreeNodes();
353
        }
354

355
        if (isPlatformBrowser(this.platformId)) {
356
            this.thyClickDispatcher
357
                .clicked(0)
358
                .pipe(takeUntil(this.destroy$))
359
                .subscribe(event => {
360
                    event.stopPropagation();
361
                    if (!this.elementRef.nativeElement.contains(event.target) && this.expandTreeSelectOptions) {
362
                        this.ngZone.run(() => {
363
                            this.close();
364
                            this.ref.markForCheck();
365
                        });
366
                    }
367
                });
368
        }
369
        this.viewportRuler
370
            .change()
371
            .pipe(takeUntil(this.destroy$))
372
            .subscribe(() => {
373
                this.init();
374
            });
375
    }
376

377
    onFocus($event: FocusEvent) {
378
        const inputElement: HTMLInputElement = this.elementRef.nativeElement.querySelector('input');
379
        inputElement?.focus();
380
    }
381

382
    onBlur($event: FocusEvent) {
383
        // 1. Tab 聚焦后自动聚焦到 input 输入框,此分支下直接返回,无需触发 onTouchedFn
1✔
384
        // 2. 打开选择框后如果点击弹框内导致 input 失焦,无需触发 onTouchedFn
385
        if (elementMatchClosest($event?.relatedTarget as HTMLElement, ['thy-tree-select', 'thy-tree-select-nodes'])) {
386
            return;
387
        }
388
        this.onTouchedFn();
389
    }
390

9✔
391
    ngOnDestroy(): void {
392
        this.destroy$.next();
393
    }
394

395
    get selectedValueObject() {
396
        return this.thyMultiple ? this.selectedNodes : this.selectedNode;
397
    }
398

399
    searchValue(searchText: string) {
400
        this.treeNodes = filterTreeData(this.originTreeNodes, searchText.trim(), this.thyShowKey);
401
    }
113✔
402

403
    public setPosition() {
404
        this.ngZone.onStable
405
            .asObservable()
406
            .pipe(take(1))
407
            .subscribe(() => {
408
                this.cdkConnectedOverlay.overlayRef.updatePosition();
409
            });
410
    }
411

412
    private init() {
413
        this.cdkConnectOverlayWidth = this.cdkOverlayOrigin.elementRef.nativeElement.getBoundingClientRect().width;
414
    }
415

416
    private flattenNodes(
417
        nodes: ThyTreeSelectNode[] = [],
1✔
418
        resultNodes: ThyTreeSelectNode[] = [],
419
        parentPrimaryValue: string[] = []
420
    ): ThyTreeSelectNode[] {
421
        resultNodes = resultNodes.concat(nodes);
1✔
422
        let nodesLeafs: ThyTreeSelectNode[] = [];
423
        (nodes || []).forEach(item => {
13✔
424
            item.parentValues = parentPrimaryValue;
425
            item.level = item.parentValues.length;
13✔
426
            if (item.children && isArray(item.children)) {
13✔
427
                const nodeLeafs = this.flattenNodes(item.children, resultNodes, [...parentPrimaryValue, item[this.thyPrimaryKey]]);
428
                nodesLeafs = [...nodesLeafs, ...nodeLeafs];
429
            }
13✔
430
        });
13✔
431
        return [...nodes, ...nodesLeafs];
13✔
432
    }
13✔
433

13✔
434
    private _findTreeNode(value: string): ThyTreeSelectNode {
13✔
435
        return (this.flattenTreeNodes || []).find(item => item[this.thyPrimaryKey] === value);
13✔
436
    }
13✔
437

13✔
438
    private setSelectedNodes() {
13✔
439
        if (this.selectedValue) {
13✔
440
            // 多选数据初始化
13✔
441
            if (this.thyMultiple) {
442
                if (this.selectedValue.length > 0) {
443
                    if (this.valueIsObject && Object.keys(this.selectedValue[0]).indexOf(this.thyPrimaryKey) >= 0) {
13✔
444
                        this.selectedNodes = this.selectedValue.map((item: any) => {
445
                            return this._findTreeNode(item[this.thyPrimaryKey]);
446
                        });
361✔
447
                    } else {
244!
448
                        this.selectedNodes = this.selectedValue.map((item: any) => {
50✔
449
                            return this._findTreeNode(item);
450
                        });
451
                    }
452
                }
117!
453
            } else {
454
                // 单选数据初始化
455
                if (this.valueIsObject) {
456
                    if (Object.keys(this.selectedValue).indexOf(this.thyPrimaryKey) >= 0) {
418✔
457
                        this.selectedNode = this._findTreeNode(this.selectedValue[this.thyPrimaryKey]);
394✔
458
                    }
459
                } else {
24!
460
                    this.selectedNode = this._findTreeNode(this.selectedValue);
24✔
461
                }
UNCOV
462
            }
×
463
        } else {
464
            this.selectedNodes = [];
465
            this.selectedNode = null;
373✔
466
        }
363✔
467
    }
468

10!
469
    openSelectPop() {
10✔
470
        if (this.thyDisable) {
UNCOV
471
            return;
×
472
        }
473
        this.cdkConnectOverlayWidth = this.cdkOverlayOrigin.elementRef.nativeElement.getBoundingClientRect().width;
474
        this.expandTreeSelectOptions = !this.expandTreeSelectOptions;
707✔
475
        this.thyExpandStatusChange.emit(this.expandTreeSelectOptions);
707✔
476
    }
536!
477

110✔
478
    close() {
479
        if (this.expandTreeSelectOptions) {
480
            this.expandTreeSelectOptions = false;
481
            this.thyExpandStatusChange.emit(this.expandTreeSelectOptions);
171!
482
            this.onTouchedFn();
483
        }
484
    }
485

707✔
486
    clearSelectedValue(event: Event) {
707✔
487
        event.stopPropagation();
707✔
488
        this.selectedValue = null;
489
        this.selectedNode = null;
490
        this.selectedNodes = [];
1✔
491
        this.onChangeFn(this.selectedValue);
492
    }
493

12!
494
    private _changeSelectValue() {
12✔
495
        if (this.valueIsObject) {
496
            this.selectedValue = this.thyMultiple ? this.selectedNodes : this.selectedNode;
497
        } else {
498
            this.selectedValue = this.thyMultiple
1✔
499
                ? this.selectedNodes.map(item => item[this.thyPrimaryKey])
1!
500
                : this.selectedNode[this.thyPrimaryKey];
1✔
501
        }
502
        this.onChangeFn(this.selectedValue);
UNCOV
503
        if (!this.thyMultiple) {
×
UNCOV
504
            this.onTouchedFn();
×
505
        }
506
    }
UNCOV
507

×
508
    removeMultipleSelectedNode(event: { item: ThyTreeSelectNode; $eventOrigin: Event }) {
509
        this.removeSelectedNode(event.item, event.$eventOrigin);
510
    }
1!
511

1✔
512
    // thyMultiple = true 时,移除数据时调用
1✔
513
    removeSelectedNode(node: ThyTreeSelectNode, event?: Event) {
514
        if (event) {
515
            event.stopPropagation();
516
        }
1!
UNCOV
517
        if (this.thyDisable) {
×
518
            return;
519
        }
520
        if (this.thyMultiple) {
521
            this.selectedNodes = produce(this.selectedNodes).remove((item: ThyTreeSelectNode) => {
24✔
522
                return item[this.thyPrimaryKey] === node[this.thyPrimaryKey];
523
            });
1✔
524
            this._changeSelectValue();
525
        }
526
    }
1✔
527

528
    selectNode(node: ThyTreeSelectNode) {
529
        if (!this.thyMultiple) {
530
            this.selectedNode = node;
531
            this.expandTreeSelectOptions = false;
532
            this.thyExpandStatusChange.emit(this.expandTreeSelectOptions);
1✔
533
            this._changeSelectValue();
534
        } else {
535
            if (
536
                this.selectedNodes.find(item => {
537
                    return item[this.thyPrimaryKey] === node[this.thyPrimaryKey];
538
                })
539
            ) {
540
                this.removeSelectedNode(node);
541
            } else {
542
                this.selectedNodes = produce(this.selectedNodes).add(node);
543
                this._changeSelectValue();
544
            }
545
        }
546
    }
547

548
    getNodeChildren(node: ThyTreeSelectNode) {
549
        const result = this.thyGetNodeChildren(node);
550
        if (result && result.subscribe) {
551
            result.pipe().subscribe((data: ThyTreeSelectNode[]) => {
552
                const nodes = this.flattenNodes(data, this.flattenTreeNodes, [...node.parentValues, node[this.thyPrimaryKey]]);
553
                const otherNodes = nodes.filter((item: ThyTreeNode) => {
554
                    return !this.flattenTreeNodes.find(hasItem => {
555
                        return hasItem[this.thyPrimaryKey] === item[this.thyPrimaryKey];
556
                    });
557
                });
558
                this.flattenTreeNodes = [...this.flattenTreeNodes, ...otherNodes];
559
                node.children = data;
560
            });
561
            return result;
562
        }
563
    }
564
}
565

566
const DEFAULT_ITEM_SIZE = 40;
567

568
/**
569
 * @private
570
 */
571
@Component({
572
    selector: 'thy-tree-select-nodes',
573
    templateUrl: './tree-select-nodes.component.html',
574
    standalone: true,
575
    imports: [
576
        NgIf,
577
        NgFor,
578
        NgTemplateOutlet,
579
        CdkVirtualScrollViewport,
580
        CdkFixedSizeVirtualScroll,
581
        CdkVirtualForOf,
582
        ThyEmpty,
583
        NgClass,
584
        NgStyle,
585
        ThyIcon,
586
        ThyFlexibleText
587
    ],
588
    host: {
589
        '[attr.tabindex]': '-1'
590
    }
591
})
592
export class ThyTreeSelectNodes implements OnInit {
593
    @HostBinding('class') class: string;
594

595
    nodeList: ThyTreeSelectNode[] = [];
596

597
    @Input() set treeNodes(value: ThyTreeSelectNode[]) {
598
        const treeSelectHeight = this.defaultItemSize * value.length;
599
        // 父级设置了max-height:300 & padding:10 0; 故此处最多设置280,否则将出现滚动条
600
        this.thyVirtualHeight = treeSelectHeight > 300 ? '280px' : `${treeSelectHeight}px`;
601
        this.nodeList = value;
602
    }
603

604
    @Input() thyVirtualScroll: boolean = false;
605

606
    public primaryKey = this.parent.thyPrimaryKey;
607

608
    public showKey = this.parent.thyShowKey;
609

610
    public isMultiple = this.parent.thyMultiple;
611

612
    public valueIsObject = this.parent.valueIsObject;
613

614
    public selectedValue = this.parent.selectedValue;
615

616
    public childCountKey = this.parent.thyChildCountKey;
617

618
    public treeNodeTemplateRef = this.parent.treeNodeTemplateRef;
619

620
    public defaultItemSize = DEFAULT_ITEM_SIZE;
621

622
    public thyVirtualHeight: string = null;
623

624
    constructor(public parent: ThyTreeSelect) {}
625

626
    ngOnInit() {
627
        this.class = this.isMultiple ? 'thy-tree-select-dropdown thy-tree-select-dropdown-multiple' : 'thy-tree-select-dropdown';
628
    }
629

630
    treeNodeIsSelected(node: ThyTreeSelectNode) {
631
        if (this.parent.thyMultiple) {
632
            return (this.parent.selectedNodes || []).find(item => {
633
                return item[this.primaryKey] === node[this.primaryKey];
634
            });
635
        } else {
636
            return this.parent.selectedNode && this.parent.selectedNode[this.primaryKey] === node[this.primaryKey];
637
        }
638
    }
639

640
    treeNodeIsHidden(node: ThyTreeSelectNode) {
641
        if (this.parent.thyHiddenNodeKey) {
642
            return node[this.parent.thyHiddenNodeKey];
643
        }
644
        if (this.parent.thyHiddenNodeFn) {
645
            return this.parent.thyHiddenNodeFn(node);
646
        }
647
        return false;
648
    }
649

650
    treeNodeIsDisable(node: ThyTreeSelectNode) {
651
        if (this.parent.thyDisableNodeKey) {
652
            return node[this.parent.thyDisableNodeKey];
653
        }
654
        if (this.parent.thyDisableNodeFn) {
655
            return this.parent.thyDisableNodeFn(node);
656
        }
657
        return false;
658
    }
659

660
    treeNodeIsExpand(node: ThyTreeSelectNode) {
661
        let isSelectedNodeParent = false;
662
        if (this.parent.thyMultiple) {
663
            isSelectedNodeParent = !!(this.parent.selectedNodes || []).find(item => {
664
                return item.parentValues.indexOf(node[this.primaryKey]) > -1;
665
            });
666
        } else {
667
            isSelectedNodeParent = this.parent.selectedNode
668
                ? this.parent.selectedNode.parentValues.indexOf(node[this.primaryKey]) > -1
669
                : false;
670
        }
671
        const isExpand = node.expand || (Object.keys(node).indexOf('expand') < 0 && isSelectedNodeParent);
672
        node.expand = isExpand;
673
        return isExpand;
674
    }
675

676
    getNodeChildren(node: ThyTreeSelectNode) {
677
        return this.parent.getNodeChildren(node);
678
    }
679

680
    selectTreeNode(event: Event, node: ThyTreeSelectNode) {
681
        if (!this.treeNodeIsDisable(node)) {
682
            this.parent.selectNode(node);
683
        }
684
    }
685

686
    nodeExpandToggle(event: Event, node: ThyTreeSelectNode) {
687
        event.stopPropagation();
688
        if (Object.keys(node).indexOf('expand') > -1) {
689
            node.expand = !node.expand;
690
        } else {
691
            if (this.treeNodeIsExpand(node)) {
692
                node.expand = false;
693
            } else {
694
                node.expand = true;
695
            }
696
        }
697

698
        if (node.expand && this.parent.thyAsyncNode) {
699
            this.getNodeChildren(node).subscribe(() => {
700
                this.parent.setPosition();
701
            });
702
        }
703
        // this.parent.setPosition();
704
        if (this.thyVirtualScroll) {
705
            this.parent.buildFlattenTreeNodes();
706
        }
707
    }
708

709
    tabTrackBy(index: number, item: ThyTreeSelectNode) {
710
        return index;
711
    }
712
}
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