Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions e2e/scroll.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { expect, test } from '@playwright/test';

test('scrolls to top when changing routes', async ({ page }) => {
await page.goto('/');
await expect(page.locator('app-root')).toBeVisible({ timeout: 15000 });

await page.addStyleTag({
content: 'html, body, main { min-height: 4000px !important; }',
});
await page.evaluate(() => {
const y = Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight
);
window.scrollTo(0, y);
document.documentElement.scrollTop = y;
document.body.scrollTop = y;
});

const scrolled = await page.evaluate(
() =>
window.scrollY ||
document.documentElement.scrollTop ||
document.body.scrollTop
);
expect(scrolled).toBeGreaterThan(100);

await page.locator('.desktop-navigation a[title="About us"]').click();
await expect(page).toHaveURL(/\/about-us$/);
await expect(page.locator('mat-card-title[title="About us"]')).toBeVisible({
timeout: 15000,
});

await expect
.poll(
async () =>
page.evaluate(
() =>
window.scrollY ||
document.documentElement.scrollTop ||
document.body.scrollTop
)
)
.toBe(0);
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"homepage": "https://github.com/Ditectrev/ditectrev.com",
"name": "ditectrev",
"url": "https://ditectrev.com",
"version": "2.1.0",
"version": "2.1.1",
"packageManager": "pnpm@9.15.0",
"scripts": {
"prepare:browser-env": "node ./generate-browser-env.mjs",
Expand Down
24 changes: 23 additions & 1 deletion src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import 'hammerjs';
import { Component } from '@angular/core';
import { AppComponent } from './app.component';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Meta, Title } from '@angular/platform-browser';
import { HomeModule } from './home/home.module';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';

@Component({ standalone: true, template: '' })
class BlankStubComponent {}

describe('AppComponent', () => {
let app: AppComponent;
let fixture: ComponentFixture<AppComponent>;
Expand All @@ -18,7 +23,10 @@ describe('AppComponent', () => {
BrowserAnimationsModule,
HomeModule,
HttpClientTestingModule,
RouterTestingModule,
RouterTestingModule.withRoutes([
{ path: '', component: BlankStubComponent },
{ path: 'about-us', component: BlankStubComponent },
]),
],
providers: [Title, Meta]
}).compileComponents();
Expand Down Expand Up @@ -57,4 +65,18 @@ describe('AppComponent', () => {
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('app-footer')).not.toBeNull();
});

it('should scroll the viewport to the top after navigation', async () => {
const router = TestBed.inject(Router);
const scrollToSpy = spyOn(window, 'scrollTo');
document.documentElement.scrollTop = 800;
document.body.scrollTop = 800;

await fixture.ngZone!.run(() => router.navigateByUrl('/about-us'));
await fixture.whenStable();

expect(scrollToSpy).toHaveBeenCalledWith(0, 0);
expect(document.documentElement.scrollTop).toBe(0);
expect(document.body.scrollTop).toBe(0);
});
});
15 changes: 14 additions & 1 deletion src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { animate, style, transition, trigger } from '@angular/animations';
import { Component, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Component, PLATFORM_ID, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router, RouterOutlet } from '@angular/router';
import { filter } from 'rxjs/operators';
Expand Down Expand Up @@ -31,6 +32,7 @@ const FADE_ANIMATION =
export class AppComponent {
private readonly router = inject(Router);
private readonly seoService = inject(SeoService);
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));

constructor() {
this.router.events
Expand All @@ -40,9 +42,20 @@ export class AppComponent {
)
.subscribe((event) => {
this.seoService.updateForUrl(event.urlAfterRedirects);
this.scrollToTop();
});
}

/** html/body height:100% + overflow-x:hidden can make body the scroller, not window. */
private scrollToTop(): void {
if (!this.isBrowser) {
return;
}
window.scrollTo(0, 0);
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
}

public getRouterOutletState(routerOutlet: RouterOutlet): string {
const routeData = routerOutlet.activatedRouteData['animation'];
return routeData ? routeData : 'rootPage';
Expand Down
7 changes: 5 additions & 2 deletions src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideRouter, withInMemoryScrolling } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient, withJsonpSupport } from '@angular/common/http';
import { AngularFireModule } from '@angular/fire/compat';
Expand All @@ -23,7 +23,10 @@ const isFirebaseConfigured =
!!firebaseConfig.appId;

const baseProviders = [
provideRouter(routes),
provideRouter(
routes,
withInMemoryScrolling({ scrollPositionRestoration: 'top' })
),
provideAnimations(),
provideHttpClient(withJsonpSupport()),
{
Expand Down
14 changes: 14 additions & 0 deletions src/app/routing/app-routing.module.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { TestBed } from "@angular/core/testing";
import { HttpClientTestingModule } from "@angular/common/http/testing";
import { ROUTER_CONFIGURATION } from "@angular/router";
import { RoutingModule } from "./app-routing.module";
import { RouterTestingModule } from "@angular/router/testing";

Expand All @@ -14,3 +15,16 @@ describe("RoutingModule", () => {
expect(RoutingModule).toBeDefined();
});
});

describe("RoutingModule scrollPositionRestoration", () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RoutingModule],
});
});

it("scrolls to the top on navigation", () => {
const config = TestBed.inject(ROUTER_CONFIGURATION);
expect(config.scrollPositionRestoration).toBe("top");
});
});
2 changes: 1 addition & 1 deletion src/app/routing/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { routes } from '../app.routes';
@NgModule({
exports: [RouterModule],
imports: [
RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' }),
RouterModule.forRoot(routes, { scrollPositionRestoration: 'top' }),
],
})
export class RoutingModule {}
Loading