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

atinc / ngx-tethys / e62d3b10-1466-49c3-aabd-707148681fc8

14 Jun 2024 08:24AM UTC coverage: 90.422%. Remained the same
e62d3b10-1466-49c3-aabd-707148681fc8

push

circleci

minlovehua
feat: use the ngx-tethys/util's coerceBooleanProperty instead of booleanAttribute #INFR-12648

5467 of 6692 branches covered (81.69%)

Branch coverage included in aggregate %.

117 of 120 new or added lines in 66 files covered. (97.5%)

183 existing lines in 46 files now uncovered.

13216 of 13970 relevant lines covered (94.6%)

985.91 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
    ChangeDetectionStrategy,
11
    ChangeDetectorRef,
12
    Component,
13
    ContentChild,
14
    ContentChildren,
15
    DestroyRef,
16
    ElementRef,
17
    HostBinding,
1✔
18
    inject,
19
    Input,
20
    NgZone,
21
    OnChanges,
22
    OnInit,
23
    QueryList,
24
    SimpleChanges,
25
    TemplateRef,
26
    ViewChild
27
} from '@angular/core';
28

1✔
29
import { RouterLinkActive } from '@angular/router';
30
import { ThyNavInkBarDirective } from './nav-ink-bar.directive';
31
import { ThyNavItemDirective } from './nav-item.directive';
32
import { BypassSecurityTrustHtmlPipe } from './nav.pipe';
33
import { ThyDropdownMenuComponent, ThyDropdownMenuItemDirective, ThyDropdownMenuItemActiveDirective } from 'ngx-tethys/dropdown';
1✔
34
import { ThyIcon } from 'ngx-tethys/icon';
35
import { NgClass, NgTemplateOutlet, NgIf, NgFor } from '@angular/common';
36
import { coerceBooleanProperty } from 'ngx-tethys/util';
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',
56✔
57
    sm: 'thy-nav-sm'
56✔
58
};
59

60
const tabItemRight = 20;
658✔
61

62
/**
63
 * 导航组件
280✔
64
 * @name thy-nav
280✔
65
 * @order 10
66
 */
67
@Component({
77✔
68
    selector: 'thy-nav',
77!
69
    templateUrl: './nav.component.html',
77✔
70
    host: {
71
        class: 'thy-nav'
77✔
72
    },
49✔
73
    changeDetection: ChangeDetectionStrategy.OnPush,
74
    standalone: true,
77✔
75
    imports: [
76
        NgClass,
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,
50✔
86
        BypassSecurityTrustHtmlPipe
87
    ]
88
})
89
export class ThyNav implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked, OnChanges {
90
    private readonly destroyRef = inject(DestroyRef);
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 } = {
50✔
98
        height: 0,
99
        width: 0,
100
        left: 0,
50✔
101
        top: 0
42✔
102
    };
103

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

106
    public moreActive: boolean;
50✔
107

8✔
108
    public showMore = true;
8✔
109

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

112
    private hostRenderer = useHostRenderer();
113

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

242
    private curActiveIndex: number;
243

244
    private prevActiveIndex: number = NaN;
2✔
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) {
255
            this.initialized = true;
1✔
256
        }
257

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

14✔
261
    ngAfterViewInit() {
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());
125✔
266
                this.setHiddenItems();
2✔
267
            });
268
        }
125✔
269
        this.ngZone.runOutsideAngular(() => {
74✔
270
            merge(
74✔
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))),
274
                ...(this.routers || []).map(router => router?.isActiveChange)
82✔
275
            )
82✔
276
                .pipe(
74✔
277
                    takeUntilDestroyed(this.destroyRef),
278
                    tap(() => {
279
                        if (this.thyResponsive) {
1✔
280
                            this.resetSizes();
281
                            this.setHiddenItems();
282
                            this.calculateMoreIsActive();
283
                        }
284
                    })
285
                )
1✔
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

303
        this.curActiveIndex = this.links && this.links.length ? this.links.toArray().findIndex(item => item.linkIsActive()) : -1;
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