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

atinc / ngx-tethys / b902eee1-accd-4360-b235-09475b1cbff9

25 Apr 2025 03:06AM UTC coverage: 90.264% (-0.005%) from 90.269%
b902eee1-accd-4360-b235-09475b1cbff9

push

circleci

web-flow
fix(nav): the default value of showMore should be false #TINFR-1943 (#3364)

5614 of 6878 branches covered (81.62%)

Branch coverage included in aggregate %.

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

8 existing lines in 2 files now uncovered.

13365 of 14148 relevant lines covered (94.47%)

922.18 hits per line

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

87.4
/src/nav/nav.component.ts
1
import { ThyPopover, ThyPopoverConfig } from 'ngx-tethys/popover';
2
import { merge, Observable, of } from 'rxjs';
3
import { startWith, take, tap } from 'rxjs/operators';
4
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
5
import { useHostRenderer } from '@tethys/cdk/dom';
6
import {
7
    AfterContentChecked,
8
    AfterContentInit,
9
    AfterViewInit,
10
    ChangeDetectionStrategy,
11
    ChangeDetectorRef,
12
    Component,
13
    ContentChild,
14
    ContentChildren,
15
    DestroyRef,
16
    ElementRef,
17
    HostBinding,
18
    inject,
19
    input,
1✔
20
    Input,
21
    NgZone,
22
    OnChanges,
23
    OnDestroy,
24
    OnInit,
25
    QueryList,
26
    signal,
27
    Signal,
28
    SimpleChanges,
29
    TemplateRef,
30
    ViewChild,
31
    WritableSignal
1✔
32
} from '@angular/core';
33

34
import { RouterLinkActive } from '@angular/router';
35
import { ThyNavInkBarDirective } from './nav-ink-bar.directive';
36
import { ThyNavItemDirective } from './nav-item.directive';
1✔
37
import { BypassSecurityTrustHtmlPipe } from './nav.pipe';
38
import { ThyDropdownMenuComponent, ThyDropdownMenuItemDirective, ThyDropdownMenuItemActiveDirective } from 'ngx-tethys/dropdown';
39
import { ThyIcon } from 'ngx-tethys/icon';
40
import { NgClass, NgTemplateOutlet } from '@angular/common';
41
import { coerceBooleanProperty } from 'ngx-tethys/util';
42
import { injectLocale, ThyNavLocale } from 'ngx-tethys/i18n';
1✔
43
import { ThyPlacement } from 'ngx-tethys/core';
44

49✔
45
export type ThyNavType = 'pulled' | 'tabs' | 'pills' | 'lite' | 'card' | 'primary' | 'secondary' | 'thirdly' | 'secondary-divider';
49✔
46
export type ThyNavSize = 'lg' | 'md' | 'sm';
49✔
47
export type ThyNavHorizontal = '' | 'start' | 'center' | 'end';
49✔
48

49✔
49
const navTypeClassesMap = {
49✔
50
    pulled: ['thy-nav-pulled'],
49✔
51
    tabs: ['thy-nav-tabs'],
49✔
52
    pills: ['thy-nav-pills'],
49✔
53
    lite: ['thy-nav-lite'],
54
    card: ['thy-nav-card'],
55
    //如下类型已经废弃
56
    primary: ['thy-nav-primary'],
57
    secondary: ['thy-nav-secondary'],
58
    thirdly: ['thy-nav-thirdly'],
49✔
59
    'secondary-divider': ['thy-nav-secondary-divider']
49✔
60
};
49✔
61

49✔
62
const navSizeClassesMap = {
49✔
63
    lg: 'thy-nav-lg',
49✔
64
    md: 'thy-nav-md',
49✔
65
    sm: 'thy-nav-sm'
49✔
66
};
49✔
67

49✔
68
const tabItemRight = 20;
49✔
69

70
/**
71
 * 导航组件
72✔
72
 * @name thy-nav
72✔
73
 * @order 10
23✔
74
 */
