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

atinc / ngx-tethys / a9e8da9d-f09f-43dd-9a95-62c3596ea635

29 Oct 2024 06:11AM UTC coverage: 90.438% (-0.005%) from 90.443%
a9e8da9d-f09f-43dd-9a95-62c3596ea635

Pull #3223

circleci

pubuzhixing8
fix(thy-loading): thy-loading align vertical #TINFR-872
Pull Request #3223: fix(thy-loading): thy-loading align vertical #TINFR-872

5504 of 6730 branches covered (81.78%)

Branch coverage included in aggregate %.

13251 of 14008 relevant lines covered (94.6%)

991.65 hits per line

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

88.24
/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
    Inject,
10
    Input,
1✔
11
    NgZone,
12
    OnChanges,
13
    OnDestroy,
14
    Output,
15
    Renderer2,
1✔
16
    SimpleChanges,
17
    ViewChild,
11✔
18
    ViewEncapsulation,
11✔
19
    numberAttribute
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
    standalone: true,
70
    imports: [ThyAffix, NgTemplateOutlet, NgStyle, NgClass]
×
71
})
72
export class ThyAnchor implements OnDestroy, AfterViewInit, OnChanges {
73
    @ViewChild('ink') private ink!: ElementRef;
74

12✔
75
    /**
76
     * 固定模式
77
     */
5✔
78
    @Input({ transform: coerceBooleanProperty }) thyAffix = true;
1✔
79

80
    /**
4✔
81
     * 锚点区域边界,单位:px
4✔
82
     */
4!
83
    @Input({ transform: numberAttribute })
4✔
84
    thyBounds = 5;
12✔
85

12!
86
    /**
×
87
     * 缓冲的偏移量阈值
88
     */
12✔
89
    @Input({ transform: numberAttribute })
12✔
90
    thyOffsetTop?: number = undefined;
10✔
91

10✔
92
    /**
4✔
93
     * 指定滚动的容器
94
     * @type string | HTMLElement
95
     */
96
    @Input() thyContainer?: string | HTMLElement;
97

98
    /**
99
     * 设置导航方向
4✔
100
     * @type 'vertical' | 'horizontal'
4!
101
     */
×
102
    @Input() thyDirection: 'vertical' | 'horizontal' = 'vertical';
×
103

104
    /**
105
     * 点击项触发
4!
106
     */
4✔
107
    @Output() readonly thyClick = new EventEmitter<ThyAnchorLink>();
108

4✔
109
    /**
110
     * 滚动到某锚点时触发
111
     */
6✔
112
    @Output() readonly thyScroll = new EventEmitter<ThyAnchorLink>();
22✔
113

114
    visible = false;
115

116
    wrapperStyle = { 'max-height': '100vh' };
6✔
117

6✔
118
    container?: HTMLElement | Window;
6✔
119

6✔
120
    private links: ThyAnchorLink[] = [];
6✔
121

6✔
122
    private animating = false;
6✔
123

6✔
124
    private destroy$ = new Subject<void>();
6✔
125

6✔
126
    private handleScrollTimeoutID: any = -1;
6✔
127

128
    constructor(
129
        @Inject(DOCUMENT) private document: any,
10✔
130
        private cdr: ChangeDetectorRef,
10✔
131
        private platform: Platform,
10!
132
        private zone: NgZone,
10!
133
        private renderer: Renderer2,
10✔
134
        private scrollService: ThyScrollService
135
    ) {}
136

×
137
    registerLink(link: ThyAnchorLink): void {
138
        this.links.push(link);
139
    }
140

141
    unregisterLink(link: ThyAnchorLink): void {
3!
142
        this.links.splice(this.links.indexOf(link), 1);
3✔
143
    }
3✔
144

1✔
145
    private getContainer(): HTMLElement | Window {
146
        return this.container || window;
2✔
147
    }
2✔
148

2✔
149
    ngAfterViewInit(): void {
2!
150
        this.warningPrompt();
2✔
151
        this.registerScrollEvent();
2✔
152
    }
153

2✔
154
    ngOnDestroy(): void {
2✔
155
        clearTimeout(this.handleScrollTimeoutID);
156
        this.destroy$.next();
157
        this.destroy$.complete();
11✔
158
    }
11!
159

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

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

186
    handleScroll(): void {
187
        if (typeof document === 'undefined' || this.animating) {
188
            return;
1✔
189
        }
190
        const container: HTMLElement = this.container instanceof HTMLElement ? this.container : this.document;
191

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

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

222
    private clearActive(): void {
223
        this.links.forEach(i => {
224
            i.unsetActive();
225
        });
226
    }
227

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

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

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

255
    handleScrollTo(linkComponent: ThyAnchorLink): void {
256
        const container: HTMLElement = this.container instanceof HTMLElement ? this.container : this.document;
257
        const linkElement: HTMLElement = container.querySelector(linkComponent.thyHref);
258
        if (!linkElement) {
259
            return;
260
        }
261

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

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