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

atinc / ngx-tethys / 3175bd09-7257-4520-af06-32481b06712b

10 Feb 2025 06:18AM UTC coverage: 90.278% (-0.002%) from 90.28%
3175bd09-7257-4520-af06-32481b06712b

Pull #3293

circleci

minlovehua
fix: ci error
Pull Request #3293: fix(nav): need to monitor the resize changes of the newly added nav item #TINFR-1492

5570 of 6825 branches covered (81.61%)

Branch coverage included in aggregate %.

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

7 existing lines in 2 files now uncovered.

13281 of 14056 relevant lines covered (94.49%)

991.61 hits per line

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

87.97
/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
    OnInit,
24
    QueryList,
25
    Signal,
26
    SimpleChanges,
27
    TemplateRef,
28
    ViewChild
29
} from '@angular/core';
30

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

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

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

49✔
59
const navSizeClassesMap = {
49✔
60
    lg: 'thy-nav-lg',
49✔
61
    md: 'thy-nav-md',
49✔
62
    sm: 'thy-nav-sm'
49✔
63
};
49✔
64

49✔
65
const tabItemRight = 20;
49✔
66

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

77!
98
    private readonly destroyRef = inject(DestroyRef);
77✔
99

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

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

112
    public hiddenItems: ThyNavItemDirective[] = [];
49✔
113

8✔
114
    public moreActive: boolean;
8✔
115

21✔
116
    public showMore = true;
8✔
117

118
    private moreBtnOffset: { height: number; width: number } = { height: 0, width: 0 };
119

49✔
120
    private hostRenderer = useHostRenderer();
49✔
121

55✔
122
    private innerLinks: QueryList<ThyNavItemDirective>;
6✔
123

124
    locale: Signal<ThyNavLocale> = injectLocale('nav');
159!
125

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

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

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

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

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

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

214✔
184
    /**
214✔
185
     * 更多操作的菜单点击内部是否可关闭
214✔
186
     * @deprecated please use thyPopoverOptions
187
     */
188
    @Input({ transform: coerceBooleanProperty })
189
    thyInsideClosable = true;
190

139✔
191
    /**
34✔
192
     * 更多菜单弹出框的参数,底层使用 Popover 组件
193
     * @type ThyPopoverConfig
139✔
194
     */
195
    thyPopoverOptions = input<ThyPopoverConfig<unknown>>(null);
196

9✔
197
    /**
9✔
198
     * 右侧额外区域模板
9✔
199
     * @type TemplateRef
1✔
200
     */
1✔
201
    @Input() thyExtra: TemplateRef<unknown>;
1✔
202

203
    /**
8✔
204
     * @private
8✔
205
     */
8!
206
    @ContentChildren(ThyNavItemDirective, { descendants: true })
7✔
207
    set links(value) {
208
        this.innerLinks = value;
8!
209
        this.prevActiveIndex = NaN;
8!
210
    }
17✔
211
    get links(): QueryList<ThyNavItemDirective> {
212
        return this.innerLinks;
8✔
213
    }
8✔
214

215
    /**
216
     * @private
7✔
217
     */
7✔
218
    @ContentChildren(RouterLinkActive, { descendants: true }) routers: QueryList<RouterLinkActive>;
7✔
219

7✔
220
    /**
19✔
221
     * 响应式模式下更多操作模板
19✔
222
     * @type TemplateRef
7✔
223
     */
7✔
224
    @ContentChild('more') moreOperation: TemplateRef<unknown>;
1✔
225

226
    /**
227
     * 响应式模式下更多弹框模板
6✔
228
     * @type TemplateRef
229
     */
7✔
230
    @ContentChild('morePopover') morePopover: TemplateRef<unknown>;
231

232
    /**
12✔
233
     * 右侧额外区域模板,支持 thyExtra 传参和 <ng-template #extra></ng-template> 模板
12✔
234
     * @name extra
235
     * @type TemplateRef
236
     */
7✔
237
    @ContentChild('extra') extra: TemplateRef<unknown>;
238

239
    @ViewChild('moreOperationContainer') defaultMoreOperation: ElementRef<HTMLAnchorElement>;
1✔
240

1✔
241
    @ViewChild(ThyNavInkBarDirective, { static: true }) inkBar!: ThyNavInkBarDirective;
1✔
242

1✔
243
    get showInkBar(): boolean {
3✔
244
        const showTypes: ThyNavType[] = ['pulled', 'tabs'];
3✔
245
        return showTypes.includes(this.type);
1✔
246
    }
1!
UNCOV
247

×
248
    private updateClasses() {
249
        let classNames: string[] = [];
250
        if (navTypeClassesMap[this.type]) {
1✔
251
            classNames = [...navTypeClassesMap[this.type]];
252
        }
1✔
253
        if (navSizeClassesMap[this.size]) {
254
            classNames.push(navSizeClassesMap[this.size]);
255
        }
2✔
256
        this.hostRenderer.updateClass(classNames);
2✔
257
    }
