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

atinc / ngx-tethys / edbc1d43-1648-411a-a6bc-f24c9aa3f654

27 Mar 2025 06:13AM UTC coverage: 90.236% (+0.06%) from 90.179%
edbc1d43-1648-411a-a6bc-f24c9aa3f654

push

circleci

web-flow
Merge pull request #3282 from atinc/v19.0.0-next

5598 of 6865 branches covered (81.54%)

Branch coverage included in aggregate %.

8 of 8 new or added lines in 7 files covered. (100.0%)

157 existing lines in 46 files now uncovered.

13357 of 14141 relevant lines covered (94.46%)

992.51 hits per line

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

88.03
/src/tree-select/tree-select.component.ts
1
import {
2
    EXPANDED_DROPDOWN_POSITIONS,
3
    injectPanelEmptyIcon,
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, ViewportRuler } from '@angular/cdk/overlay';
18
import { CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
×
19
import { isPlatformBrowser, NgClass, NgStyle, NgTemplateOutlet } from '@angular/common';
2✔
20
import {
17✔
21
    ChangeDetectorRef,
2✔
22
    Component,
2✔
23
    ContentChild,
24
    ElementRef,
15!
25
    EventEmitter,
15✔
26
    forwardRef,
15✔
27
    HostBinding,
2✔
28
    Input,
2✔
29
    NgZone,
30
    OnDestroy,
31
    OnInit,
15✔
32
    Output,
33
    PLATFORM_ID,
4✔
34
    TemplateRef,
2✔
35
    ViewChild,
36
    inject,
37
    Signal
38
} from '@angular/core';
39
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
40

41
import { ThyTreeSelectNode, ThyTreeSelectType } from './tree-select.class';
1✔
42
import { injectLocale, ThyTreeSelectLocale } from 'ngx-tethys/i18n';
43

40✔
44
type InputSize = 'xs' | 'sm' | 'md' | 'lg' | '';
40✔
45

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

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

39✔
103
    @HostBinding('class.thy-select-custom') treeSelectClass = true;
39✔
104

39✔
105
    @HostBinding('class.thy-select') isTreeSelect = true;
39✔
106

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

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

39✔
112
    public treeNodes: ThyTreeSelectNode[];
39✔
113

39✔
114
    public selectedValue: any;
39✔
115

39✔
116
    public selectedNode: ThyTreeSelectNode;
39✔
117

118
    public selectedNodes: ThyTreeSelectNode[] = [];
119

120
    public flattenTreeNodes: ThyTreeSelectNode[] = [];
121

39✔
122
    virtualTreeNodes: ThyTreeSelectNode[] = [];
39✔
123

39✔
124
    public cdkConnectOverlayWidth = 0;
39✔
125

39✔
126
    public expandedDropdownPositions = EXPANDED_DROPDOWN_POSITIONS;
39✔
127

39✔
128
    public icons: { expand: string; collapse: string; gap?: number } = {
39✔
129
        expand: 'angle-down',
39✔
130
        collapse: 'angle-right',
39✔
131
        gap: 15
39✔
132
    };
39✔
133

39✔
134
    private initialled = false;
39✔
135

39✔
136
    private destroy$ = new Subject<void>();
39✔
137

39✔
138
    private locale: Signal<ThyTreeSelectLocale> = injectLocale('treeSelect');
39✔
139

39✔
140
    public valueIsObject = false;
39✔
141

39✔
142
    originTreeNodes: ThyTreeSelectNode[];
143

144
    @ContentChild('thyTreeSelectTriggerDisplay')
39✔
145
    thyTreeSelectTriggerDisplayRef: TemplateRef<any>;
39✔
146

39✔
147
    @ContentChild('treeNodeTemplate')
39✔
148
    treeNodeTemplateRef: TemplateRef<any>;
39✔
149

4✔
150
    @ViewChild(CdkOverlayOrigin, { static: true }) cdkOverlayOrigin: CdkOverlayOrigin;
151

39!
152
    @ViewChild(CdkConnectedOverlay, { static: true }) cdkConnectedOverlay: CdkConnectedOverlay;
39✔
153

154
    @ViewChild('customDisplayTemplate', { static: true }) customDisplayTemplate: TemplateRef<any>;
155

156
    /**
27✔
157
     * treeNodes 数据
27✔
158
     * @type ThyTreeSelectNode[]
2✔
159
     */
2✔
160
    @Input()
2✔
161
    set thyTreeNodes(value: ThyTreeSelectNode[]) {
162
        this.treeNodes = value;
163
        this.originTreeNodes = value;
164
        if (this.initialled) {
165
            this.flattenTreeNodes = this.flattenNodes(this.treeNodes, this.flattenTreeNodes, []);
39✔
166
            this.setSelectedNodes();
167

168
            if (this.thyVirtualScroll) {
169
                this.buildFlattenTreeNodes();
1✔
170
            }
171
        }
172
    }
173

1✔
174
    /**
1✔
175
     * 开启虚拟滚动
176
     */
177
    @Input({ transform: coerceBooleanProperty }) thyVirtualScroll: boolean = false;
178

179
    /**
2✔
180
     * 树节点的唯一标识
1✔
181
     * @type string
182
     */
1✔
183
    @Input() thyPrimaryKey = '_id';
184

185
    /**
39✔
186
     * 树节点的显示的字段 key
187
     * @type string
188
     */
196✔
189
    @Input() thyShowKey = 'name';
190

191
    @Input() thyChildCountKey = 'childCount';
1✔
192

193
    /**
194
     * 单选时,是否显示清除按钮,当为 true 时,显示清除按钮
1✔
195
     * @default false
196
     */
197
    @Input({ transform: coerceBooleanProperty }) thyAllowClear: boolean;
198

1✔
199
    /**
200
     * 是否多选
201
     * @type boolean
202
     */
1✔
203
    @Input({ transform: coerceBooleanProperty }) thyMultiple = false;
204

×
205
    /**
4,083✔
206
     * 是否禁用树选择器,当为 true 禁用树选择器
4,083✔
207
     * @type boolean
4,083!
208
     */
112,044✔
209
    @Input({ transform: coerceBooleanProperty }) thyDisable = false;
112,044✔
210

112,044✔
211
    get thyDisabled(): boolean {
4,042✔
212
        return this.thyDisable;
4,042✔
213
    }
214

215
    /**
4,083✔
216
     * 树选择框默认文字
217
     * @type string
218
     */
28!
219
    @Input() thyPlaceholder = this.locale().placeholder;
220

221
    get placeholder() {
62✔
222
        return this.thyPlaceholder;
223
    }
4✔
224

2!
225
    /**
2✔
226
     * 控制树选择的输入框大小
1✔
227
     * @type xs | sm | md | default | lg
2✔
228
     */
229
    @Input() thySize: InputSize;
230

231
    /**
1✔
232
     * 改变空选项的情况下的提示文本
2✔
233
     * @type string
234
     */
235
    @Input() thyEmptyOptionsText = this.locale().empty;
236

237
    /**
238
     * 设置是否隐藏节点(不可进行任何操作),优先级高于 thyHiddenNodeFn
239
     * @type string
2✔
240
     */
1!
241
    @Input() thyHiddenNodeKey = 'hidden';
1✔
242

243
    /**
244
     * 设置是否禁用节点(不可进行任何操作),优先级高于 thyDisableNodeFn
245
     * @type string
1✔
246
     */
247
    @Input() thyDisableNodeKey = 'disabled';
248

249
    /**
250
     * 是否异步加载节点的子节点(显示加载状态),当为 true 时,异步获取
58✔
251
     * @type boolean
58✔
252
     */
253
    @Input({ transform: coerceBooleanProperty }) thyAsyncNode = false;
254

255
    /**
14✔
256
     * 是否展示全名
1✔
257
     * @type boolean
258
     */
13✔
259
    @Input({ transform: coerceBooleanProperty }) thyShowWholeName = false;
13✔
260

13✔
261
    /**
262
     * 是否展示搜索
263
     * @type boolean
7✔
264
     */
2✔
265
    @Input({ transform: coerceBooleanProperty }) thyShowSearch = false;
2✔
266

2✔
267
    /**
268
     * 图标类型,支持 default | especial,已废弃
269
     * @deprecated
270
     */
2✔
271
    @Input()
2✔
272
    set thyIconType(type: ThyTreeSelectType) {
2✔
273
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
2✔
274
            warnDeprecation('This parameter has been deprecation');
2✔
275
        }
276
        // if (type === 'especial') {
277
        //     this.icons = { expand: 'minus-square', collapse: 'plus-square', gap: 20 };
13!
UNCOV
278
        // } else {
×
279
        //     this.icons = { expand: 'caret-right-down', collapse: 'caret-right', gap: 15 };
280
        // }
281
    }
