This is an elegant solution for Aurelia integration. The curious thing is that it’s only possible to define this at the root router config, and the pipeline class seems to only execute on the top level route, eliminating more fine grain scrollTo
at specific child routes. I tried adding a scrollReset
setting to the routes, and only when I added it to the top-level route did my pipeline pick it up:
Root routes:
import { PLATFORM } from 'aurelia-pal';
import { Router, RouterConfiguration, ConfiguresRouter, PipelineStep, NavigationInstruction, Next } from 'aurelia-router';
class PostNavigationScrollUp implements PipelineStep {
run(instruction: NavigationInstruction, next: Next) {
console.log(instruction);
if (instruction.config.settings.scrollReset) {
window.scrollTo(0, 0);
}
return next();
}
}
export class App implements ConfiguresRouter {
private router: Router;
configureRouter(config: RouterConfiguration, router: Router) {
config.options.pushState = true;
config.options.root = '/';
config.map([
{ route: ['home'], name: 'home', moduleId: PLATFORM.moduleName('./home/index'), nav: true, title: 'Home' },
/* "scrollReset: true" WORKS HERE */
{ route: ['u/:username'], name: 'user', moduleId: PLATFORM.moduleName('./user/index'), nav: false, title: 'User', settings: { scrollReset: true}},
{ route: '', redirect: 'home' }
]);
this.router = router;
config.addPipelineStep('postcomplete', PostNavigationScrollUp);
}
}
Child routes:
import { PLATFORM } from 'aurelia-pal';
import { RouterConfiguration, Router, RouteConfig } from 'aurelia-router';
export class UserRootView {
private router: Router;
configureRouter(config: RouterConfiguration, router: Router) {
this.router = router;
config.map([
{ route: [''], name: 'profile', moduleId: PLATFORM.moduleName('./profile.component'), nav: false, title: 'Timeline'},
/* "scrollReset: true" DOES NOT WORK HERE */
{ route: ['p/:slug'], name: 'post', moduleId: PLATFORM.moduleName('./post.component'), nav: false, title: 'Post', settings: { scrollReset: true}}
]);
}
}
There is only one console.log
output, and that’s for the parent route:
NavigationInstruction {plan: null, options: {…}, fragment: '/u/someuser/p/random-post-slug', queryString: '', config: {…}, …}
config:
hasChildRouter: true
moduleId: "./user/index"
name: "user"
nav: false
navModel: NavModel {isActive: true, title: 'User', href: undefined, relativeHref: 'u/:username', settings: {…}, …}
navigationStrategy: undefined
route: "u/:username/*childRoute"
settings: {scrollReset: true}
title: "User"
viewPorts: {default: {…}}
[[Prototype]]: Object
fragment: "/u/someuser/p/random-post-slug"
Alternatively, window.scrollTo()
can just be called in the activate()
method of the end view component.
That’s by experience with this.