Skip to content

Commit 3414316

Browse files
wKozajasonaden
authored andcommitted
feat(docs-infra): saves the scroll position before the change of location (#28037)
Issue #27916, #17308 PR Close #28037
1 parent 67a41d8 commit 3414316

4 files changed

Lines changed: 294 additions & 41 deletions

File tree

‎aio/src/app/app.component.spec.ts‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,13 @@ describe('AppComponent', () => {
169169

170170
expect(component.tocMaxHeight).toMatch(/^\d+\.\d{2}$/);
171171
});
172+
173+
it('should update `scrollService.updateScrollPositonInHistory()`', () => {
174+
const scrollService = fixture.debugElement.injector.get<ScrollService>(ScrollService);
175+
spyOn(scrollService, 'updateScrollPositionInHistory');
176+
component.onScroll();
177+
expect(scrollService.updateScrollPositionInHistory).toHaveBeenCalled();
178+
});
172179
});
173180

174181
describe('SideNav', () => {
@@ -461,11 +468,15 @@ describe('AppComponent', () => {
461468
let scrollService: ScrollService;
462469
let scrollSpy: jasmine.Spy;
463470
let scrollToTopSpy: jasmine.Spy;
471+
let scrollAfterRenderSpy: jasmine.Spy;
472+
let removeStoredScrollPositionSpy: jasmine.Spy;
464473

465474
beforeEach(() => {
466475
scrollService = fixture.debugElement.injector.get<ScrollService>(ScrollService);
467476
scrollSpy = spyOn(scrollService, 'scroll');
468477
scrollToTopSpy = spyOn(scrollService, 'scrollToTop');
478+
scrollAfterRenderSpy = spyOn(scrollService, 'scrollAfterRender');
479+
removeStoredScrollPositionSpy = spyOn(scrollService, 'removeStoredScrollPosition');
469480
});
470481

471482
it('should not scroll immediately when the docId (path) changes', () => {
@@ -510,33 +521,24 @@ describe('AppComponent', () => {
510521
expect(scrollSpy).toHaveBeenCalledTimes(1);
511522
});
512523

513-
it('should scroll to top when call `onDocRemoved` directly', () => {
514-
scrollToTopSpy.calls.reset();
515-
524+
it('should call `removeStoredScrollPosition` when call `onDocRemoved` directly', () => {
516525
component.onDocRemoved();
517-
expect(scrollToTopSpy).toHaveBeenCalled();
526+
expect(removeStoredScrollPositionSpy).toHaveBeenCalled();
518527
});
519528

520-
it('should scroll after a delay when call `onDocInserted` directly', fakeAsync(() => {
529+
it('should call `scrollAfterRender` when call `onDocInserted` directly', (() => {
521530
component.onDocInserted();
522-
expect(scrollSpy).not.toHaveBeenCalled();
523-
524-
tick(scrollDelay);
525-
expect(scrollSpy).toHaveBeenCalled();
531+
expect(scrollAfterRenderSpy).toHaveBeenCalledWith(scrollDelay);
526532
}));
527533

528-
it('should scroll (via `onDocInserted`) when finish navigating to a new doc', fakeAsync(() => {
529-
expect(scrollToTopSpy).not.toHaveBeenCalled();
530-
534+
it('should call `scrollAfterRender` (via `onDocInserted`) when navigate to a new Doc', fakeAsync(() => {
531535
locationService.go('guide/pipes');
532-
tick(1); // triggers the HTTP response for the document
536+
tick(1); // triggers the HTTP response for the document
533537
fixture.detectChanges(); // triggers the event that calls `onDocInserted`
534538

535-
expect(scrollToTopSpy).toHaveBeenCalled();
536-
expect(scrollSpy).not.toHaveBeenCalled();
539+
expect(scrollAfterRenderSpy).toHaveBeenCalledWith(scrollDelay);
537540

538-
tick(scrollDelay);
539-
expect(scrollSpy).toHaveBeenCalled();
541+
tick(500); // there are other outstanding timers in the AppComponent that are not relevant
540542
}));
541543
});
542544

‎aio/src/app/app.component.ts‎

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ export class AppComponent implements OnInit {
127127
}
128128
if (path === this.currentPath) {
129129
// scroll only if on same page (most likely a change to the hash)
130-
this.autoScroll();
130+
this.scrollService.scroll();
131131
} else {
132132
// don't scroll; leave that to `onDocRendered`
133133
this.currentPath = path;
@@ -187,11 +187,6 @@ export class AppComponent implements OnInit {
187187
.subscribe(() => this.updateShell());
188188
}
189189

190-
// Scroll to the anchor in the hash fragment or top of doc.
191-
autoScroll() {
192-
this.scrollService.scroll();
193-
}
194-
195190
onDocReady() {
196191
// About to transition to new view.
197192
this.isTransitioning = true;
@@ -204,9 +199,7 @@ export class AppComponent implements OnInit {
204199
}
205200

206201
onDocRemoved() {
207-
// The previous document has been removed.
208-
// Scroll to top to restore a clean visual state for the new document.
209-
this.scrollService.scrollToTop();
202+
this.scrollService.removeStoredScrollPosition();
210203
}
211204

212205
onDocInserted() {
@@ -216,9 +209,8 @@ export class AppComponent implements OnInit {
216209
// (e.g. sidenav, host classes) needs to happen asynchronously.
217210
setTimeout(() => this.updateShell());
218211

219-
// Scroll 500ms after the new document has been inserted into the doc-viewer.
220-
// The delay is to allow time for async layout to complete.
221-
setTimeout(() => this.autoScroll(), 500);
212+
// Scroll the good position depending on the context
213+
this.scrollService.scrollAfterRender(500);
222214
}
223215

224216
onDocRendered() {
@@ -256,7 +248,6 @@ export class AppComponent implements OnInit {
256248

257249
@HostListener('click', ['$event.target', '$event.button', '$event.ctrlKey', '$event.metaKey', '$event.altKey'])
258250
onClick(eventTarget: HTMLElement, button: number, ctrlKey: boolean, metaKey: boolean, altKey: boolean): boolean {
259-
260251
// Hide the search results if we clicked outside both the "search box" and the "search results"
261252
if (!this.searchElements.some(element => element.nativeElement.contains(eventTarget))) {
262253
this.hideSearchResults();
@@ -348,6 +339,9 @@ export class AppComponent implements OnInit {
348339
// Dynamically change height of table of contents container
349340
@HostListener('window:scroll')
350341
onScroll() {
342+
343+
this.scrollService.updateScrollPositionInHistory();
344+
351345
if (!this.tocMaxHeightOffset) {
352346
// Must wait until `mat-toolbar` is measurable.
353347
const el = this.hostElement.nativeElement as Element;

‎aio/src/app/shared/scroll.service.spec.ts‎

Lines changed: 160 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
import { ReflectiveInjector } from '@angular/core';
2-
import { PlatformLocation } from '@angular/common';
2+
import { Location, LocationStrategy, PlatformLocation, ViewportScroller } from '@angular/common';
33
import { DOCUMENT } from '@angular/common';
4+
import { MockLocationStrategy, SpyLocation } from '@angular/common/testing';
5+
import { fakeAsync, tick } from '@angular/core/testing';
46

57
import { ScrollService, topMargin } from './scroll.service';
68

79
describe('ScrollService', () => {
810
const topOfPageElem = {} as Element;
911
let injector: ReflectiveInjector;
1012
let document: MockDocument;
11-
let location: MockPlatformLocation;
13+
let platformLocation: MockPlatformLocation;
1214
let scrollService: ScrollService;
15+
let location: SpyLocation;
1316

1417
class MockPlatformLocation {
1518
hash: string;
@@ -27,19 +30,36 @@ describe('ScrollService', () => {
2730
scrollIntoView = jasmine.createSpy('Element scrollIntoView');
2831
}
2932

33+
const viewportScrollerStub = jasmine.createSpyObj(
34+
'viewportScroller',
35+
['getScrollPosition', 'scrollToPosition']);
36+
37+
3038
beforeEach(() => {
3139
spyOn(window, 'scrollBy');
3240
});
3341

3442
beforeEach(() => {
3543
injector = ReflectiveInjector.resolveAndCreate([
3644
ScrollService,
45+
{ provide: Location, useClass: SpyLocation },
3746
{ provide: DOCUMENT, useClass: MockDocument },
38-
{ provide: PlatformLocation, useClass: MockPlatformLocation }
47+
{ provide: PlatformLocation, useClass: MockPlatformLocation },
48+
{ provide: ViewportScroller, useValue: viewportScrollerStub },
49+
{ provide: LocationStrategy, useClass: MockLocationStrategy }
3950
]);
40-
location = injector.get(PlatformLocation);
51+
platformLocation = injector.get(PlatformLocation);
4152
document = injector.get(DOCUMENT);
4253
scrollService = injector.get(ScrollService);
54+
location = injector.get(Location);
55+
});
56+
57+
it('should set `scrollRestoration` to `manual` if supported', () => {
58+
if (scrollService.supportManualScrollRestoration) {
59+
expect(window.history.scrollRestoration).toBe('manual');
60+
} else {
61+
expect(window.history.scrollRestoration).toBeUndefined();
62+
}
4363
});
4464

4565
describe('#topOffset', () => {
@@ -107,7 +127,7 @@ describe('ScrollService', () => {
107127

108128
describe('#scroll', () => {
109129
it('should scroll to the top if there is no hash', () => {
110-
location.hash = '';
130+
platformLocation.hash = '';
111131

112132
const topOfPage = new MockElement();
113133
document.getElementById.and
@@ -118,7 +138,7 @@ describe('ScrollService', () => {
118138
});
119139

120140
it('should not scroll if the hash does not match an element id', () => {
121-
location.hash = 'not-found';
141+
platformLocation.hash = 'not-found';
122142
document.getElementById.and.returnValue(null);
123143

124144
scrollService.scroll();
@@ -128,7 +148,7 @@ describe('ScrollService', () => {
128148

129149
it('should scroll to the element whose id matches the hash', () => {
130150
const element = new MockElement();
131-
location.hash = 'some-id';
151+
platformLocation.hash = 'some-id';
132152
document.getElementById.and.returnValue(element);
133153

134154
scrollService.scroll();
@@ -139,7 +159,7 @@ describe('ScrollService', () => {
139159

140160
it('should scroll to the element whose id matches the hash with encoded characters', () => {
141161
const element = new MockElement();
142-
location.hash = '%F0%9F%91%8D'; // 👍
162+
platformLocation.hash = '%F0%9F%91%8D'; // 👍
143163
document.getElementById.and.returnValue(element);
144164

145165
scrollService.scroll();
@@ -210,4 +230,136 @@ describe('ScrollService', () => {
210230
});
211231
});
212232

233+
describe('#isLocationWithHash', () => {
234+
it('should return true when the location has a hash', () => {
235+
platformLocation.hash = 'anchor';
236+
expect(scrollService.isLocationWithHash()).toBe(true);
237+
});
238+
239+
it('should return false when the location has no hash', () => {
240+
platformLocation.hash = '';
241+
expect(scrollService.isLocationWithHash()).toBe(false);
242+
});
243+
});
244+
245+
describe('#needToFixScrollPosition', async() => {
246+
it('should return true when popState event was fired after a back navigation if the browser supports ' +
247+
'scrollRestoration`. Otherwise, needToFixScrollPosition() returns false', () => {
248+
249+
if (scrollService.supportManualScrollRestoration) {
250+
location.go('/initial-url1');
251+
// We simulate a scroll down
252+
location.replaceState('/initial-url1', 'hack', {scrollPosition: [2000, 0]});
253+
location.go('/initial-url2');
254+
location.back();
255+
256+
expect(scrollService.popStateFired).toBe(true);
257+
expect(scrollService.scrollPosition).toEqual([2000, 0]);
258+
expect(scrollService.needToFixScrollPosition()).toBe(true);
259+
} else {
260+
location.go('/initial-url1');
261+
location.go('/initial-url2');
262+
location.back();
263+
264+
expect(scrollService.popStateFired).toBe(false); // popStateFired is always false
265+
expect(scrollService.scrollPosition).toEqual([0, 0]); // scrollPosition always equals [0, 0]
266+
expect(scrollService.needToFixScrollPosition()).toBe(false);
267+
}
268+
269+
});
270+
271+
it('should return true when popState event was fired after a forward navigation if the browser supports ' +
272+
'scrollRestoration`. Otherwise, needToFixScrollPosition() returns false', () => {
273+
274+
if (scrollService.supportManualScrollRestoration) {
275+
location.go('/initial-url1');
276+
location.go('/initial-url2');
277+
// We simulate a scroll down
278+
location.replaceState('/initial-url1', 'hack', {scrollPosition: [2000, 0]});
279+
280+
location.back();
281+
scrollService.popStateFired = false;
282+
scrollService.scrollPosition = [0, 0];
283+
location.forward();
284+
285+
expect(scrollService.popStateFired).toBe(true);
286+
expect(scrollService.scrollPosition).toEqual([2000, 0]);
287+
expect(scrollService.needToFixScrollPosition()).toBe(true);
288+
} else {
289+
location.go('/initial-url1');
290+
location.go('/initial-url2');
291+
location.back();
292+
location.forward();
293+
294+
expect(scrollService.popStateFired).toBe(false); // popStateFired is always false
295+
expect(scrollService.scrollPosition).toEqual([0, 0]); // scrollPosition always equals [0, 0]
296+
expect(scrollService.needToFixScrollPosition()).toBe(false);
297+
}
298+
299+
});
300+
});
301+
302+
describe('#scrollAfterRender', async() => {
303+
304+
let scrollSpy: jasmine.Spy;
305+
let scrollToTopSpy: jasmine.Spy;
306+
let needToFixScrollPositionSpy: jasmine.Spy;
307+
let scrollToPosition: jasmine.Spy;
308+
let isLocationWithHashSpy: jasmine.Spy;
309+
let getStoredScrollPositionSpy: jasmine.Spy;
310+
const scrollDelay = 500;
311+
312+
beforeEach(() => {
313+
scrollSpy = spyOn(scrollService, 'scroll');
314+
scrollToTopSpy = spyOn(scrollService, 'scrollToTop');
315+
scrollToPosition = spyOn(scrollService, 'scrollToPosition');
316+
needToFixScrollPositionSpy = spyOn(scrollService, 'needToFixScrollPosition');
317+
getStoredScrollPositionSpy = spyOn(scrollService, 'getStoredScrollPosition');
318+
isLocationWithHashSpy = spyOn(scrollService, 'isLocationWithHash');
319+
});
320+
321+
322+
it('should call `scroll` when we navigate to a location with anchor', fakeAsync(() => {
323+
needToFixScrollPositionSpy.and.returnValue(false);
324+
getStoredScrollPositionSpy.and.returnValue(null);
325+
isLocationWithHashSpy.and.returnValue(true);
326+
327+
scrollService.scrollAfterRender(scrollDelay);
328+
329+
expect(scrollSpy).not.toHaveBeenCalled();
330+
tick(scrollDelay);
331+
expect(scrollSpy).toHaveBeenCalled();
332+
}));
333+
334+
it('should call `scrollToTop` when we navigate to a location without anchor', fakeAsync(() => {
335+
needToFixScrollPositionSpy.and.returnValue(false);
336+
getStoredScrollPositionSpy.and.returnValue(null);
337+
isLocationWithHashSpy.and.returnValue(false);
338+
339+
scrollService.scrollAfterRender(scrollDelay);
340+
341+
expect(scrollToTopSpy).toHaveBeenCalled();
342+
tick(scrollDelay);
343+
expect(scrollSpy).not.toHaveBeenCalled();
344+
}));
345+
346+
it('should call `viewportScroller.scrollToPosition` when we reload a page', fakeAsync(() => {
347+
getStoredScrollPositionSpy.and.returnValue([0, 1000]);
348+
349+
scrollService.scrollAfterRender(scrollDelay);
350+
351+
expect(viewportScrollerStub.scrollToPosition).toHaveBeenCalled();
352+
expect(getStoredScrollPositionSpy).toHaveBeenCalled();
353+
}));
354+
355+
it('should call `scrollToPosition` after a popState', fakeAsync(() => {
356+
needToFixScrollPositionSpy.and.returnValue(true);
357+
getStoredScrollPositionSpy.and.returnValue(null);
358+
scrollService.scrollAfterRender(scrollDelay);
359+
expect(scrollToPosition).toHaveBeenCalled();
360+
tick(scrollDelay);
361+
expect(scrollSpy).not.toHaveBeenCalled();
362+
expect(scrollToTopSpy).not.toHaveBeenCalled();
363+
}));
364+
});
213365
});

0 commit comments

Comments
 (0)