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

atinc / ngx-tethys / d1685753-acee-43ae-9066-ce71b1b78f96

13 Jun 2024 02:32AM UTC coverage: 90.422% (+0.001%) from 90.421%
d1685753-acee-43ae-9066-ce71b1b78f96

Pull #3102

circleci

yxb941006
fix(nav): #INFR-12632 fix prevActiveIndex not reset when links are changed
Pull Request #3102: fix(nav): #INFR-12632 fix prevActiveIndex not reset when links are ch…

5467 of 6692 branches covered (81.69%)

Branch coverage included in aggregate %.

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

2 existing lines in 1 file now uncovered.

13216 of 13970 relevant lines covered (94.6%)

984.13 hits per line

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

94.31
/src/nav/nav.component.ts
1
import { ThyPopover } from 'ngx-tethys/popover';
2
import { merge, Observable, of } from 'rxjs';
3
import { debounceTime, 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
    booleanAttribute,
11
    ChangeDetectionStrategy,
12
    ChangeDetectorRef,
13
    Component,
14
    ContentChild,
15
    ContentChildren,
16
    DestroyRef,
1✔
17
    ElementRef,
18
    HostBinding,
19
    inject,
20
    Input,
21
    NgZone,
22
    OnChanges,
23
    OnInit,
24
    QueryList,
25
    SimpleChanges,
26
    TemplateRef,
27
    ViewChild
1✔
28
} from '@angular/core';
29

30
import { RouterLinkActive } from '@angular/router';
31
import { ThyNavInkBarDirective } from './nav-ink-bar.directive';
32
import { ThyNavItemDirective } from './nav-item.directive';
1✔
33
import { BypassSecurityTrustHtmlPipe } from './nav.pipe';
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';
1✔
39
export type ThyNavSize = 'lg' | 'md' | 'sm';
40
export type ThyNavHorizontal = '' | 'start' | 'center' | 'end';
72✔
41

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

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

658✔
60
const tabItemRight = 20;
61

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

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

50✔
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,
42✔
101
        top: 0
102
    };
50✔
103

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

50✔
106
    public moreActive: boolean;
8✔
107

8✔
108
    public showMore = true;
21✔
109

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

112
    private hostRenderer = useHostRenderer();
50✔
113

140!
114
    private innerLinks: QueryList<ThyNavItemDirective>;
115

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

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

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

152
    /**
153
     * 是否垂直排列
190✔
UNCOV
154
     * @default false
×
155
     */
156
    @HostBinding('class.thy-nav--vertical')
190✔
157
    @Input({ transform: booleanAttribute })
190✔
158
    thyVertical: boolean;
190✔
159

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

141✔
167
    /**
168
     * 是否响应式,自动计算宽度存放 thyNavItem,并添加更多弹框
169
     * @default false
10✔
170
     */
10✔
171
    @Input({ transform: booleanAttribute })
10✔
172
    thyResponsive: boolean;
1✔
173

1✔
174
    /**
1✔
175
     * 更多操作的菜单点击内部是否可关闭
176
     */
9✔
177
    @Input({ transform: booleanAttribute })
9✔
178
    thyInsideClosable = true;
9!
179

7✔
180
    /**
181
     * 右侧额外区域模板
9!
182
     * @type TemplateRef
9!
183
     */
21✔
184
    @Input() thyExtra: TemplateRef<unknown>;
185

9✔
186
    /**
9✔
187
     * @private
188
     */
189
    @ContentChildren(ThyNavItemDirective, { descendants: true })
8✔
190
    set links(value) {
8✔
191
        this.innerLinks = value;
8✔
192
        this.prevActiveIndex = NaN;
8✔
193
    }
21✔
194
    get links(): QueryList<ThyNavItemDirective> {
21✔
195
        return this.innerLinks;
8✔
196
    }
8✔
197

1✔
198
    /**
199
     * @private
200
     */
7✔
201
    @ContentChildren(RouterLinkActive, { descendants: true }) routers: QueryList<RouterLinkActive>;
202

8✔
203
    /**
204
     * 响应式模式下更多操作模板
205
     * @type TemplateRef
13✔
206
     */
13✔
207
    @ContentChild('more') moreOperation: TemplateRef<unknown>;
208

209
    /**
8✔
210
     * 响应式模式下更多弹框模板
211
     * @type TemplateRef
212
     */
1✔
213
    @ContentChild('morePopover') morePopover: TemplateRef<unknown>;
1✔
214

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

222
    @ViewChild('moreOperationContainer') defaultMoreOperation: ElementRef<HTMLAnchorElement>;
223

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

1✔
226
    get showInkBar(): boolean {
227
        const showTypes: ThyNavType[] = ['pulled', 'tabs'];
228
        return showTypes.includes(this.type);
2✔
229
    }
2✔
230