258

259
    private curActiveIndex: number;
1✔
260

261
    private prevActiveIndex: number = NaN;
262

9✔
263
    private navSubscription: { unsubscribe: () => void } | null = null;
9!
264

9!
265
    ngOnInit() {
10✔
266
        if (!this.thyResponsive) {
10✔
267
            this.initialized = true;
268
        }
269

270
        this.updateClasses();
2✔
271
    }
272

273
    ngAfterViewInit() {
274
        if (this.thyResponsive) {
275
            this.setMoreBtnOffset();
276
            this.ngZone.onStable.pipe(take(1)).subscribe(() => {
277
                this.links.toArray().forEach(link => link.setOffset());
278
                this.setHiddenItems();
2!
279
            });
280
        }
281

1✔
282
        this.ngZone.runOutsideAngular(() => {
283
            this.links.changes.pipe(startWith(this.links), takeUntilDestroyed(this.destroyRef)).subscribe(() => {
284
                if (this.navSubscription) {
131✔
285
                    this.navSubscription.unsubscribe();
16✔
286
                }
16✔
287

288
                this.navSubscription = merge(
115✔
289
                    this.createResizeObserver(this.elementRef.nativeElement),
115✔
290
                    ...this.links.map(item => this.createResizeObserver(item.elementRef.nativeElement).pipe(tap(() => item.setOffset()))),
115✔
291
                    ...(this.routers || []).map(router => router?.isActiveChange)
115✔
292
                )
2✔
293
                    .pipe(
294
                        takeUntilDestroyed(this.destroyRef),
115✔
295
                        tap(() => {
66✔
296
                            if (this.thyResponsive) {
66✔
297
                                this.resetSizes();
298
                                this.setHiddenItems();
299
                                this.calculateMoreIsActive();
300
                            }
82✔
301

82✔
302
                            if (this.type === 'card') {
74✔
303
                                this.setNavItemDivider();
304
                            }
305
                        })
306
                    )
49!
307
                    .subscribe(() => {
49✔
308
                        this.alignInkBarToSelectedTab();
309
                    });
310
            });
1✔
311
        });
312
    }
313

314
    ngAfterContentInit(): void {
315
        if (this.thyResponsive) {
316
            this.ngZone.onStable.pipe(take(1)).subscribe(() => {
317
                this.resetSizes();
318
            });
319
        }
320
    }
321

322
    ngAfterContentChecked() {
323
        this.calculateMoreIsActive();
324

325
        this.curActiveIndex = this.links && this.links.length ? this.links.toArray().findIndex(item => item.linkIsActive()) : -1;
326
        if (this.curActiveIndex < 0) {
327
            this.inkBar.hide();
328
        } else if (this.curActiveIndex !== this.prevActiveIndex) {
329
            this.alignInkBarToSelectedTab();
1✔
330
        }
331
    }
332

333
    private setMoreBtnOffset() {
334
        this.moreBtnOffset = {
335
            height: this.defaultMoreOperation?.nativeElement?.offsetHeight,
336
            width: this.defaultMoreOperation?.nativeElement?.offsetWidth
337
        };
338
    }
339

340
    private setNavItemDivider() {
341
        const tabs = this.links.toArray();
342
        const activeIndex = tabs.findIndex(item => item.linkIsActive());
343

344
        for (let i = 0; i < tabs.length; i++) {
345
            if ((i !== activeIndex && i !== activeIndex - 1 && i !== tabs.length - 1) || (i === activeIndex - 1 && this.moreActive)) {
346
                tabs[i].addClass('has-right-divider');
347
            } else {
348
                tabs[i].removeClass('has-right-divider');
349
            }
350
        }
351
    }
352

353
    createResizeObserver(element: HTMLElement) {
354
        return typeof ResizeObserver === 'undefined'
355
            ? of(null)
356
            : new Observable(observer => {
357
                  const resize = new ResizeObserver(entries => {
358
                      observer.next(entries);
359
                  });
360
                  resize.observe(element);
361
                  return () => {
362
                      resize.disconnect();
363
                  };
364
              });
365
    }
366

367
    private calculateMoreIsActive() {
368
        this.moreActive = this.hiddenItems.some(item => {
369
            return item.linkIsActive();
370
        });
371
        this.changeDetectorRef.detectChanges();
372
    }
373

