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

atinc / ngx-tethys / b594ea18-fa77-46ee-b644-2281b1565db3

14 Apr 2025 03:08AM UTC coverage: 90.228% (-0.008%) from 90.236%
b594ea18-fa77-46ee-b644-2281b1565db3

Pull #3331

circleci

xinglu01
fix(util): code review
Pull Request #3331: fix(util): handle i18n and tinyDate set default locale

5602 of 6871 branches covered (81.53%)

Branch coverage included in aggregate %.

9 of 9 new or added lines in 3 files covered. (100.0%)

10 existing lines in 2 files now uncovered.

13363 of 14148 relevant lines covered (94.45%)

995.66 hits per line

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

88.16
/src/anchor/anchor.component.ts
1
import { Platform } from '@angular/cdk/platform';
2
import {
3
    AfterViewInit,
4
    ChangeDetectionStrategy,
5
    ChangeDetectorRef,
6
    Component,
7
    ElementRef,
8
    EventEmitter,
9
    Input,
10
    NgZone,
1✔
11
    OnChanges,
12
    OnDestroy,
13
    Output,
14
    Renderer2,
15
    SimpleChanges,
1✔
16
    ViewChild,
17
    ViewEncapsulation,
11✔
18
    numberAttribute,
11✔
19
    inject
11✔
20
} from '@angular/core';
11✔
21
import { Subject, fromEvent } from 'rxjs';
11✔
22
import { takeUntil, throttleTime } from 'rxjs/operators';
11✔
23

11✔
24
import { DOCUMENT, NgClass, NgStyle, NgTemplateOutlet } from '@angular/common';
11✔
25
import { ThyAffix } from 'ngx-tethys/affix';
11✔
26
import { ThyScrollService } from 'ngx-tethys/core';
11✔
27
import { coerceBooleanProperty, getOffset } from 'ngx-tethys/util';
11✔
28
import { ThyAnchorLink } from './anchor-link.component';
11✔
29

11✔
30
interface Section {
11✔
31
    linkComponent: ThyAnchorLink;
11✔
32
    top: number;
11✔
33
}
11✔
34

11✔
35
const sharpMatcherRegx = /#([^#]+)$/;
36

37
/**
48✔
38
 * 锚点组件
39
 * @name thy-anchor
40
 */