231
    private updateClasses() {
232
        let classNames: string[] = [];
1✔
233
        if (navTypeClassesMap[this.type]) {
234
            classNames = [...navTypeClassesMap[this.type]];
235
        }
10✔
236
        if (navSizeClassesMap[this.size]) {
10!
237
            classNames.push(navSizeClassesMap[this.size]);
10!
238
        }
12✔
239
        this.hostRenderer.updateClass(classNames);
12✔
240
    }
241

242
    private curActiveIndex: number;
243

2✔
244
    private prevActiveIndex: number = NaN;
245

246
    constructor(
247
        private elementRef: ElementRef,
248
        private ngZone: NgZone,
249
        private changeDetectorRef: ChangeDetectorRef,
250
        private popover: ThyPopover
251
    ) {}
252

253
    ngOnInit() {
254
        if (!this.thyResponsive) {
1✔
255
            this.initialized = true;
256
        }
257

139✔
258
        this.updateClasses();
14✔
259
    }
14✔
260

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

292
    ngAfterContentInit(): void {
293
        if (this.thyResponsive) {
294
            this.ngZone.onStable.pipe(take(1)).subscribe(() => {
295
                this.resetSizes();
296
            });
297
        }
298
    }
299

300
    ngAfterContentChecked() {
301
        this.calculateMoreIsActive();
302

1✔
303
        this.curActiveIndex = this.links && this.links.length ? this.links.toArray().findIndex(item => item.linkIsActive()) : -1;
304
        if (this.curActiveIndex < 0) {
305
            this.inkBar.hide();
306
        } else if (this.curActiveIndex !== this.prevActiveIndex) {
307
            this.alignInkBarToSelectedTab();
308
        }
309
    }
310

311
    private setMoreBtnOffset() {
312
        this.moreBtnOffset = {
313
            height: this.defaultMoreOperation?.nativeElement?.offsetHeight,
314
            width: this.defaultMoreOperation?.nativeElement?.offsetWidth
315
        };
316
    }
317

318
    createResizeObserver(element: HTMLElement) {
319
        return typeof ResizeObserver === 'undefined'
320
            ? of(null)
321
            : new Observable(observer => {
322
                  const resize = new ResizeObserver(entries => {
323
                      observer.next(entries);
324
                  });
325
                  resize.observe(element);
326
                  return () => {
327
                      resize.disconnect();
328
                  };
329
              });
330
    }
331

332
    private calculateMoreIsActive() {
333
        this.moreActive = this.hiddenItems.some(item => {
334
            return item.linkIsActive();
335
        });
336
        this.changeDetectorRef.detectChanges();
337
    }
338

339
    private setHiddenItems() {
340
        this.moreActive = false;
341
        const tabs = this.links.toArray();
342
        if (!tabs.length) {
343
            this.hiddenItems = [];
344
            this.showMore = this.hiddenItems.length > 0;
345
            return;
346
        }
347

348
        const endIndex = this.thyVertical ? this.getShowItemsEndIndexWhenVertical(tabs) : this.getShowItemsEndIndexWhenHorizontal(tabs);
349

350
        const showItems = tabs.slice(0, endIndex + 1);
351
        (showItems || []).forEach(item => {
352
            item.setNavLinkHidden(false);
353
        });
354

355
        this.hiddenItems = endIndex === tabs.length - 1 ? [] : tabs.slice(endIndex + 1);
356
        (this.hiddenItems || []).forEach(item => {
357
            item.setNavLinkHidden(true);
358
        });
359

360
        this.showMore = this.hiddenItems.length > 0;
361
        this.initialized = true;
362
    }
363

364
    private getShowItemsEndIndexWhenHorizontal(tabs: ThyNavItemDirective[]) {
365
        const tabsLength = tabs.length;
366
        let endIndex = tabsLength;
367
        let totalWidth = 0;
368

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

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

409
    private resetSizes() {
410
        this.wrapperOffset = {
411
            height: this.elementRef.nativeElement.offsetHeight || 0,
412
            width: this.elementRef.nativeElement.offsetWidth || 0,
413
            left: this.elementRef.nativeElement.offsetLeft || 0,
414
            top: this.elementRef.nativeElement.offsetTop || 0
415
        };
416
    }
417

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

430
    navItemClick(item: ThyNavItemDirective) {
431
        item.elementRef.nativeElement.click();
432
    }
433

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

443
        if (selectedItem && this.moreActive) {
444
            selectedItemElement = this.defaultMoreOperation.nativeElement;
445
        }
446
        if (selectedItemElement) {
447
            this.prevActiveIndex = this.curActiveIndex;
448
            this.inkBar.alignToElement(selectedItemElement);
449
        }
450
    }
451

452
    ngOnChanges(changes: SimpleChanges): void {
453
        const { thyVertical, thyType } = changes;
454

455
        if (thyType?.currentValue !== thyType?.previousValue || thyVertical?.currentValue !== thyVertical?.previousValue) {
456
            this.alignInkBarToSelectedTab();
457
        }
458
    }
459
}
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