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

atinc / ngx-tethys / 2c11b3d7-fd65-411c-a4e3-dc774f8b7c23

02 Apr 2024 08:08AM UTC coverage: 90.55% (-0.04%) from 90.585%
2c11b3d7-fd65-411c-a4e3-dc774f8b7c23

Pull #3061

circleci

minlovehua
refactor(all): use takeUntilDestroyed instead of mixinUnsubscribe INFR-9529
Pull Request #3061: refactor(all): use takeUntilDestroyed instead of mixinUnsubscribe INFR-9529

5417 of 6635 branches covered (81.64%)

Branch coverage included in aggregate %.

52 of 55 new or added lines in 16 files covered. (94.55%)

54 existing lines in 9 files now uncovered.

13460 of 14212 relevant lines covered (94.71%)

979.65 hits per line

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

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

30
import { RouterLinkActive } from '@angular/router';
31
import { ThyNavInkBarDirective } from './nav-ink-bar.directive';
32
import { ThyNavItemDirective } from './nav-item.directive';
33
import { BypassSecurityTrustHtmlPipe } from './nav.pipe';
1✔
34
import { ThyDropdownMenuComponent, ThyDropdownMenuItemDirective, ThyDropdownMenuItemActiveDirective } from 'ngx-tethys/dropdown';
35
import { ThyIcon } from 'ngx-tethys/icon';
36
import { NgClass, NgTemplateOutlet, NgIf, NgFor } from '@angular/common';
37

38
export type ThyNavType = 'pulled' | 'tabs' | 'pills' | 'lite' | 'primary' | 'secondary' | 'thirdly' | 'secondary-divider';
39
export type ThyNavSize = 'lg' | 'md' | 'sm';
1✔
40
export type ThyNavHorizontal = '' | 'start' | 'center' | 'end';
41

72✔
42
const navTypeClassesMap = {
72✔
43
    pulled: ['thy-nav-pulled'],
22✔
44
    tabs: ['thy-nav-tabs'],
45
    pills: ['thy-nav-pills'],
46
    lite: ['thy-nav-lite'],
47
    //如下类型已经废弃
52✔
48
    primary: ['thy-nav-primary'],
52✔
49
    secondary: ['thy-nav-secondary'],
5✔
50
    thirdly: ['thy-nav-thirdly'],
51
    'secondary-divider': ['thy-nav-secondary-divider']
52
};
53

21!
54
const navSizeClassesMap = {
55
    lg: 'thy-nav-lg',
56
    md: 'thy-nav-md',
278✔
57
    sm: 'thy-nav-sm'
278✔
58
};
59

60
const tabItemRight = 20;
77✔
61

77!
62
/**
77✔
63
 * 导航组件
64
 * @name thy-nav
77✔
65
 * @order 10
49✔
66
 */