48✔
41
@Component({
42
    selector: 'thy-anchor',
43
    exportAs: 'thyAnchor',
28✔
44
    preserveWhitespaces: false,
45
    template: `
46
        @if (thyAffix) {
11✔
47
            <thy-affix [thyOffsetTop]="thyOffsetTop" [thyContainer]="container">
11✔
48
                <ng-template [ngTemplateOutlet]="content"></ng-template>
49
            </thy-affix>
50
        } @else {
11✔
51
            <ng-template [ngTemplateOutlet]="content"></ng-template>
11✔
52
        }
11✔
53
        <ng-template #content>
54
            <div
55
                class="thy-anchor-wrapper"
11✔
56
                [ngClass]="{ 'thy-anchor-wrapper-horizontal': thyDirection === 'horizontal' }"
25✔
57
                [ngStyle]="wrapperStyle">
5✔
58
                <div class="thy-anchor">
1✔
59
                    <div class="thy-anchor-ink">
60
                        <div class="thy-anchor-ink-full" #ink></div>
61
                    </div>
62
                    <ng-content></ng-content>
63
                </div>
12!
64
            </div>
×
65
        </ng-template>
66
    `,
12✔
67
    encapsulation: ViewEncapsulation.None,
12✔
68
    changeDetection: ChangeDetectionStrategy.OnPush,
12✔
69
    imports: [ThyAffix, NgTemplateOutlet, NgStyle, NgClass]
UNCOV
70
})
×
71
export class ThyAnchor implements OnDestroy, AfterViewInit, OnChanges {
72
    private document = inject(DOCUMENT);
73
    private cdr = inject(ChangeDetectorRef);
74
    private platform = inject(Platform);
12✔
75
    private zone = inject(NgZone);
76
    private renderer = inject(Renderer2);
77
    private scrollService = inject(ThyScrollService);
5✔
78

1✔
79
    @ViewChild('ink') private ink!: ElementRef;
80

4✔
81
    /**
4✔
82
     * 固定模式
4!
83
     */
4✔
84
    @Input({ transform: coerceBooleanProperty }) thyAffix = true;
12✔
85

12!
86
    /**
×
87
     * 锚点区域边界,单位:px
88
     */
12✔
89
    @Input({ transform: numberAttribute })
12✔
90
    thyBounds = 5;
10✔
91

10✔
92
    /**
4✔
93
     * 缓冲的偏移量阈值
94
     */
95
    @Input({ transform: numberAttribute })
96
    thyOffsetTop?: number = undefined;
97

98
    /**
99
     * 指定滚动的容器
4✔
100
     * @type string | HTMLElement
4!
101
     */
×
102
    @Input() thyContainer?: string | HTMLElement;
×
103

104
    /**
105
     * 设置导航方向
4!
106
     * @type 'vertical' | 'horizontal'
4✔
107
     */
108
    @Input() thyDirection: 'vertical' | 'horizontal' = 'vertical';
4✔
109

110
    /**
111
     * 点击项触发
6✔
112
     */
22✔
113
    @Output() readonly thyClick = new EventEmitter<ThyAnchorLink>();
114

115
    /**
116
     * 滚动到某锚点时触发
6✔
117
     */
6✔
118
    @Output() readonly thyScroll = new EventEmitter<ThyAnchorLink>();
6✔
119

6✔
120
    visible = false;
6✔
121

6✔
122
    wrapperStyle = { 'max-height': '100vh' };
6✔
123

6✔
124
    container?: HTMLElement | Window;
6✔
125

6✔
126
    private links: ThyAnchorLink[] = [];
6✔
127

128
    private animating = false;
129

10✔
130
    private destroy$ = new Subject<void>();
10✔
131

10!
132
    private handleScrollTimeoutID: any = -1;
10!
133

10✔
134
    registerLink(link: ThyAnchorLink): void {
135
        this.links.push(link);
136
    }
×
137

138
    unregisterLink(link: ThyAnchorLink): void {
139
        this.links.splice(this.links.indexOf(link), 1);
140
    }
141

3!
142
    private getContainer(): HTMLElement | Window {
3✔
143
        return this.container || window;
3✔
144
    }
1✔
145

146
    ngAfterViewInit(): void {
2✔
147
        this.warningPrompt();
2✔
148
        this.registerScrollEvent();
2✔
149
    }
2!
150

2✔
151
    ngOnDestroy(): void {
2✔
152
        clearTimeout(this.handleScrollTimeoutID);
153
        this.destroy$.next();
2✔
154
        this.destroy$.complete();
2✔
155
    }
156

157
    private warningPrompt() {
11✔
158
        if (this.thyDirection === 'horizontal') {
11!
159
            const hasChildren = this.links.some(link =>
11✔
160
                Array.from(link?.elementRef?.nativeElement?.childNodes)?.some((item: HTMLElement) => item?.nodeName === 'THY-ANCHOR-LINK')
161
            );
162
            if (hasChildren) {
163
                console.warn("Anchor link nesting is not supported when 'Anchor' direction is horizontal.");
11✔
164
            }
1✔
165
        }
1!
166
    }
1✔
167

168
    private registerScrollEvent(): void {
169
        if (!this.platform.isBrowser) {
1✔
170
            return;
171
        }
172
        this.destroy$.next();
173
        this.zone.runOutsideAngular(() => {
174
            fromEvent(this.getContainer(), 'scroll', { passive: true })
175
                .pipe(throttleTime(50), takeUntil(this.destroy$))
176
                .subscribe(() => this.handleScroll());
177
        });
178
        // Browser would maintain the scrolling position when refreshing.
179
        // So we have to delay calculation in avoid of getting a incorrect result.
180
        this.handleScrollTimeoutID = setTimeout(() => this.handleScroll());
1✔
181
    }
182

183
    handleScroll(): void {
184
        if (typeof document === 'undefined' || this.animating) {
185
            return;
186
        }
187
        const container: HTMLElement = this.container instanceof HTMLElement ? this.container : (this.document as unknown as HTMLElement);
188

189
        const sections: Section[] = [];
190
        const scope = (this.thyOffsetTop || 0) + this.thyBounds;
191
        this.links.forEach(linkComponent => {
192
            const sharpLinkMatch = sharpMatcherRegx.exec(linkComponent.thyHref.toString());
193
            if (!sharpLinkMatch) {
194
                return;
195
            }
196
            const target = container.querySelector(`#${sharpLinkMatch[1]}`) as HTMLElement;
197
            if (target) {
198
                const top = getOffset(target, this.getContainer()).top;
199
                if (top < scope) {
200
                    sections.push({
201
                        top,
202
                        linkComponent
203
                    });
204
                }
205
            }
206
        });
207

208
        this.visible = !!sections.length;
209
        if (!this.visible) {
210
            this.clearActive();
211
            this.cdr.detectChanges();
212
        } else {
213
            const maxSection = sections.reduce((prev, curr) => (curr.top > prev.top ? curr : prev));
214
            this.handleActive(maxSection.linkComponent);
215
        }
216
        this.setVisible();
217
    }
218

219
    private clearActive(): void {
220
        this.links.forEach(i => {
221
            i.unsetActive();
222
        });
223
    }
224

225
    private handleActive(linkComponent: ThyAnchorLink): void {
226
        this.clearActive();
227
        linkComponent.setActive();
228
        const linkNode = linkComponent.getLinkTitleElement();
229
        const horizontalAnchor = this.thyDirection === 'horizontal';
230

231
        this.ink.nativeElement.style.top = horizontalAnchor ? '' : `${linkNode.offsetTop}px`;
232
        this.ink.nativeElement.style.height = horizontalAnchor ? '' : `${linkNode.clientHeight}px`;
233
        this.ink.nativeElement.style.left = horizontalAnchor ? `${linkNode.offsetLeft}px` : '';
234
        this.ink.nativeElement.style.width = horizontalAnchor ? `${linkNode.clientWidth}px` : '';
235
        this.visible = true;
236
        this.setVisible();
237
        this.thyScroll.emit(linkComponent);
238
    }
239

240
    private setVisible(): void {
241
        const visible = this.visible;
242
        const visibleClassname = 'visible';
243
        if (this.ink) {
244
            if (visible) {
245
                this.renderer.addClass(this.ink.nativeElement, visibleClassname);
246
            } else {
247
                this.renderer.removeClass(this.ink.nativeElement, visibleClassname);
248
            }
249
        }
250
    }
251

252
    handleScrollTo(linkComponent: ThyAnchorLink): void {
253
        const container: HTMLElement = this.container instanceof HTMLElement ? this.container : (this.document as unknown as HTMLElement);
254
        const linkElement: HTMLElement = container.querySelector(linkComponent.thyHref);
255
        if (!linkElement) {
256
            return;
257
        }
258

259
        this.animating = true;
260
        const containerScrollTop = this.scrollService.getScroll(this.getContainer());
261
        const elementOffsetTop = getOffset(linkElement, this.getContainer()).top;
262
        const targetScrollTop = containerScrollTop + elementOffsetTop - (this.thyOffsetTop || 0);
263
        this.scrollService.scrollTo(this.getContainer(), targetScrollTop, undefined, () => {
264
            this.animating = false;
265
        });
266
        this.handleActive(linkComponent);
267
        this.thyClick.emit(linkComponent);
268
    }
269

270
    ngOnChanges(changes: SimpleChanges): void {
271
        const { thyOffsetTop, thyContainer } = changes;
272
        if (thyOffsetTop) {
273
            this.wrapperStyle = {
274
                'max-height': `calc(100vh - ${this.thyOffsetTop}px)`
275
            };
276
        }
277
        if (thyContainer && this.thyContainer) {
278
            const container = this.thyContainer;
279
            this.container = typeof container === 'string' ? (this.document.querySelector(container) as HTMLElement) : container;
280
            this.registerScrollEvent();
281
        }
282
    }
283
}
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