75
@Component({
76
    selector: 'thy-nav',
77
    templateUrl: './nav.component.html',
52✔
78
    host: {
52✔
79
        class: 'thy-nav'
5✔
80
    },
81
    changeDetection: ChangeDetectionStrategy.OnPush,
82
    imports: [
83
        NgClass,
21!
84
        NgTemplateOutlet,
85
        ThyNavItemDirective,
86
        ThyIcon,
55✔
87
        ThyNavInkBarDirective,
55✔
88
        ThyDropdownMenuComponent,
89
        ThyDropdownMenuItemDirective,
90
        ThyDropdownMenuItemActiveDirective,
697✔
91
        BypassSecurityTrustHtmlPipe
92
    ]
93
})
270✔
94
export class ThyNav implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked, OnChanges, OnDestroy {
270✔
95
    private elementRef = inject(ElementRef);
96
    private ngZone = inject(NgZone);
97
    private changeDetectorRef = inject(ChangeDetectorRef);
77✔
98
    private popover = inject(ThyPopover);
77!
99

77✔
100
    private readonly destroyRef = inject(DestroyRef);
101

77✔
102
    public type: ThyNavType = 'pulled';
48✔
103
    private size: ThyNavSize = 'md';
104
    public initialized = false;
77✔
105

106
    public horizontal: ThyNavHorizontal;
107
    public wrapperOffset: { height: number; width: number; left: number; top: number } = {
49✔
108
        height: 0,
41✔
109
        width: 0,
110
        left: 0,
49✔
111
        top: 0
112
    };
113

49✔
114
    public hiddenItems: ThyNavItemDirective[] = [];
8✔
115

8✔
116
    public moreActive: boolean;
21✔
117

8✔
118
    readonly showMore: WritableSignal<boolean> = signal(false);
119

120
    private moreBtnOffset: { height: number; width: number } = { height: 0, width: 0 };
49✔
121

49✔
122
    private hostRenderer = useHostRenderer();
55✔
123

6✔
124
    private innerLinks: QueryList<ThyNavItemDirective>;
125

159!
126
    locale: Signal<ThyNavLocale> = injectLocale('nav');
127

4!
UNCOV
128
    /**
×
129
     * 导航类型
130
     * @type pulled | tabs | pills | lite | primary | secondary | thirdly | secondary-divider
4✔
131
     * @default pulled
1✔
132
     */
1✔
133
    @Input()
1✔
134
    set thyType(type: ThyNavType) {
135
        this.type = type || 'pulled';
4!
UNCOV
136
        if (this.initialized) {
×
137
            this.updateClasses();
138
        }
139
    }
140

4✔
141
    /**
142
     * 导航大小
143
     * @type lg | md | sm
144
     * @default md
145
     */
146
    @Input()
49✔
147
    set thySize(size: ThyNavSize) {
8✔
148
        this.size = size;
8✔
149
        if (this.initialized) {
150
            this.updateClasses();
151
        }
152
    }
153

138✔
154
    /**
213✔
155
     * 水平排列
138✔
156
     * @type '' | 'start' | 'center' | 'end'
25✔
157
     * @default false
158
     */
113✔
159
    @Input()
53✔
160
    set thyHorizontal(horizontal: ThyNavHorizontal) {
161
        this.horizontal = (horizontal as string) === 'right' ? 'end' : horizontal;
162
    }
163

8✔
164
    /**
165
     * 是否垂直排列
166
     * @default false
167
     */
168
    @HostBinding('class.thy-nav--vertical')
UNCOV
169
    @Input({ transform: coerceBooleanProperty })
×
UNCOV
170
    thyVertical: boolean;
×
171

×
172
    /**
×
173
     * 是否是填充模式
×
174
     */
175
    @HostBinding('class.thy-nav--fill')
UNCOV
176
    @Input({ transform: coerceBooleanProperty })
×
177
    thyFill: boolean = false;
178

179
    /**
180
     * 是否响应式,自动计算宽度存放 thyNavItem,并添加更多弹框
181
     * @default false
214!
182
     */
183
    @Input({ transform: coerceBooleanProperty })
184
    thyResponsive: boolean;
214✔
UNCOV
185

×
186
    /**
187
     * 支持暂停自适应计算
214✔
188
     */
214✔
189
    thyPauseReCalculate = input<boolean>(false);
214✔
190

191
    /**
192
     * 更多操作的菜单点击内部是否可关闭
193
     * @deprecated please use thyPopoverOptions
194
     */
139✔
195
    @Input({ transform: coerceBooleanProperty })
34✔
196
    thyInsideClosable = true;
197

139✔
198
    /**
199
     * 更多菜单弹出框的参数,底层使用 Popover 组件
200
     * @type ThyPopoverConfig
9✔
201
     */
9✔
202
    thyPopoverOptions = input<ThyPopoverConfig<unknown>>(null);
9✔
203

1✔
204
    /**
1✔
205
     * 右侧额外区域模板
1✔
206
     * @type TemplateRef
207
     */
8✔
208
    @Input() thyExtra: TemplateRef<unknown>;
8✔
209

8!
210
    /**
7✔
211
     * @private
212
     */
8!
213
    @ContentChildren(ThyNavItemDirective, { descendants: true })
8!
214
    set links(value) {
17✔
215
        this.innerLinks = value;
216
        this.prevActiveIndex = NaN;
8✔
217
    }
8✔
218
    get links(): QueryList<ThyNavItemDirective> {
219
        return this.innerLinks;
220
    }
7✔
221

7✔
222
    /**
7✔
223
     * @private
7✔
224
     */
19✔
225
    @ContentChildren(RouterLinkActive, { descendants: true }) routers: QueryList<RouterLinkActive>;
19✔
226

7✔
227
    /**
7✔
228
     * 响应式模式下更多操作模板
1✔
229
     * @type TemplateRef
230
     */
231
    @ContentChild('more') moreOperation: TemplateRef<unknown>;
6✔
232

233
    /**
7✔
234
     * 响应式模式下更多弹框模板
235
     * @type TemplateRef
236
     */
12✔
237
    @ContentChild('morePopover') morePopover: TemplateRef<unknown>;
12✔
238

239
    /**
240
     * 右侧额外区域模板,支持 thyExtra 传参和 <ng-template #extra></ng-template> 模板
7✔
241
     * @name extra
242
     * @type TemplateRef
243
     */
1✔
244
    @ContentChild('extra') extra: TemplateRef<unknown>;
1✔
245

1✔
246
    @ViewChild('moreOperationContainer') defaultMoreOperation: ElementRef<HTMLAnchorElement>;
1✔
247

3✔
248
    @ViewChild(ThyNavInkBarDirective, { static: true }) inkBar!: ThyNavInkBarDirective;
3✔
249

1✔
250
    get showInkBar(): boolean {
1!
UNCOV
251
        const showTypes: ThyNavType[] = ['pulled', 'tabs'];
×
252
        return showTypes.includes(this.type);
253
    }
254

1✔
255
    private updateClasses() {
256
        let classNames: string[] = [];
1✔
257
        if (navTypeClassesMap[this.type]) {
258
            classNames = [...navTypeClassesMap[this.type]];
259
        }
2✔
260
        if (navSizeClassesMap[this.size]) {
2✔
261
            classNames.push(navSizeClassesMap[this.size]);
262
        }
263
        this.hostRenderer.updateClass(classNames);
1✔
264
    }
265

266
    private curActiveIndex: number;
9✔
267

9!
268
    private prevActiveIndex: number = NaN;
9!
269

10✔
270
    private navSubscription: { unsubscribe: () => void } | null = null;
10✔
271

272
    ngOnInit() {
273
        if (!this.thyResponsive) {
274
            this.initialized = true;
2✔
275
        }
276

277
        this.updateClasses();
278
    }
279

280
    ngAfterViewInit() {
281
        if (this.thyResponsive) {
282
            this.setMoreBtnOffset();
2!
283
            this.ngZone.onStable.pipe(take(1)).subscribe(() => {
284
                this.links.toArray().forEach(link => link.setOffset());
285
                this.setHiddenItems();
1✔
286
            });
287
        }
288

131✔
289
        this.ngZone.runOutsideAngular(() => {
16✔
290
            this.links.changes.pipe(startWith(this.links), takeUntilDestroyed(this.destroyRef)).subscribe(() => {
16✔
291
                if (this.navSubscription) {
292
                    this.navSubscription.unsubscribe();
115✔
293
                }
115✔
294

115✔
295
                this.navSubscription = merge(
115✔
296
                    this.createResizeObserver(this.elementRef.nativeElement),
2✔
297
                    ...this.links.map(item => this.createResizeObserver(item.elementRef.nativeElement).pipe(tap(() => item.setOffset()))),
298
                    ...(this.routers || []).map(router => router?.isActiveChange)
115✔
299
                )
66✔
300
                    .pipe(
66✔
301
                        takeUntilDestroyed(this.destroyRef),
302
                        tap(() => {
303
                            if (this.thyPauseReCalculate()) {
304
                                return;
82✔
305
                            }
82✔
306

74✔
307
                            if (this.thyResponsive) {
308
                                this.resetSizes();
309
                                this.setHiddenItems();
310
                                this.calculateMoreIsActive();
49!
311
                            }
49✔
312

313
                            if (this.type === 'card') {
314
                                this.setNavItemDivider();
1✔
315
                            }
316
                        })
317
                    )
318
                    .subscribe(() => {
319
                        this.alignInkBarToSelectedTab();
320
                    });
321
            });
322
        });
323
    }
324

325
    ngAfterContentInit(): void {
326
        if (this.thyResponsive) {
327
            this.ngZone.onStable.pipe(take(1)).subscribe(() => {
328
                this.resetSizes();
329
            });
330
        }
331
    }
332

333
    ngAfterContentChecked() {
334
        this.calculateMoreIsActive();
1✔
335

336
        this.curActiveIndex = this.links && this.links.length ? this.links.toArray().findIndex(item => item.linkIsActive()) : -1;
337
        if (this.curActiveIndex < 0) {
338
            this.inkBar.hide();
339
        } else if (this.curActiveIndex !== this.prevActiveIndex) {
340
            this.alignInkBarToSelectedTab();
341
        }
342
    }
343

344
    private setMoreBtnOffset() {
345
        this.moreBtnOffset = {
346
            height: this.defaultMoreOperation?.nativeElement?.offsetHeight,
347
            width: this.defaultMoreOperation?.nativeElement?.offsetWidth
348
        };
349
    }
350

351
    private setNavItemDivider() {
352
        const tabs = this.links.toArray();
353
        const activeIndex = tabs.findIndex(item => item.linkIsActive());
354

355
        for (let i = 0; i < tabs.length; i++) {
356
            if ((i !== activeIndex && i !== activeIndex - 1 && i !== tabs.length - 1) || (i === activeIndex - 1 && this.moreActive)) {
357
                tabs[i].addClass('has-right-divider');
358
            } else {
359
                tabs[i].removeClass('has-right-divider');
360
            }
361
        }
362
    }
363

364
    createResizeObserver(element: HTMLElement) {
365
        return typeof ResizeObserver === 'undefined'
366
            ? of(null)
367
            : new Observable(observer => {
368
                  const resize = new ResizeObserver(entries => {
369
                      observer.next(entries);
370
                  });
371
                  resize.observe(element);
372
                  return () => {
373
                      resize.disconnect();
374
                  };
375
              });
376
    }
377

378
    private calculateMoreIsActive() {
379
        this.moreActive = this.hiddenItems.some(item => {
380
            return item.linkIsActive();
381
        });
382
        this.changeDetectorRef.detectChanges();
383
    }
384

385
    private setHiddenItems() {
386
        this.moreActive = false;
387
        const tabs = this.links.toArray();
388
        if (!tabs.length) {
389
            this.hiddenItems = [];
390
            this.showMore.set(false);
391
            return;
392
        }
393

394
        const endIndex = this.thyVertical ? this.getShowItemsEndIndexWhenVertical(tabs) : this.getShowItemsEndIndexWhenHorizontal(tabs);
395

396
        const showItems = tabs.slice(0, endIndex + 1);
397
        (showItems || []).forEach(item => {
398
            item.setNavLinkHidden(false);
399
        });
400

401
        this.hiddenItems = endIndex === tabs.length - 1 ? [] : tabs.slice(endIndex + 1);
402
        (this.hiddenItems || []).forEach(item => {
403
            item.setNavLinkHidden(true);
404
        });
405

406
        this.showMore.set(this.hiddenItems.length > 0);
407
        this.initialized = true;
408
    }
409

410
    private getShowItemsEndIndexWhenHorizontal(tabs: ThyNavItemDirective[]) {
411
        const tabsLength = tabs.length;
412
        let endIndex = tabsLength;
413
        let totalWidth = 0;
414

415
        for (let i = 0; i < tabsLength; i += 1) {
416
            const _totalWidth = i === tabsLength - 1 ? totalWidth + tabs[i].offset.width : totalWidth + tabs[i].offset.width + tabItemRight;
417
            if (_totalWidth > this.wrapperOffset.width) {
418
                let moreOperationWidth = this.moreBtnOffset.width;
419
                if (totalWidth + moreOperationWidth <= this.wrapperOffset.width) {
420
                    endIndex = i - 1;
421
                } else {
422
                    endIndex = i - 2;
423
                }
424
                break;
425
            } else {
426
                totalWidth = _totalWidth;
427
                endIndex = i;
428
            }
429
        }
430
        return endIndex;
431
    }
432

433
    private getShowItemsEndIndexWhenVertical(tabs: ThyNavItemDirective[]) {
434
        const tabsLength = tabs.length;
435
        let endIndex = tabsLength;
436
        let totalHeight = 0;
437
        for (let i = 0; i < tabsLength; i += 1) {
438
            const _totalHeight = totalHeight + tabs[i].offset.height;
439
            if (_totalHeight > this.wrapperOffset.height) {
440
                let moreOperationHeight = this.moreBtnOffset.height;
441
                if (totalHeight + moreOperationHeight <= this.wrapperOffset.height) {
442
                    endIndex = i - 1;
443
                } else {
444
                    endIndex = i - 2;
445
                }
446
                break;
447
            } else {
448
                totalHeight = _totalHeight;
449
                endIndex = i;
450
            }
451
        }
452
        return endIndex;
453
    }
454

455
    private resetSizes() {
456
        this.wrapperOffset = {
457
            height: this.elementRef.nativeElement.offsetHeight || 0,
458
            width: this.elementRef.nativeElement.offsetWidth || 0,
459
            left: this.elementRef.nativeElement.offsetLeft || 0,
460
            top: this.elementRef.nativeElement.offsetTop || 0
461
        };
462
    }
463

464
    openMoreMenu(event: Event, template: TemplateRef<any>) {
465
        this.popover.open(
466
            template,
467
            Object.assign(
468
                {
469
                    origin: event.currentTarget as HTMLElement,
470
                    hasBackdrop: true,
471
                    backdropClosable: true,
472
                    insideClosable: true,
473
                    placement: 'bottom' as ThyPlacement,
474
                    panelClass: 'thy-nav-list-popover',
475
                    originActiveClass: 'thy-nav-origin-active'
476
                },
477
                this.thyPopoverOptions() ? this.thyPopoverOptions() : {}
478
            )
479
        );
480
    }
481

482
    navItemClick(item: ThyNavItemDirective) {
483
        item.elementRef.nativeElement.click();
484
    }
485

486
    private alignInkBarToSelectedTab(): void {
487
        if (!this.showInkBar) {
488
            this.inkBar.hide();
489
            return;
490
        }
491
        const tabs = this.links?.toArray() ?? [];
492
        const selectedItem = tabs.find(item => item.linkIsActive());
493
        let selectedItemElement: HTMLElement = selectedItem && selectedItem.elementRef.nativeElement;
494

495
        if (selectedItem && this.moreActive) {
496
            selectedItemElement = this.defaultMoreOperation.nativeElement;
497
        }
498
        if (selectedItemElement) {
499
            this.prevActiveIndex = this.curActiveIndex;
500
            this.inkBar.alignToElement(selectedItemElement);
501
        }
502
    }
503

504
    ngOnChanges(changes: SimpleChanges): void {
505
        const { thyVertical, thyType } = changes;
506

507
        if (thyType?.currentValue !== thyType?.previousValue || thyVertical?.currentValue !== thyVertical?.previousValue) {
508
            this.alignInkBarToSelectedTab();
509
        }
510
    }
511

512
    ngOnDestroy() {
513
        if (this.navSubscription) {
514
            this.navSubscription.unsubscribe();
515
        }
516
    }
517
}
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

© 2026 Coveralls, Inc