67
@Component({
77✔
68
    selector: 'thy-nav',
69
    templateUrl: './nav.component.html',
70
    host: {
50✔
71
        class: 'thy-nav'
50✔
72
    },
50✔
73
    changeDetection: ChangeDetectionStrategy.OnPush,
50✔
74
    standalone: true,
50✔
75
    imports: [
50✔
76
        NgClass,
50✔
77
        NgTemplateOutlet,
50✔
78
        NgIf,
50✔
79
        ThyNavItemDirective,
80
        ThyIcon,
81
        ThyNavInkBarDirective,
82
        ThyDropdownMenuComponent,
83
        NgFor,
84
        ThyDropdownMenuItemDirective,
50✔
85
        ThyDropdownMenuItemActiveDirective,
50✔
86
        BypassSecurityTrustHtmlPipe
50✔
87
    ]
50✔
88
})
50✔
89
export class ThyNav implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked, OnChanges {
50✔
90
    private readonly destroyRef = inject(DestroyRef);
50✔
91

92
    private type: ThyNavType = 'pulled';
93
    private size: ThyNavSize = 'md';
50✔
94
    public initialized = false;
42✔
95

96
    public horizontal: ThyNavHorizontal;
50✔
97
    public wrapperOffset: { height: number; width: number; left: number; top: number } = {
98
        height: 0,
99
        width: 0,
50✔
100
        left: 0,
8✔
101
        top: 0
8✔
102
    };
21✔
103

8✔
104
    public hiddenItems: ThyNavItemDirective[] = [];
105

106
    public moreActive: boolean;
50✔
107

140!
108
    public showMore = true;
109

10✔
110
    private moreBtnOffset: { height: number; width: number } = { height: 0, width: 0 };
2✔
111

2✔
112
    private hostRenderer = useHostRenderer();
2✔
113

114
    /**
115
     * 导航类型
116
     * @type pulled | tabs | pills | lite | primary | secondary | thirdly | secondary-divider
10✔
117
     * @default pulled
118
     */
119
    @Input()
120
    set thyType(type: ThyNavType) {
121
        this.type = type || 'pulled';
50✔
122
        if (this.initialized) {
8✔
123
            this.updateClasses();
8✔
124
        }
125
    }
126

127
    /**
128
     * 导航大小
139✔
129
     * @type lg | md | sm
215✔
130
     * @default md
139✔
131
     */
25✔
132
    @Input()
133
    set thySize(size: ThyNavSize) {
114✔
134
        this.size = size;
53✔
135
        if (this.initialized) {
136
            this.updateClasses();
137
        }
138
    }
8✔
139

140
    /**
141
     * 水平排列
142
     * @type '' | 'start' | 'center' | 'end'
143
     * @default false
144
     */
190!
145
    @Input()
146
    set thyHorizontal(horizontal: ThyNavHorizontal) {
147
        this.horizontal = (horizontal as string) === 'right' ? 'end' : horizontal;
190✔
UNCOV
148
    }
×
149

150
    /**
190✔
151
     * 是否垂直排列
190✔
152
     * @default false
190✔
153
     */
154
    @HostBinding('class.thy-nav--vertical')
155
    @Input()
156
    @InputBoolean()
157
    thyVertical: boolean;
141✔
158

42✔
159
    /**
160
     * 是否是填充模式
141✔
161
     */
162
    @HostBinding('class.thy-nav--fill')
163
    @Input()
10✔
164
    @InputBoolean()
10✔
165
    thyFill: boolean = false;
10✔
166

1✔
167
    /**
1✔
168
     * 是否响应式,自动计算宽度存放 thyNavItem,并添加更多弹框
1✔
169
     * @default false
170
     */
9✔
171
    @Input()
9✔
172
    @InputBoolean()
9!
173
    thyResponsive: boolean;
7✔
174

175
    /**
9!
176
     * 更多操作的菜单点击内部是否可关闭
9!
177
     */
21✔
178
    @Input()
179
    @InputBoolean()
9✔
180
    thyInsideClosable = true;
9✔
181

182
    /**
183
     * 右侧额外区域模板
8✔
184
     * @type TemplateRef
8✔
185
     */
8✔
186
    @Input() thyExtra: TemplateRef<unknown>;
8✔
187

21✔
188
    /**
21✔
189
     * @private
8✔
190
     */
8✔
191
    @ContentChildren(ThyNavItemDirective, { descendants: true }) links: QueryList<ThyNavItemDirective>;
1✔
192

193
    /**
194
     * @private
7✔
195
     */
196
    @ContentChildren(RouterLinkActive, { descendants: true }) routers: QueryList<RouterLinkActive>;
8✔
197

198
    /**
199
     * 响应式模式下更多操作模板
13✔
200
     * @type TemplateRef
13✔
201
     */
202
    @ContentChild('more') moreOperation: TemplateRef<unknown>;
203

8✔
204
    /**
205
     * 响应式模式下更多弹框模板
206
     * @type TemplateRef
1✔
207
     */
1✔
208
    @ContentChild('morePopover') morePopover: TemplateRef<unknown>;
1✔
209

1✔
210
    /**
3✔
211
     * 右侧额外区域模板,支持 thyExtra 传参和 <ng-template #extra></ng-template> 模板
3✔
212
     * @name extra
1✔
213
     * @type TemplateRef
1!
UNCOV
214
     */
×
215
    @ContentChild('extra') extra: TemplateRef<unknown>;
216

217
    @ViewChild('moreOperationContainer') defaultMoreOperation: ElementRef<HTMLAnchorElement>;
1✔
218

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

221
    get showInkBar(): boolean {
222
        const showTypes: ThyNavType[] = ['pulled', 'tabs'];
2✔
223
        return showTypes.includes(this.type);
2✔
224
    }
225

226
    private updateClasses() {
1✔
227
        let classNames: string[] = [];
228
        if (navTypeClassesMap[this.type]) {
229
            classNames = [...navTypeClassesMap[this.type]];
10✔
230
        }
10!
231
        if (navSizeClassesMap[this.size]) {
10!
232
            classNames.push(navSizeClassesMap[this.size]);
12✔
233
        }
12✔
234
        this.hostRenderer.updateClass(classNames);
235
    }
236

237
    private curActiveIndex: number;
2✔
238

239
    private prevActiveIndex: number = NaN;
240

241
    constructor(
242
        private elementRef: ElementRef,
243
        private ngZone: NgZone,
244
        private changeDetectorRef: ChangeDetectorRef,
245
        private popover: ThyPopover
246
    ) {}
247

248
    ngOnInit() {
1✔
249
        if (!this.thyResponsive) {
250
            this.initialized = true;
251
        }
137✔
252

14✔
253
        this.updateClasses();
14✔
254
    }
255

123✔
256
    ngAfterViewInit() {
123✔
257
        if (this.thyResponsive) {
123✔
258
            this.setMoreBtnOffset();
123✔
259
            this.ngZone.onStable.pipe(take(1)).subscribe(() => {
2✔
260
                this.links.toArray().forEach(link => link.setOffset());
261
                this.setHiddenItems();
123✔
262
            });
72✔
263
        }
72✔
264
        this.ngZone.runOutsideAngular(() => {
265
            merge(
266
                this.links.changes,
267
                this.createResizeObserver(this.elementRef.nativeElement).pipe(debounceTime(100)),
82✔
268
                ...this.links.map(item => this.createResizeObserver(item.elementRef.nativeElement).pipe(debounceTime(100))),
82✔
269
                ...(this.routers || []).map(router => router?.isActiveChange)
74✔
270
            )
271
                .pipe(
272
                    takeUntilDestroyed(this.destroyRef),
1✔
273
                    tap(() => {
274
                        if (this.thyResponsive) {
275
                            this.resetSizes();
276
                            this.setHiddenItems();
277
                            this.calculateMoreIsActive();
278
                        }
1✔
279
                    })
280
                )
281
                .subscribe(() => {
282
                    this.alignInkBarToSelectedTab();
283
                });
284
        });
285
    }
286

287
    ngAfterContentInit(): void {
288
        if (this.thyResponsive) {
289
            this.ngZone.onStable.pipe(take(1)).subscribe(() => {
290
                this.resetSizes();
291
            });
292
        }
293
    }
294

295
    ngAfterContentChecked() {
296
        this.calculateMoreIsActive();
1✔
297

298
        this.curActiveIndex = this.links && this.links.length ? this.links.toArray().findIndex(item => item.linkIsActive()) : -1;
299
        if (this.curActiveIndex < 0) {
300
            this.inkBar.hide();
1✔
301
        } else if (this.curActiveIndex !== this.prevActiveIndex) {
302
            this.alignInkBarToSelectedTab();
303
        }
304
    }
1✔
305

306
    private setMoreBtnOffset() {
307
        this.moreBtnOffset = {
308
            height: this.defaultMoreOperation?.nativeElement?.offsetHeight,
1✔
309
            width: this.defaultMoreOperation?.nativeElement?.offsetWidth
310
        };
311
    }
312

1✔
313
    createResizeObserver(element: HTMLElement) {
314
        return typeof ResizeObserver === 'undefined'
315
            ? of(null)
316
            : new Observable(observer => {
317
                  const resize = new ResizeObserver(entries => {
318
                      observer.next(entries);
319
                  });
320
                  resize.observe(element);
321
                  return () => {
322
                      resize.disconnect();
323
                  };
324
              });
325
    }
326

327
    private calculateMoreIsActive() {
328
        this.moreActive = this.hiddenItems.some(item => {
329
            return item.linkIsActive();
330
        });
331
        this.changeDetectorRef.detectChanges();
332
    }
333

334
    private setHiddenItems() {
335
        this.moreActive = false;
336
        const tabs = this.links.toArray();
337
        if (!tabs.length) {
338
            this.hiddenItems = [];
339
            this.showMore = this.hiddenItems.length > 0;
340
            return;
341
        }
342

343
        const endIndex = this.thyVertical ? this.getShowItemsEndIndexWhenVertical(tabs) : this.getShowItemsEndIndexWhenHorizontal(tabs);
344

345
        const showItems = tabs.slice(0, endIndex + 1);
346
        (showItems || []).forEach(item => {
347
            item.setNavLinkHidden(false);
348
        });
349

350
        this.hiddenItems = endIndex === tabs.length - 1 ? [] : tabs.slice(endIndex + 1);
351
        (this.hiddenItems || []).forEach(item => {
352
            item.setNavLinkHidden(true);
353
        });
354

355
        this.showMore = this.hiddenItems.length > 0;
356
        this.initialized = true;
357
    }
358

359
    private getShowItemsEndIndexWhenHorizontal(tabs: ThyNavItemDirective[]) {
360
        const tabsLength = tabs.length;
361
        let endIndex = tabsLength;
362
        let totalWidth = 0;
363

364
        for (let i = 0; i < tabsLength; i += 1) {
365
            const _totalWidth = i === tabsLength - 1 ? totalWidth + tabs[i].offset.width : totalWidth + tabs[i].offset.width + tabItemRight;
366
            if (_totalWidth > this.wrapperOffset.width) {
367
                let moreOperationWidth = this.moreBtnOffset.width;
368
                if (totalWidth + moreOperationWidth <= this.wrapperOffset.width) {
369
                    endIndex = i - 1;
370
                } else {
371
                    endIndex = i - 2;
372
                }
373
                break;
374
            } else {
375
                totalWidth = _totalWidth;
376
                endIndex = i;
377
            }
378
        }
379
        return endIndex;
380
    }
381

382
    private getShowItemsEndIndexWhenVertical(tabs: ThyNavItemDirective[]) {
383
        const tabsLength = tabs.length;
384
        let endIndex = tabsLength;
385
        let totalHeight = 0;
386
        for (let i = 0; i < tabsLength; i += 1) {
387
            const _totalHeight = totalHeight + tabs[i].offset.height;
388
            if (_totalHeight > this.wrapperOffset.height) {
389
                let moreOperationHeight = this.moreBtnOffset.height;
390
                if (totalHeight + moreOperationHeight <= this.wrapperOffset.height) {
391
                    endIndex = i - 1;
392
                } else {
393
                    endIndex = i - 2;
394
                }
395
                break;
396
            } else {
397
                totalHeight = _totalHeight;
398
                endIndex = i;
399
            }
400
        }
401
        return endIndex;
402
    }
403

404
    private resetSizes() {
405
        this.wrapperOffset = {
406
            height: this.elementRef.nativeElement.offsetHeight || 0,
407
            width: this.elementRef.nativeElement.offsetWidth || 0,
408
            left: this.elementRef.nativeElement.offsetLeft || 0,
409
            top: this.elementRef.nativeElement.offsetTop || 0
410
        };
411
    }
412

413
    openMore(event: Event, template: TemplateRef<any>) {
414
        this.popover.open(template, {
415
            origin: event.currentTarget as HTMLElement,
416
            hasBackdrop: true,
417
            backdropClosable: true,
418
            insideClosable: this.thyInsideClosable,
419
            placement: 'bottom',
420
            panelClass: 'thy-nav-list-popover',
421
            originActiveClass: 'thy-nav-origin-active'
422
        });
423
    }
424

425
    navItemClick(item: ThyNavItemDirective) {
426
        item.elementRef.nativeElement.click();
427
    }
428

429
    private alignInkBarToSelectedTab(): void {
430
        if (!this.showInkBar) {
431
            this.inkBar.hide();
432
            return;
433
        }
434
        const tabs = this.links?.toArray() ?? [];
435
        const selectedItem = tabs.find(item => item.linkIsActive());
436
        let selectedItemElement: HTMLElement = selectedItem && selectedItem.elementRef.nativeElement;
437

438
        if (selectedItem && this.moreActive) {
439
            selectedItemElement = this.defaultMoreOperation.nativeElement;
440
        }
441
        if (selectedItemElement) {
442
            this.prevActiveIndex = this.curActiveIndex;
443
            this.inkBar.alignToElement(selectedItemElement);
444
        }
445
    }
446

447
    ngOnChanges(changes: SimpleChanges): void {
448
        const { thyVertical, thyType } = changes;
449

450
        if (thyType?.currentValue !== thyType?.previousValue || thyVertical?.currentValue !== thyVertical?.previousValue) {
451
            this.alignInkBarToSelectedTab();
452
        }
453
    }
454
}
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