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

atinc / ngx-tethys / c0ef8457-a839-451f-8b72-80fd73106231

02 Apr 2024 02:27PM UTC coverage: 90.524% (-0.06%) from 90.585%
c0ef8457-a839-451f-8b72-80fd73106231

Pull #3062

circleci

minlovehua
refactor(all): use the transform attribute of @Input() instead of @InputBoolean() and @InputNumber()
Pull Request #3062: refactor(all): use the transform attribute of @input() instead of @InputBoolean() and @InputNumber()

4987 of 6108 branches covered (81.65%)

Branch coverage included in aggregate %.

217 of 223 new or added lines in 82 files covered. (97.31%)

202 existing lines in 53 files now uncovered.

12246 of 12929 relevant lines covered (94.72%)

1055.59 hits per line

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

87.4
/src/cascader/cascader.component.ts
1
import {
2
    EXPANDED_DROPDOWN_POSITIONS,
3
    ScrollToService,
4
    TabIndexDisabledControlValueAccessorMixin,
5
    ThyClickDispatcher
6
} from 'ngx-tethys/core';
7
import { ThyEmpty } from 'ngx-tethys/empty';
8
import { ThyIcon } from 'ngx-tethys/icon';
9
import { SelectControlSize, SelectOptionBase, ThySelectControl } from 'ngx-tethys/shared';
10
import { elementMatchClosest, isEmpty } from 'ngx-tethys/util';
11
import { BehaviorSubject, Observable, Subject, Subscription, timer } from 'rxjs';
12
import { debounceTime, distinctUntilChanged, filter, take, takeUntil } from 'rxjs/operators';
13
import { CdkConnectedOverlay, CdkOverlayOrigin, ConnectedOverlayPositionChange, ConnectionPositionPair } from '@angular/cdk/overlay';
14
import { NgClass, NgFor, NgIf, NgStyle, NgTemplateOutlet, isPlatformBrowser } from '@angular/common';
15
import {
16
    AfterContentInit,
17
    booleanAttribute,
18
    ChangeDetectorRef,
19
    Component,
20
    ElementRef,
21
    EventEmitter,
22
    forwardRef,
23
    HostListener,
1✔
24
    Inject,
25
    Input,
59✔
26
    NgZone,
59✔
27
    numberAttribute,
59✔
28
    OnChanges,
5✔
29
    OnDestroy,
30
    OnInit,
31
    Output,
32
    PLATFORM_ID,
3✔
33
    QueryList,
3✔
34
    SimpleChanges,
3✔
35
    TemplateRef,
36
    ViewChild,
37
    ViewChildren
4✔
38
} from '@angular/core';
39
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
40
import { useHostRenderer } from '@tethys/cdk/dom';
37✔
41

42
import { ThyCascaderOptionComponent } from './cascader-li.component';
43
import { ThyCascaderSearchOptionComponent } from './cascader-search-option.component';
51✔
44
import { ThyCascaderExpandTrigger, ThyCascaderOption, ThyCascaderSearchOption, ThyCascaderTriggerType } from './types';
45
import { ThyCascaderService } from './cascader.service';
46
import { scaleYMotion } from 'ngx-tethys/core';
34✔
47

34✔
48
/**
49
 * 级联选择菜单
50
 * @name thy-cascader
344✔
51
 */
52
@Component({
53
    selector: 'thy-cascader,[thy-cascader]',
34✔
54
    templateUrl: './cascader.component.html',
34✔
55
    providers: [
56
        {
57
            provide: NG_VALUE_ACCESSOR,
102✔
58
            useExisting: forwardRef(() => ThyCascader),
59
            multi: true
60
        },
48✔
61
        ThyCascaderService
62
    ],
63
    host: {
490✔
64
        '[attr.tabindex]': `tabIndex`,
65
        '(focus)': 'onFocus($event)',
66
        '(blur)': 'onBlur($event)'
35✔
67
    },
68
    standalone: true,
69
    imports: [
48✔
70
        CdkOverlayOrigin,
48✔
71
        NgIf,
72
        ThySelectControl,
73
        NgClass,
2,913✔
74
        NgTemplateOutlet,
75
        CdkConnectedOverlay,
76
        NgStyle,
570✔
77
        NgFor,
78
        ThyCascaderOptionComponent,
79
        ThyCascaderSearchOptionComponent,
28✔
80
        ThyEmpty,
81
        ThyIcon
82
    ],
×
83
    animations: [scaleYMotion]
84
})
85
export class ThyCascader
833✔
86
    extends TabIndexDisabledControlValueAccessorMixin