374
    private setHiddenItems() {
375
        this.moreActive = false;
376
        const tabs = this.links.toArray();
377
        if (!tabs.length) {
378
            this.hiddenItems = [];
379
            this.showMore = this.hiddenItems.length > 0;
380
            return;
381
        }
382

383
        const endIndex = this.thyVertical ? this.getShowItemsEndIndexWhenVertical(tabs) : this.getShowItemsEndIndexWhenHorizontal(tabs);
384

385
        const showItems = tabs.slice(0, endIndex + 1);
386
        (showItems || []).forEach(item => {
387
            item.setNavLinkHidden(false);
388
        });
389

390
        this.hiddenItems = endIndex === tabs.length - 1 ? [] : tabs.slice(endIndex + 1);
391
        (this.hiddenItems || []).forEach(item => {
392
            item.setNavLinkHidden(true);
393
        });
394

395
        this.showMore = this.hiddenItems.length > 0;
396
        this.initialized = true;
397
    }
398

399
    private getShowItemsEndIndexWhenHorizontal(tabs: ThyNavItemDirective[]) {
400
        const tabsLength = tabs.length;
401
        let endIndex = tabsLength;
402
        let totalWidth = 0;
403

404
        for (let i = 0; i < tabsLength; i += 1) {
405
            const _totalWidth = i === tabsLength - 1 ? totalWidth + tabs[i].offset.width : totalWidth + tabs[i].offset.width + tabItemRight;
406
            if (_totalWidth > this.wrapperOffset.width) {
407
                let moreOperationWidth = this.moreBtnOffset.width;
408
                if (totalWidth + moreOperationWidth <= this.wrapperOffset.width) {
409
                    endIndex = i - 1;
410
                } else {
411
                    endIndex = i - 2;
412
                }
413
                break;
414
            } else {
415
                totalWidth = _totalWidth;
416
                endIndex = i;
417
            }
418
        }
419
        return endIndex;
420
    }
421

422
    private getShowItemsEndIndexWhenVertical(tabs: ThyNavItemDirective[]) {
423
        const tabsLength = tabs.length;
424
        let endIndex = tabsLength;
425
        let totalHeight = 0;
426
        for (let i = 0; i < tabsLength; i += 1) {
427
            const _totalHeight = totalHeight + tabs[i].offset.height;
428
            if (_totalHeight > this.wrapperOffset.height) {
429
                let moreOperationHeight = this.moreBtnOffset.height;
430
                if (totalHeight + moreOperationHeight <= this.wrapperOffset.height) {
431
                    endIndex = i - 1;
432
                } else {
433
                    endIndex = i - 2;
434
                }
435
                break;
436
            } else {
437
                totalHeight = _totalHeight;
438
                endIndex = i;
439
            }
440
        }
441
        return endIndex;
442
    }
443

444
    private resetSizes() {
445
        this.wrapperOffset = {
446
            height: this.elementRef.nativeElement.offsetHeight || 0,
447
            width: this.elementRef.nativeElement.offsetWidth || 0,
448
            left: this.elementRef.nativeElement.offsetLeft || 0,
449
            top: this.elementRef.nativeElement.offsetTop || 0
450
        };
451
    }
452

453
    openMoreMenu(event: Event, template: TemplateRef<any>) {
454
        this.popover.open(
455
            template,
456
            Object.assign(
457
                {
458
                    origin: event.currentTarget as HTMLElement,
459
                    hasBackdrop: true,
460
                    backdropClosable: true,
461
                    insideClosable: true,
462
                    placement: 'bottom' as ThyPlacement,
463
                    panelClass: 'thy-nav-list-popover',
464
                    originActiveClass: 'thy-nav-origin-active'
465
                },
466
                this.thyPopoverOptions() ? this.thyPopoverOptions() : {}
467
            )
468
        );
469
    }
470

471
    navItemClick(item: ThyNavItemDirective) {
472
        item.elementRef.nativeElement.click();
473
    }
474

475
    private alignInkBarToSelectedTab(): void {
476
        if (!this.showInkBar) {
477
            this.inkBar.hide();
478
            return;
479
        }
480
        const tabs = this.links?.toArray() ?? [];
481
        const selectedItem = tabs.find(item => item.linkIsActive());
482
        let selectedItemElement: HTMLElement = selectedItem && selectedItem.elementRef.nativeElement;
483

484
        if (selectedItem && this.moreActive) {
485
            selectedItemElement = this.defaultMoreOperation.nativeElement;
486
        }
487
        if (selectedItemElement) {
488
            this.prevActiveIndex = this.curActiveIndex;
489
            this.inkBar.alignToElement(selectedItemElement);
490
        }
491
    }
492

493
    ngOnChanges(changes: SimpleChanges): void {
494
        const { thyVertical, thyType } = changes;
495

496
        if (thyType?.currentValue !== thyType?.previousValue || thyVertical?.currentValue !== thyVertical?.previousValue) {
497
            this.alignInkBarToSelectedTab();
498
        }
499
    }
500

501
    ngOnDestroy() {
502
        if (this.navSubscription) {
503
            this.navSubscription.unsubscribe();
504
        }
505
    }
506
}
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