13✔
282

7✔
283
    /**
284
     * 设置是否隐藏节点(不可进行任何操作),优先级低于 thyHiddenNodeKey。
285
     * @default (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.hidden
13✔
286
     */
13✔
287
    @Input() thyHiddenNodeFn: (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.hidden;
3✔
288

289
    /**
290
     * 设置是否禁用节点(不可进行任何操作),优先级低于 thyDisableNodeKey。
291
     * @default (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.disabled
1✔
292
     */
293
    @Input() thyDisableNodeFn: (node: ThyTreeSelectNode) => boolean = (node: ThyTreeSelectNode) => node.disabled;
294

295
    /**
3✔
296
     * 获取节点的子节点,返回 Observable<ThyTreeSelectNode>。
1✔
297
     * @default (node: ThyTreeSelectNode) => Observable<ThyTreeSelectNode> = (node: ThyTreeSelectNode) => of([])
298
     */
3!
UNCOV
299
    @Input() thyGetNodeChildren: (node: ThyTreeSelectNode) => Observable<ThyTreeSelectNode> = (node: ThyTreeSelectNode) => of([]);
×
300

301
    /**
3!
302
     * 树选择组件展开和折叠状态事件
3✔
303
     */
3✔
304
    @Output() thyExpandStatusChange: EventEmitter<boolean> = new EventEmitter<boolean>();
305

3✔
306
    private _getNgModelType() {
307
        if (this.thyMultiple) {
308
            this.valueIsObject = !this.selectedValue[0] || isObject(this.selectedValue[0]);
309
        } else {
12✔
310
            this.valueIsObject = isObject(this.selectedValue);
3✔
311
        }
3✔
312
    }
3✔
313

3✔
314
    public buildFlattenTreeNodes() {
315
        this.virtualTreeNodes = this.getFlattenTreeNodes(this.treeNodes);
316
    }
9✔
317

2✔
318
    private getFlattenTreeNodes(rootTrees: ThyTreeSelectNode[] = this.treeNodes) {
319
        const forEachTree = (tree: ThyTreeSelectNode[], fn: any, result: ThyTreeSelectNode[] = []) => {
2✔
320
            tree.forEach(item => {
321
                result.push(item);
322
                if (item.children && fn(item)) {
7✔
323
                    forEachTree(item.children, fn, result);
7✔
324
                }
325
            });
326
            return result;
327
        };
328
        return forEachTree(rootTrees, (node: ThyTreeSelectNode) => !!node.expand);
1✔
329
    }
1!
330

1✔
331
    writeValue(value: any): void {
1✔
332
        this.selectedValue = value;
1✔
333

2✔
334
        if (value) {
18✔
335
            this._getNgModelType();
336
        }
337
        this.setSelectedNodes();
1✔
338
    }
1✔
339

340
    constructor() {
1✔
341
        super();
342
    }
343

1✔
344
    ngOnInit() {
1✔
345
        this.isMulti = this.thyMultiple;
346
        this.flattenTreeNodes = this.flattenNodes(this.treeNodes, this.flattenTreeNodes, []);
347
        this.setSelectedNodes();
348
        this.initialled = true;
349

350
        if (this.thyVirtualScroll) {
351
            this.buildFlattenTreeNodes();
352
        }
353

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

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

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

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

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

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

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

1✔
411
    private init() {
412
        this.cdkConnectOverlayWidth = this.cdkOverlayOrigin.elementRef.nativeElement.getBoundingClientRect().width;
13✔
413
    }
13✔
414

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

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

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

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

477
    close() {
707✔
478
        if (this.expandTreeSelectOptions) {
707✔
479
            this.expandTreeSelectOptions = false;
707✔
480
            this.thyExpandStatusChange.emit(this.expandTreeSelectOptions);
481
            this.onTouchedFn();
482
        }
1✔
483
    }
484

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

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

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

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

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

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

565
const DEFAULT_ITEM_SIZE = 40;
566

567
/**
568
 * @private
569
 */
570
@Component({
571
    selector: 'thy-tree-select-nodes',
572
    templateUrl: './tree-select-nodes.component.html',
573
    imports: [
574
        NgTemplateOutlet,
575
        CdkVirtualScrollViewport,
576
        CdkFixedSizeVirtualScroll,
577
        CdkVirtualForOf,
578
        ThyEmpty,
579
        NgClass,
580
        NgStyle,
581
        ThyIcon,
582
        ThyFlexibleText
583
    ],
584
    host: {
585
        '[attr.tabindex]': '-1'
586
    }
587
})
588
export class ThyTreeSelectNodes implements OnInit {
589
    parent = inject(ThyTreeSelect);
590
    emptyIcon: Signal<string> = injectPanelEmptyIcon();
591

592
    @HostBinding('class') class: string;
593

594
    nodeList: ThyTreeSelectNode[] = [];
595

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

606
    @Input() thyVirtualScroll: boolean = false;
607

608
    public primaryKey = this.parent.thyPrimaryKey;
609

610
    public showKey = this.parent.thyShowKey;
611

612
    public isMultiple = this.parent.thyMultiple;
613

614
    public valueIsObject = this.parent.valueIsObject;
615

616
    public selectedValue = this.parent.selectedValue;
617

618
    public childCountKey = this.parent.thyChildCountKey;
619

620
    public treeNodeTemplateRef = this.parent.treeNodeTemplateRef;
621

622
    public defaultItemSize = DEFAULT_ITEM_SIZE;
623

624
    public thyVirtualHeight: string = null;
625

626
    public hasNodeChildren: boolean = false;
627

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

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

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

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

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

678
    getNodeChildren(node: ThyTreeSelectNode) {
679
        return this.parent.getNodeChildren(node);
680
    }
681

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

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

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

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