87
    implements ControlValueAccessor, OnInit, OnChanges, OnDestroy, AfterContentInit
88
{
51✔
89
    /**
51✔
90
     * 选项的实际值的属性名
51✔
91
     */
51✔
92
    @Input() thyValueProperty = 'value';
51✔
93

51✔
94
    /**
51✔
95
     * 选项的显示值的属性名
96
     */
97
    @Input() thyLabelProperty = 'label';
98

99
    /**
100
     * 描述输入字段预期值的简短的提示信息
101
     */
102
    @Input() thyPlaceholder = '请选择';
51✔
103

51✔
104
    /**
9!
105
     * 控制大小(4种)
9✔
106
     * @type 'sm' | 'md' | 'lg' | ''
9✔
107
     */
1✔
108
    @Input() thySize: SelectControlSize = '';
109

9✔
110
    /**
9✔
111
     * 数据项
9✔
112
     * @type ThyCascaderOption[]
5✔
113
     * @default []
5✔
114
     */
115
    @Input()
116
    set thyOptions(options: ThyCascaderOption[] | null) {
117
        const columns = options && options.length ? [options] : [];
51!
118
        this.thyCascaderService.initColumns(columns);
51✔
119
        if (this.thyCascaderService.defaultValue && columns.length) {
120
            this.thyCascaderService.initOptions(0);
121
        }
122
    }
44✔
123

124
    /**
125
     * 点击父级菜单选项时,可通过该函数判断是否允许值的变化
1✔
126
     */
1✔
127
    @Input() thyChangeOn: (option: ThyCascaderOption, level: number) => boolean;
1✔
128

129
    /**
130
     * 点击项时,表单是否动态展示数据项
131
     * @type boolean
132
     */
133
    @Input({ transform: booleanAttribute }) thyChangeOnSelect = false;
134

51✔
135
    /**
34✔
136
     * 显示输入框
34✔
137
     * @type boolean
34✔
138
     */
139
    @Input({ transform: booleanAttribute }) thyShowInput = true;
140

141
    /**
142
     * 用户自定义模板
79✔
143
     * @type TemplateRef
37✔
144
     */
145
    @Input()
146
    set thyLabelRender(value: TemplateRef<any>) {
147
        this.labelRenderTpl = value;
51✔
148
        this.isLabelRenderTemplate = value instanceof TemplateRef;
204✔
149
        this.thyCascaderService.setCascaderOptions({ isLabelRenderTemplate: this.isLabelRenderTemplate });
150
    }
51✔
151

152
    get thyLabelRender(): TemplateRef<any> {
153
        return this.labelRenderTpl;
112✔
154
    }
112✔
155

29✔
156
    /**
157
     * 用于动态加载选项
158
     */
159
    @Input() set thyLoadData(value: (node: ThyCascaderOption, index?: number) => PromiseLike<any>) {
51✔
160
        this.thyCascaderService.setCascaderOptions({ loadData: value });
161
    }
162

13!
163
    get thyLoadData() {
13!
164
        return this.thyCascaderService?.cascaderOptions?.loadData;
×
165
    }
×
166

167
    /**
168
     * 控制触发状态, 支持 `click` | `hover`
169
     * @type ThyCascaderTriggerType | ThyCascaderTriggerType[]
1,752✔
170
     */
171
    @Input() thyTriggerAction: ThyCascaderTriggerType | ThyCascaderTriggerType[] = ['click'];
172

1,752✔
173
    /**
174
     * 鼠标经过下方列表项时,是否自动展开列表,支持 `click` | `hover`
175
     * @type ThyCascaderExpandTrigger | ThyCascaderExpandTrigger[]
1,752✔
176
     */
177
    @Input() thyExpandTriggerAction: ThyCascaderExpandTrigger | ThyCascaderExpandTrigger[] = ['click'];
178

35✔
179
    /**
35✔
180
     * 自定义浮层样式
13✔
181
     */
182
    @Input() thyMenuStyle: { [key: string]: string };
183

184
    /**
21✔
185
     * 自定义浮层类名
10✔
186
     * @type string
67✔
187
     */
188
    @Input()
189
    set thyMenuClassName(value: string) {
10✔
190
        this.menuClassName = value;
25✔
191
        this.setMenuClass();
22✔
192
    }
22✔
193

194
    get thyMenuClassName(): string {
195
        return this.menuClassName;
196
    }
197

198
    /**
76✔
199
     * 自定义浮层列类名
53✔
200
     * @type string
53✔
201
     */
53✔
202
    @Input()
53✔
203
    set thyColumnClassName(value: string) {
53✔
204
        this.columnClassName = value;
46✔
205
        this.setMenuClass();
46✔
206
    }
207

208
    get thyColumnClassName(): string {
7✔
209
        return this.columnClassName;
210
    }
53✔
211

212
    /**
213
     * 是否只读
214
     * @default false
353✔
215
     */
216
    @Input({ transform: booleanAttribute })
217
    override set thyDisabled(value: boolean) {
172✔
218
        this.disabled = value;
219
    }
220
    override get thyDisabled(): boolean {
221
        return this.disabled;
222
    }
223

224
    disabled = false;
225

661✔
226
    /**
227
     * 空状态下的展示文字
228
     * @default 暂无可选项
51✔
229
     */
230
    @Input()
231
    set thyEmptyStateText(value: string) {
232
        this.emptyStateText = value;
233
    }
234

435✔
235
    /**
236
     * 是否多选
237
     * @type boolean
51✔
238
     * @default false
239
     */
240
    @Input({ transform: booleanAttribute })
241
    set thyMultiple(value: boolean) {
242
        this.isMultiple = value;
243
        this.thyCascaderService.setCascaderOptions({ isMultiple: value });
244
    }
245

104✔
246
    get thyMultiple(): boolean {
247
        return this.isMultiple;
248
    }
249

250
    /**
251
     * 设置多选时最大显示的标签数量,0 表示不限制
252
     * @type number
104✔
253
     */
254
    @Input({ transform: numberAttribute }) thyMaxTagCount = 0;
255

33✔
256
    /**
24✔
257
     * 是否仅允许选择叶子项
258
     * @default true
9✔
259
     */
260
    @Input({ transform: booleanAttribute })
261
    thyIsOnlySelectLeaf = true;
4!
262

4✔
263
    /**
UNCOV
264
     * 初始化时,是否展开面板
×
265
     * @default false
266
     */
267
    @Input({ transform: booleanAttribute }) thyAutoExpand: boolean;
2!
268

2✔
269
    /**
UNCOV
270
     * 是否支持搜索
×
271
     * @default false
272
     */
273
    @Input({ transform: booleanAttribute }) thyShowSearch: boolean = false;
35✔
274

2✔
275
    /**
276
     * 多选选中项的展示方式,默认为空,渲染文字模板,传入tag,渲染展示模板,
33!
277
     * @default ''|tag
33✔
278
     */
279
    @Input() thyPreset: string = '';
280

281
    /**
2!
UNCOV
282
     * 是否有幕布
×
283
     */
284
    @Input({ transform: booleanAttribute }) thyHasBackdrop = true;
2✔
285

286
    /**
287
     * 值发生变化时触发,返回选择项的值
2✔
288
     * @type EventEmitter<any[]>
1✔
289
     */
1✔
290
    @Output() thyChange = new EventEmitter<any[]>();
291

1✔
292
    /**
1✔
293
     * 值发生变化时触发,返回选择项列表
1!
294
     * @type EventEmitter<ThyCascaderOption[]>
295
     */
UNCOV
296
    @Output() thySelectionChange = new EventEmitter<ThyCascaderOption[]>();
×
297

298
    /**
1✔
299
     * 选择选项时触发
300
     */
301
    @Output() thySelect = new EventEmitter<{
20✔
302
        option: ThyCascaderOption;
303
        index: number;
304
    }>();
2!
305

2✔
306
    /**
307
     * @private 暂无实现
2!
UNCOV
308
     */
×
309
    @Output() thyDeselect = new EventEmitter<{
310
        option: ThyCascaderOption;
2!
311
        index: number;
1✔
312
    }>();
313

1✔
314
    /**
315
     * 清空选项时触发
316
     */
317
    @Output() thyClear = new EventEmitter<void>();
1!
UNCOV
318

×
319
    /**
320
     * 下拉选项展开和折叠状态事件
1✔
321
     */
322
    @Output() thyExpandStatusChange: EventEmitter<boolean> = new EventEmitter<boolean>();
323

1!
324
    @ViewChildren('cascaderOptions', { read: ElementRef }) cascaderOptions: QueryList<ElementRef>;
1✔
325

1✔
326
    @ViewChildren('cascaderOptionContainers', { read: ElementRef }) cascaderOptionContainers: QueryList<ElementRef>;
327

328
    @ViewChild(CdkConnectedOverlay, { static: true }) cdkConnectedOverlay: CdkConnectedOverlay;
329

4✔
330
    @ViewChild('trigger', { read: ElementRef, static: true }) trigger: ElementRef<any>;
1✔
331

1✔
332
    @ViewChild('input') input: ElementRef;
1✔
333

1✔
334
    @ViewChild('menu') menu: ElementRef;
335

336
    public dropDownPosition = 'bottom';
4✔
337

4✔
338
    public menuVisible = false;
339

340
    public isLabelRenderTemplate = false;
1✔
341

1✔
342
    public triggerRect: DOMRect;
343

UNCOV
344
    public emptyStateText = '暂无可选项';
×
345

346
    private prefixCls = 'thy-cascader';
347

1!
348
    private menuClassName: string;
1✔
349

1✔
350
    private columnClassName: string;
351

1✔
352
    private _menuColumnCls: any;
1✔
353

354
    private readonly destroy$ = new Subject<void>();
1✔
355

356
    private _menuCls: { [name: string]: any };
357

51✔
358
    private _labelCls: { [name: string]: any };
51✔
359

51✔
360
    private labelRenderTpl: TemplateRef<any>;
51✔
361

51✔
362
    private hostRenderer = useHostRenderer();
51✔
363

51✔
364
    public positions: ConnectionPositionPair[];
51✔
365

51✔
366
    get selected(): SelectOptionBase | SelectOptionBase[] {
51✔
367
        return this.thyMultiple ? this.thyCascaderService.selectionModel.selected : this.thyCascaderService.selectionModel.selected[0];
51✔
368
    }
51✔
369
    private isMultiple = false;
51✔
370

51✔
371
    public menuMinWidth = 122;
51✔
372

51✔
373
    private searchText$ = new BehaviorSubject('');
51✔
374

51✔
375
    public get searchResultList(): ThyCascaderSearchOption[] {
51✔
376
        return this.thyCascaderService.searchResultList;
51✔
377
    }
51✔
378

51✔
379
    public isShowSearchPanel: boolean = false;
51✔
380

51✔
381
    /**
51✔
382
     * 解决搜索&多选的情况下,点击搜索项会导致 panel 闪烁
51✔
383
     * 由于点击后,thySelectedOptions变化,导致 thySelectControl
51✔
384
     * 又会触发 searchFilter 函数,即 resetSearch 会执行
51✔
385
     * 会导致恢复级联状态再变为搜索状态
51✔
386
     */
51✔
387
    private isSelectingSearchState: boolean = false;
51✔
388

51✔
389
    public get isLoading() {
51✔
390
        return this.thyCascaderService?.isLoading;
51✔
391
    }
51✔
392

51✔
393
    public get columns() {
51✔
394
        return this.thyCascaderService.columns;
51✔
395
    }
396

397
    private afterChangeFn: () => void;
398

399
    private resizeSubscription: Subscription;
400

401
    ngOnInit(): void {
51✔
402
        this.setClassMap();
51✔
403
        this.setMenuClass();
9✔
404
        this.setMenuColumnClass();
4✔
405
        this.setLabelClass();
4✔
406
        this.initPosition();
4✔
407
        this.initSearch();
408
        const options = {
409
            labelProperty: this.thyLabelProperty,
9✔
410
            valueProperty: this.thyValueProperty,
9✔
411
            isMultiple: this.isMultiple,
9!
412
            isOnlySelectLeaf: this.thyIsOnlySelectLeaf,
9✔
413
            isLabelRenderTemplate: this.isLabelRenderTemplate,
414
            loadData: this.thyLoadData
415
        };
416
        this.thyCascaderService.setCascaderOptions(options);
417

1,110!
418
        this.thyCascaderService.cascaderValueChange().subscribe(options => {
419
            if (!options.isValueEqual) {
420
                this.onChangeFn(options.value);
7✔
421
                if (options.isSelectionModelEmpty) {
1✔
422
                    this.thyClear.emit();
423
                }
7✔
424
                this.thySelectionChange.emit(this.thyCascaderService.selectedOptions);
425
                this.thyChange.emit(options.value);
426
                if (this.afterChangeFn) {
51✔
427
                    this.afterChangeFn();
52✔
428
                    this.afterChangeFn = null;
429
                }
6✔
430
            }
431
        });
6✔
432

6✔
433
        if (isPlatformBrowser(this.platformId)) {
434
            this.thyClickDispatcher
435
                .clicked(0)
436
                .pipe(takeUntil(this.destroy$))
6✔
437
                .subscribe(event => {
438
                    if (
439
                        !this.elementRef.nativeElement.contains(event.target) &&
8✔
440
                        !this.menu?.nativeElement.contains(event.target as Node) &&
8✔
441
                        this.menuVisible
8✔
442
                    ) {
443
                        this.ngZone.run(() => {
444
                            this.closeMenu();
1✔
445
                            this.cdr.markForCheck();
1!
UNCOV
446
                        });
×
UNCOV
447
                    }
×
448
                });
UNCOV
449
        }
×
450
    }
451

1✔
452
    ngAfterContentInit() {
3✔
453
        if (this.thyAutoExpand) {
454
            timer(0).subscribe(() => {
1!
455
                this.cdr.markForCheck();
×
456
                this.setMenuVisible(true);
×
457
            });
×
458
        }
UNCOV
459
    }
×
UNCOV
460

×
UNCOV
461
    ngOnChanges(changes: SimpleChanges): void {
×
UNCOV
462
        if (changes['thyIsOnlySelectLeaf']) {
×
463
            this.thyCascaderService.setCascaderOptions({ isOnlySelectLeaf: changes['thyIsOnlySelectLeaf'].currentValue });
464
        }
465
    }
466

1✔
467
    private initPosition() {
468
        const cascaderPosition: ConnectionPositionPair[] = EXPANDED_DROPDOWN_POSITIONS.map(item => {
469
            return { ...item };
470
        });
46✔
471
        this.positions = cascaderPosition;
46✔
472
    }
46✔
473

46✔
474
    writeValue(value: any): void {
55✔
475
        this.thyCascaderService.writeCascaderValue(value);
476
        if (this.isMultiple) {
46✔
477
            this.cdr.detectChanges();
478
        }
19✔
479
    }
19✔
480

19✔
481
    setDisabledState(isDisabled: boolean): void {
12✔
482
        this.disabled = isDisabled;
483
    }
19✔
484

485
    public positionChange(position: ConnectedOverlayPositionChange): void {
486
        const newValue = position.connectionPair.originY === 'bottom' ? 'bottom' : 'top';
487
        if (this.dropDownPosition !== newValue) {
488
            this.dropDownPosition = newValue;
489
            this.cdr.detectChanges();
104✔
490
        }
36✔
491
    }
36✔
492

493
    public isActivatedOption(option: ThyCascaderOption, index: number): boolean {
494
        return this.thyCascaderService.isActivatedOption(option, index);
495
    }
51✔
496

51✔
497
    public isHalfSelectedOption(option: ThyCascaderOption, index: number): boolean {
51✔
498
        return this.thyCascaderService.isHalfSelectedOption(option, index);
499
    }
1✔
500

501
    public isSelectedOption(option: ThyCascaderOption, index: number): boolean {
502
        return this.thyCascaderService.isSelectedOption(option, index);
503
    }
504

505
    public attached(): void {
506
        this.cdr.detectChanges();
507
        this.cdkConnectedOverlay.positionChange.pipe(take(1), takeUntil(this.destroy$)).subscribe(() => {
1✔
508
            this.scrollActiveElementIntoView();
509
        });
510
    }
511

512
    private scrollActiveElementIntoView() {
513
        if (!isEmpty(this.thyCascaderService.selectedOptions)) {
514
            const activeOptions = this.cascaderOptions
515
                .filter(item => item.nativeElement.classList.contains('thy-cascader-menu-item-active'))
516
                // for multiple mode
517
                .slice(-this.cascaderOptionContainers.length);
518

519
            this.cascaderOptionContainers.forEach((item, index) => {
520
                if (index <= activeOptions.length - 1) {
521
                    ScrollToService.scrollToElement(activeOptions[index].nativeElement, item.nativeElement);
522
                    this.cdr.detectChanges();
523
                }
524
            });
525
        }
526
    }
527

528
    public setMenuVisible(menuVisible: boolean): void {
529
        if (this.menuVisible !== menuVisible) {
530
            this.menuVisible = menuVisible;
531

532
            this.thyCascaderService.initActivatedOptions(this.menuVisible);
533
            this.setClassMap();
534
            this.setMenuClass();
535
            if (this.menuVisible) {
536
                this.triggerRect = this.trigger.nativeElement.getBoundingClientRect();
537
                this.subscribeTriggerResize();
538
            } else {
539
                this.unsubscribeTriggerResize();
540
            }
541
            this.thyExpandStatusChange.emit(menuVisible);
542
        }
543
    }
544

545
    public get menuCls(): any {
546
        return this._menuCls;
547
    }
548

549
    private setMenuClass(): void {
1✔
550
        this._menuCls = {
551
            [`${this.prefixCls}-menus`]: true,
552
            [`${this.prefixCls}-menus-hidden`]: !this.menuVisible,
553
            [`${this.thyMenuClassName}`]: this.thyMenuClassName,
554
            [`w-100`]: this.columns.length === 0
555
        };
556
    }
51✔
557

558
    public get menuColumnCls(): any {
559
        return this._menuColumnCls;
560
    }
561

562
    private setMenuColumnClass(): void {
563
        this._menuColumnCls = {
564
            [`${this.prefixCls}-menu`]: true,
565
            [`${this.thyColumnClassName}`]: this.thyColumnClassName
566
        };
567
    }
568

569
    public get labelCls(): any {
570
        return this._labelCls;
571
    }
572

573
    private setLabelClass(): void {
574
        this._labelCls = {
575
            [`${this.prefixCls}-picker-label`]: true,
576
            [`${this.prefixCls}-show-search`]: false,
577
            [`${this.prefixCls}-focused`]: false,
578
            'text-truncate': true
579
        };
580
    }
581

582
    private setClassMap(): void {
583
        const classMap = {
584
            [`${this.prefixCls}`]: true,
585
            [`${this.prefixCls}-picker`]: true,
586
            [`${this.prefixCls}-${this.thySize}`]: true,
587
            [`${this.prefixCls}-picker-disabled`]: this.disabled,
588
            [`${this.prefixCls}-picker-open`]: this.menuVisible
589
        };
590
        this.hostRenderer.updateClassByMap(classMap);
591
    }
592

593
    private isClickTriggerAction(): boolean {
594
        if (typeof this.thyTriggerAction === 'string') {
595
            return this.thyTriggerAction === 'click';
596
        }
597
        return this.thyTriggerAction.indexOf('click') !== -1;
598
    }
599

600
    private isHoverTriggerAction(): boolean {
601
        if (typeof this.thyTriggerAction === 'string') {
602
            return this.thyTriggerAction === 'hover';
603
        }
604
        return this.thyTriggerAction.indexOf('hover') !== -1;
605
    }
606

607
    private isHoverExpandTriggerAction(): boolean {
608
        if (typeof this.thyExpandTriggerAction === 'string') {
609
            return this.thyExpandTriggerAction === 'hover';
610
        }
611
        return this.thyExpandTriggerAction.indexOf('hover') !== -1;
612
    }
613

614
    @HostListener('click', ['$event'])
615
    public toggleClick($event: Event) {
616
        if (this.disabled) {
617
            return;
618
        }
619
        if (this.isClickTriggerAction()) {
620
            this.setMenuVisible(!this.menuVisible);
621
        }
622
    }
623

624
    @HostListener('mouseenter', ['$event'])
625
    public toggleMouseEnter(event: MouseEvent): void {
626
        if (this.disabled || !this.isHoverTriggerAction() || this.menuVisible) {
627
            return;
628
        }
629

630
        this.setMenuVisible(true);
631
    }
632

633
    @HostListener('mouseleave', ['$event'])
634
    public toggleMouseLeave(event: MouseEvent): void {
635
        if (this.disabled || !this.isHoverTriggerAction() || !this.menuVisible) {
636
            event.preventDefault();
637
            return;
638
        }
639

640
        const hostEl = this.elementRef.nativeElement;
641
        const mouseTarget = event.relatedTarget as HTMLElement;
642
        if (
643
            hostEl.contains(mouseTarget) ||
644
            mouseTarget?.classList.contains('cdk-overlay-pane') ||
645
            mouseTarget?.classList.contains('cdk-overlay-backdrop')
646
        ) {
647
            return;
648
        }
649

650
        this.setMenuVisible(false);
651
    }
652

653
    public clickOption(option: ThyCascaderOption, index: number, event: Event | boolean): void {
654
        this.thyCascaderService.clickOption(option, index, event, this.selectOption);
655
    }
656

657
    public mouseoverOption(option: ThyCascaderOption, index: number, event: Event): void {
658
        if (event) {
659
            event.preventDefault();
660
        }
661

662
        if (option && option.disabled && !this.isMultiple) {
663
            return;
664
        }
665

666
        if (!this.isHoverExpandTriggerAction() && !(option && option.disabled && this.isMultiple)) {
667
            return;
668
        }
669
        this.setActiveOption(option, index, false);
670
    }
671

672
    onBlur(event?: FocusEvent) {
673
        // Tab 聚焦后自动聚焦到 input 输入框,此分支下直接返回,无需触发 onTouchedFn
674
        if (elementMatchClosest(event?.relatedTarget as HTMLElement, ['.thy-cascader-menus', 'thy-cascader'])) {
675
            return;
676
        }
677
        this.onTouchedFn();
678
    }
679

680
    onFocus(event?: FocusEvent) {
681
        if (!elementMatchClosest(event?.relatedTarget as HTMLElement, ['.thy-cascader-menus', 'thy-cascader'])) {
682
            const inputElement: HTMLInputElement = this.elementRef.nativeElement.querySelector('input');
683
            inputElement.focus();
684
        }
685
    }
686

687
    public closeMenu(): void {
688
        if (this.menuVisible) {
689
            this.setMenuVisible(false);
690
            this.onTouchedFn();
691
            this.isShowSearchPanel = false;
692
            this.thyCascaderService.searchResultList = [];
693
        }
694
    }
695

696
    public setActiveOption(option: ThyCascaderOption, index: number, select: boolean, loadChildren: boolean = true): void {
697
        this.thyCascaderService.setActiveOption(option, index, select, loadChildren, this.selectOption);
698
    }
699

700
    private selectOption = (option: ThyCascaderOption, index: number) => {
701
        if ((option.isLeaf || !this.thyIsOnlySelectLeaf) && !this.thyMultiple) {
702
            this.afterChangeFn = () => {
703
                this.setMenuVisible(false);
704
                this.onTouchedFn();
705
            };
706
        }
707
        this.thySelect.emit({ option, index });
708
        const isOptionCanSelect = this.thyChangeOnSelect && !this.isMultiple;
709
        if (option.isLeaf || !this.thyIsOnlySelectLeaf || isOptionCanSelect || this.shouldPerformSelection(option, index)) {
710
            this.thyCascaderService.selectOption(option, index);
711
        }
712
    };
713

714
    public removeSelectedItem(event: { item: SelectOptionBase; $eventOrigin: Event }) {
715
        event.$eventOrigin.stopPropagation();
716
        this.thyCascaderService.removeSelectedItem(event?.item);
717
    }
718

719
    private shouldPerformSelection(option: ThyCascaderOption, level: number): boolean {
720
        return typeof this.thyChangeOn === 'function' ? this.thyChangeOn(option, level) === true : false;
721
    }
722

723
    public clearSelection($event: Event): void {
724
        if ($event) {
725
            $event.stopPropagation();
726
            $event.preventDefault();
727
        }
728
        this.afterChangeFn = () => {
729
            this.setMenuVisible(false);
730
        };
731
        this.thyCascaderService.clearSelection();
732
    }
733

734
    constructor(
735
        @Inject(PLATFORM_ID) private platformId: string,
736
        private cdr: ChangeDetectorRef,
737
        public elementRef: ElementRef,
738
        private thyClickDispatcher: ThyClickDispatcher,
739
        private ngZone: NgZone,
740
        public thyCascaderService: ThyCascaderService
741
    ) {
742
        super();
743
    }
744

745
    public trackByFn(index: number, item: ThyCascaderOption) {
746
        return item?.value || item?._id || index;
747
    }
748

749
    public searchFilter(searchText: string) {
750
        if (!searchText && !this.isSelectingSearchState) {
751
            this.resetSearch();
752
        }
753
        this.searchText$.next(searchText);
754
    }
755

756
    private initSearch() {
757
        this.searchText$
758
            .pipe(
759
                takeUntil(this.destroy$),
760
                debounceTime(200),
761
                distinctUntilChanged(),
762
                filter(text => text !== '')
763
            )
764
            .subscribe(searchText => {
765
                this.resetSearch();
766

767
                // local search
768
                this.searchInLocal(searchText);
769
                this.isShowSearchPanel = true;
770
            });
771
    }
772

773
    private searchInLocal(searchText: string): void {
774
        this.thyCascaderService.searchInLocal(searchText);
775
    }
776

777
    private resetSearch() {
778
        this.isShowSearchPanel = false;
779
        this.thyCascaderService.resetSearch();
780
        this.scrollActiveElementIntoView();
781
    }
782

783
    public selectSearchResult(selectOptionData: ThyCascaderSearchOption): void {
784
        const { thyRowValue: selectedOptions } = selectOptionData;
785
        if (selectOptionData.selected) {
786
            if (!this.isMultiple) {
787
                this.closeMenu();
788
            }
789
            return;
790
        }
791
        selectedOptions.forEach((item: ThyCascaderOption, index: number) => {
792
            this.setActiveOption(item, index, index === selectedOptions.length - 1);
793
        });
794
        if (this.isMultiple) {
795
            this.isSelectingSearchState = true;
796
            selectOptionData.selected = true;
797
            const originSearchResultList = this.searchResultList;
798
            // 保持搜索选项
799
            setTimeout(() => {
800
                this.isShowSearchPanel = true;
801
                this.thyCascaderService.searchResultList = originSearchResultList;
802
                this.isSelectingSearchState = false;
803
            });
804
        } else {
805
            this.resetSearch();
806
        }
807
    }
808

809
    private subscribeTriggerResize(): void {
810
        this.unsubscribeTriggerResize();
811
        this.ngZone.runOutsideAngular(() => {
812
            this.resizeSubscription = new Observable(observer => {
813
                const resize = new ResizeObserver((entries: ResizeObserverEntry[]) => {
814
                    observer.next();
815
                });
816
                resize.observe(this.trigger.nativeElement);
817
            }).subscribe(() => {
818
                this.ngZone.run(() => {
819
                    this.triggerRect = this.trigger.nativeElement.getBoundingClientRect();
820
                    if (this.cdkConnectedOverlay && this.cdkConnectedOverlay.overlayRef) {
821
                        this.cdkConnectedOverlay.overlayRef.updatePosition();
822
                    }
823
                    this.cdr.markForCheck();
824
                });
825
            });
826
        });
827
    }
828

829
    private unsubscribeTriggerResize(): void {
830
        if (this.resizeSubscription) {
831
            this.resizeSubscription.unsubscribe();
832
            this.resizeSubscription = null;
833
        }
834
    }
835

836
    ngOnDestroy() {
837
        this.unsubscribeTriggerResize();
838
        this.destroy$.next();
839
        this.destroy$.complete();
840
    }
841
}
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